docs: use "Returns:" consistently
[platform/upstream/glib.git] / glib / ghash.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
16  */
17
18 /*
19  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
20  * file for a list of people on the GLib Team.  See the ChangeLog
21  * files for a list of changes.  These files are distributed with
22  * GLib at ftp://ftp.gtk.org/pub/gtk/.
23  */
24
25 /*
26  * MT safe
27  */
28
29 #include "config.h"
30
31 #include <string.h>  /* memset */
32
33 #include "ghash.h"
34
35 #include "glib-private.h"
36 #include "gstrfuncs.h"
37 #include "gatomic.h"
38 #include "gtestutils.h"
39 #include "gslice.h"
40
41
42 /**
43  * SECTION:hash_tables
44  * @title: Hash Tables
45  * @short_description: associations between keys and values so that
46  *     given a key the value can be found quickly
47  *
48  * A #GHashTable provides associations between keys and values which is
49  * optimized so that given a key, the associated value can be found
50  * very quickly.
51  *
52  * Note that neither keys nor values are copied when inserted into the
53  * #GHashTable, so they must exist for the lifetime of the #GHashTable.
54  * This means that the use of static strings is OK, but temporary
55  * strings (i.e. those created in buffers and those returned by GTK+
56  * widgets) should be copied with g_strdup() before being inserted.
57  *
58  * If keys or values are dynamically allocated, you must be careful to
59  * ensure that they are freed when they are removed from the
60  * #GHashTable, and also when they are overwritten by new insertions
61  * into the #GHashTable. It is also not advisable to mix static strings
62  * and dynamically-allocated strings in a #GHashTable, because it then
63  * becomes difficult to determine whether the string should be freed.
64  *
65  * To create a #GHashTable, use g_hash_table_new().
66  *
67  * To insert a key and value into a #GHashTable, use
68  * g_hash_table_insert().
69  *
70  * To lookup a value corresponding to a given key, use
71  * g_hash_table_lookup() and g_hash_table_lookup_extended().
72  *
73  * g_hash_table_lookup_extended() can also be used to simply
74  * check if a key is present in the hash table.
75  *
76  * To remove a key and value, use g_hash_table_remove().
77  *
78  * To call a function for each key and value pair use
79  * g_hash_table_foreach() or use a iterator to iterate over the
80  * key/value pairs in the hash table, see #GHashTableIter.
81  *
82  * To destroy a #GHashTable use g_hash_table_destroy().
83  *
84  * A common use-case for hash tables is to store information about a
85  * set of keys, without associating any particular value with each
86  * key. GHashTable optimizes one way of doing so: If you store only
87  * key-value pairs where key == value, then GHashTable does not
88  * allocate memory to store the values, which can be a considerable
89  * space saving, if your set is large. The functions
90  * g_hash_table_add() and g_hash_table_contains() are designed to be
91  * used when using #GHashTable this way.
92  */
93
94 /**
95  * GHashTable:
96  *
97  * The #GHashTable struct is an opaque data structure to represent a
98  * [Hash Table][glib-Hash-Tables]. It should only be accessed via the
99  * following functions.
100  */
101
102 /**
103  * GHashFunc:
104  * @key: a key
105  *
106  * Specifies the type of the hash function which is passed to
107  * g_hash_table_new() when a #GHashTable is created.
108  *
109  * The function is passed a key and should return a #guint hash value.
110  * The functions g_direct_hash(), g_int_hash() and g_str_hash() provide
111  * hash functions which can be used when the key is a #gpointer, #gint*,
112  * and #gchar* respectively.
113  *
114  * g_direct_hash() is also the appropriate hash function for keys
115  * of the form `GINT_TO_POINTER (n)` (or similar macros).
116  *
117  * <!-- FIXME: Need more here. --> A good hash functions should produce
118  * hash values that are evenly distributed over a fairly large range.
119  * The modulus is taken with the hash table size (a prime number) to
120  * find the 'bucket' to place each key into. The function should also
121  * be very fast, since it is called for each key lookup.
122  *
123  * Note that the hash functions provided by GLib have these qualities,
124  * but are not particularly robust against manufactured keys that
125  * cause hash collisions. Therefore, you should consider choosing
126  * a more secure hash function when using a GHashTable with keys
127  * that originate in untrusted data (such as HTTP requests).
128  * Using g_str_hash() in that situation might make your application
129  * vulerable to
130  * [Algorithmic Complexity Attacks](https://lwn.net/Articles/474912/).
131  *
132  * The key to choosing a good hash is unpredictability.  Even
133  * cryptographic hashes are very easy to find collisions for when the
134  * remainder is taken modulo a somewhat predictable prime number.  There
135  * must be an element of randomness that an attacker is unable to guess.
136  *
137  * Returns: the hash value corresponding to the key
138  */
139
140 /**
141  * GHFunc:
142  * @key: a key
143  * @value: the value corresponding to the key
144  * @user_data: user data passed to g_hash_table_foreach()
145  *
146  * Specifies the type of the function passed to g_hash_table_foreach().
147  * It is called with each key/value pair, together with the @user_data
148  * parameter which is passed to g_hash_table_foreach().
149  */
150
151 /**
152  * GHRFunc:
153  * @key: a key
154  * @value: the value associated with the key
155  * @user_data: user data passed to g_hash_table_remove()
156  *
157  * Specifies the type of the function passed to
158  * g_hash_table_foreach_remove(). It is called with each key/value
159  * pair, together with the @user_data parameter passed to
160  * g_hash_table_foreach_remove(). It should return %TRUE if the
161  * key/value pair should be removed from the #GHashTable.
162  *
163  * Returns: %TRUE if the key/value pair should be removed from the
164  *     #GHashTable
165  */
166
167 /**
168  * GEqualFunc:
169  * @a: a value
170  * @b: a value to compare with
171  *
172  * Specifies the type of a function used to test two values for
173  * equality. The function should return %TRUE if both values are equal
174  * and %FALSE otherwise.
175  *
176  * Returns: %TRUE if @a = @b; %FALSE otherwise
177  */
178
179 /**
180  * GHashTableIter:
181  *
182  * A GHashTableIter structure represents an iterator that can be used
183  * to iterate over the elements of a #GHashTable. GHashTableIter
184  * structures are typically allocated on the stack and then initialized
185  * with g_hash_table_iter_init().
186  */
187
188 /**
189  * g_hash_table_freeze:
190  * @hash_table: a #GHashTable
191  *
192  * This function is deprecated and will be removed in the next major
193  * release of GLib. It does nothing.
194  */
195
196 /**
197  * g_hash_table_thaw:
198  * @hash_table: a #GHashTable
199  *
200  * This function is deprecated and will be removed in the next major
201  * release of GLib. It does nothing.
202  */
203
204 #define HASH_TABLE_MIN_SHIFT 3  /* 1 << 3 == 8 buckets */
205
206 #define UNUSED_HASH_VALUE 0
207 #define TOMBSTONE_HASH_VALUE 1
208 #define HASH_IS_UNUSED(h_) ((h_) == UNUSED_HASH_VALUE)
209 #define HASH_IS_TOMBSTONE(h_) ((h_) == TOMBSTONE_HASH_VALUE)
210 #define HASH_IS_REAL(h_) ((h_) >= 2)
211
212 struct _GHashTable
213 {
214   gint             size;
215   gint             mod;
216   guint            mask;
217   gint             nnodes;
218   gint             noccupied;  /* nnodes + tombstones */
219
220   gpointer        *keys;
221   guint           *hashes;
222   gpointer        *values;
223
224   GHashFunc        hash_func;
225   GEqualFunc       key_equal_func;
226   gint             ref_count;
227 #ifndef G_DISABLE_ASSERT
228   /*
229    * Tracks the structure of the hash table, not its contents: is only
230    * incremented when a node is added or removed (is not incremented
231    * when the key or data of a node is modified).
232    */
233   int              version;
234 #endif
235   GDestroyNotify   key_destroy_func;
236   GDestroyNotify   value_destroy_func;
237 };
238
239 typedef struct
240 {
241   GHashTable  *hash_table;
242   gpointer     dummy1;
243   gpointer     dummy2;
244   int          position;
245   gboolean     dummy3;
246   int          version;
247 } RealIter;
248
249 G_STATIC_ASSERT (sizeof (GHashTableIter) == sizeof (RealIter));
250 G_STATIC_ASSERT (_g_alignof (GHashTableIter) >= _g_alignof (RealIter));
251
252 /* Each table size has an associated prime modulo (the first prime
253  * lower than the table size) used to find the initial bucket. Probing
254  * then works modulo 2^n. The prime modulo is necessary to get a
255  * good distribution with poor hash functions.
256  */
257 static const gint prime_mod [] =
258 {
259   1,          /* For 1 << 0 */
260   2,
261   3,
262   7,
263   13,
264   31,
265   61,
266   127,
267   251,
268   509,
269   1021,
270   2039,
271   4093,
272   8191,
273   16381,
274   32749,
275   65521,      /* For 1 << 16 */
276   131071,
277   262139,
278   524287,
279   1048573,
280   2097143,
281   4194301,
282   8388593,
283   16777213,
284   33554393,
285   67108859,
286   134217689,
287   268435399,
288   536870909,
289   1073741789,
290   2147483647  /* For 1 << 31 */
291 };
292
293 static void
294 g_hash_table_set_shift (GHashTable *hash_table, gint shift)
295 {
296   gint i;
297   guint mask = 0;
298
299   hash_table->size = 1 << shift;
300   hash_table->mod  = prime_mod [shift];
301
302   for (i = 0; i < shift; i++)
303     {
304       mask <<= 1;
305       mask |= 1;
306     }
307
308   hash_table->mask = mask;
309 }
310
311 static gint
312 g_hash_table_find_closest_shift (gint n)
313 {
314   gint i;
315
316   for (i = 0; n; i++)
317     n >>= 1;
318
319   return i;
320 }
321
322 static void
323 g_hash_table_set_shift_from_size (GHashTable *hash_table, gint size)
324 {
325   gint shift;
326
327   shift = g_hash_table_find_closest_shift (size);
328   shift = MAX (shift, HASH_TABLE_MIN_SHIFT);
329
330   g_hash_table_set_shift (hash_table, shift);
331 }
332
333 /*
334  * g_hash_table_lookup_node:
335  * @hash_table: our #GHashTable
336  * @key: the key to lookup against
337  * @hash_return: key hash return location
338  *
339  * Performs a lookup in the hash table, preserving extra information
340  * usually needed for insertion.
341  *
342  * This function first computes the hash value of the key using the
343  * user's hash function.
344  *
345  * If an entry in the table matching @key is found then this function
346  * returns the index of that entry in the table, and if not, the
347  * index of an unused node (empty or tombstone) where the key can be
348  * inserted.
349  *
350  * The computed hash value is returned in the variable pointed to
351  * by @hash_return. This is to save insertions from having to compute
352  * the hash record again for the new record.
353  *
354  * Returns: index of the described node
355  */
356 static inline guint
357 g_hash_table_lookup_node (GHashTable    *hash_table,
358                           gconstpointer  key,
359                           guint         *hash_return)
360 {
361   guint node_index;
362   guint node_hash;
363   guint hash_value;
364   guint first_tombstone = 0;
365   gboolean have_tombstone = FALSE;
366   guint step = 0;
367
368   hash_value = hash_table->hash_func (key);
369   if (G_UNLIKELY (!HASH_IS_REAL (hash_value)))
370     hash_value = 2;
371
372   *hash_return = hash_value;
373
374   node_index = hash_value % hash_table->mod;
375   node_hash = hash_table->hashes[node_index];
376
377   while (!HASH_IS_UNUSED (node_hash))
378     {
379       /* We first check if our full hash values
380        * are equal so we can avoid calling the full-blown
381        * key equality function in most cases.
382        */
383       if (node_hash == hash_value)
384         {
385           gpointer node_key = hash_table->keys[node_index];
386
387           if (hash_table->key_equal_func)
388             {
389               if (hash_table->key_equal_func (node_key, key))
390                 return node_index;
391             }
392           else if (node_key == key)
393             {
394               return node_index;
395             }
396         }
397       else if (HASH_IS_TOMBSTONE (node_hash) && !have_tombstone)
398         {
399           first_tombstone = node_index;
400           have_tombstone = TRUE;
401         }
402
403       step++;
404       node_index += step;
405       node_index &= hash_table->mask;
406       node_hash = hash_table->hashes[node_index];
407     }
408
409   if (have_tombstone)
410     return first_tombstone;
411
412   return node_index;
413 }
414
415 /*
416  * g_hash_table_remove_node:
417  * @hash_table: our #GHashTable
418  * @node: pointer to node to remove
419  * @notify: %TRUE if the destroy notify handlers are to be called
420  *
421  * Removes a node from the hash table and updates the node count.
422  * The node is replaced by a tombstone. No table resize is performed.
423  *
424  * If @notify is %TRUE then the destroy notify functions are called
425  * for the key and value of the hash node.
426  */
427 static void
428 g_hash_table_remove_node (GHashTable   *hash_table,
429                           gint          i,
430                           gboolean      notify)
431 {
432   gpointer key;
433   gpointer value;
434
435   key = hash_table->keys[i];
436   value = hash_table->values[i];
437
438   /* Erect tombstone */
439   hash_table->hashes[i] = TOMBSTONE_HASH_VALUE;
440
441   /* Be GC friendly */
442   hash_table->keys[i] = NULL;
443   hash_table->values[i] = NULL;
444
445   hash_table->nnodes--;
446
447   if (notify && hash_table->key_destroy_func)
448     hash_table->key_destroy_func (key);
449
450   if (notify && hash_table->value_destroy_func)
451     hash_table->value_destroy_func (value);
452
453 }
454
455 /*
456  * g_hash_table_remove_all_nodes:
457  * @hash_table: our #GHashTable
458  * @notify: %TRUE if the destroy notify handlers are to be called
459  *
460  * Removes all nodes from the table.  Since this may be a precursor to
461  * freeing the table entirely, no resize is performed.
462  *
463  * If @notify is %TRUE then the destroy notify functions are called
464  * for the key and value of the hash node.
465  */
466 static void
467 g_hash_table_remove_all_nodes (GHashTable *hash_table,
468                                gboolean    notify)
469 {
470   int i;
471   gpointer key;
472   gpointer value;
473
474   hash_table->nnodes = 0;
475   hash_table->noccupied = 0;
476
477   if (!notify ||
478       (hash_table->key_destroy_func == NULL &&
479        hash_table->value_destroy_func == NULL))
480     {
481       memset (hash_table->hashes, 0, hash_table->size * sizeof (guint));
482       memset (hash_table->keys, 0, hash_table->size * sizeof (gpointer));
483       memset (hash_table->values, 0, hash_table->size * sizeof (gpointer));
484
485       return;
486     }
487
488   for (i = 0; i < hash_table->size; i++)
489     {
490       if (HASH_IS_REAL (hash_table->hashes[i]))
491         {
492           key = hash_table->keys[i];
493           value = hash_table->values[i];
494
495           hash_table->hashes[i] = UNUSED_HASH_VALUE;
496           hash_table->keys[i] = NULL;
497           hash_table->values[i] = NULL;
498
499           if (hash_table->key_destroy_func != NULL)
500             hash_table->key_destroy_func (key);
501
502           if (hash_table->value_destroy_func != NULL)
503             hash_table->value_destroy_func (value);
504         }
505       else if (HASH_IS_TOMBSTONE (hash_table->hashes[i]))
506         {
507           hash_table->hashes[i] = UNUSED_HASH_VALUE;
508         }
509     }
510 }
511
512 /*
513  * g_hash_table_resize:
514  * @hash_table: our #GHashTable
515  *
516  * Resizes the hash table to the optimal size based on the number of
517  * nodes currently held. If you call this function then a resize will
518  * occur, even if one does not need to occur.
519  * Use g_hash_table_maybe_resize() instead.
520  *
521  * This function may "resize" the hash table to its current size, with
522  * the side effect of cleaning up tombstones and otherwise optimizing
523  * the probe sequences.
524  */
525 static void
526 g_hash_table_resize (GHashTable *hash_table)
527 {
528   gpointer *new_keys;
529   gpointer *new_values;
530   guint *new_hashes;
531   gint old_size;
532   gint i;
533
534   old_size = hash_table->size;
535   g_hash_table_set_shift_from_size (hash_table, hash_table->nnodes * 2);
536
537   new_keys = g_new0 (gpointer, hash_table->size);
538   if (hash_table->keys == hash_table->values)
539     new_values = new_keys;
540   else
541     new_values = g_new0 (gpointer, hash_table->size);
542   new_hashes = g_new0 (guint, hash_table->size);
543
544   for (i = 0; i < old_size; i++)
545     {
546       guint node_hash = hash_table->hashes[i];
547       guint hash_val;
548       guint step = 0;
549
550       if (!HASH_IS_REAL (node_hash))
551         continue;
552
553       hash_val = node_hash % hash_table->mod;
554
555       while (!HASH_IS_UNUSED (new_hashes[hash_val]))
556         {
557           step++;
558           hash_val += step;
559           hash_val &= hash_table->mask;
560         }
561
562       new_hashes[hash_val] = hash_table->hashes[i];
563       new_keys[hash_val] = hash_table->keys[i];
564       new_values[hash_val] = hash_table->values[i];
565     }
566
567   if (hash_table->keys != hash_table->values)
568     g_free (hash_table->values);
569
570   g_free (hash_table->keys);
571   g_free (hash_table->hashes);
572
573   hash_table->keys = new_keys;
574   hash_table->values = new_values;
575   hash_table->hashes = new_hashes;
576
577   hash_table->noccupied = hash_table->nnodes;
578 }
579
580 /*
581  * g_hash_table_maybe_resize:
582  * @hash_table: our #GHashTable
583  *
584  * Resizes the hash table, if needed.
585  *
586  * Essentially, calls g_hash_table_resize() if the table has strayed
587  * too far from its ideal size for its number of nodes.
588  */
589 static inline void
590 g_hash_table_maybe_resize (GHashTable *hash_table)
591 {
592   gint noccupied = hash_table->noccupied;
593   gint size = hash_table->size;
594
595   if ((size > hash_table->nnodes * 4 && size > 1 << HASH_TABLE_MIN_SHIFT) ||
596       (size <= noccupied + (noccupied / 16)))
597     g_hash_table_resize (hash_table);
598 }
599
600 /**
601  * g_hash_table_new:
602  * @hash_func: a function to create a hash value from a key
603  * @key_equal_func: a function to check two keys for equality
604  *
605  * Creates a new #GHashTable with a reference count of 1.
606  *
607  * Hash values returned by @hash_func are used to determine where keys
608  * are stored within the #GHashTable data structure. The g_direct_hash(),
609  * g_int_hash(), g_int64_hash(), g_double_hash() and g_str_hash()
610  * functions are provided for some common types of keys.
611  * If @hash_func is %NULL, g_direct_hash() is used.
612  *
613  * @key_equal_func is used when looking up keys in the #GHashTable.
614  * The g_direct_equal(), g_int_equal(), g_int64_equal(), g_double_equal()
615  * and g_str_equal() functions are provided for the most common types
616  * of keys. If @key_equal_func is %NULL, keys are compared directly in
617  * a similar fashion to g_direct_equal(), but without the overhead of
618  * a function call.
619  *
620  * Returns: a new #GHashTable
621  */
622 GHashTable *
623 g_hash_table_new (GHashFunc  hash_func,
624                   GEqualFunc key_equal_func)
625 {
626   return g_hash_table_new_full (hash_func, key_equal_func, NULL, NULL);
627 }
628
629
630 /**
631  * g_hash_table_new_full:
632  * @hash_func: a function to create a hash value from a key
633  * @key_equal_func: a function to check two keys for equality
634  * @key_destroy_func: (allow-none): a function to free the memory allocated for the key
635  *     used when removing the entry from the #GHashTable, or %NULL
636  *     if you don't want to supply such a function.
637  * @value_destroy_func: (allow-none): a function to free the memory allocated for the
638  *     value used when removing the entry from the #GHashTable, or %NULL
639  *     if you don't want to supply such a function.
640  *
641  * Creates a new #GHashTable like g_hash_table_new() with a reference
642  * count of 1 and allows to specify functions to free the memory
643  * allocated for the key and value that get called when removing the
644  * entry from the #GHashTable.
645  *
646  * Returns: a new #GHashTable
647  */
648 GHashTable *
649 g_hash_table_new_full (GHashFunc      hash_func,
650                        GEqualFunc     key_equal_func,
651                        GDestroyNotify key_destroy_func,
652                        GDestroyNotify value_destroy_func)
653 {
654   GHashTable *hash_table;
655
656   hash_table = g_slice_new (GHashTable);
657   g_hash_table_set_shift (hash_table, HASH_TABLE_MIN_SHIFT);
658   hash_table->nnodes             = 0;
659   hash_table->noccupied          = 0;
660   hash_table->hash_func          = hash_func ? hash_func : g_direct_hash;
661   hash_table->key_equal_func     = key_equal_func;
662   hash_table->ref_count          = 1;
663 #ifndef G_DISABLE_ASSERT
664   hash_table->version            = 0;
665 #endif
666   hash_table->key_destroy_func   = key_destroy_func;
667   hash_table->value_destroy_func = value_destroy_func;
668   hash_table->keys               = g_new0 (gpointer, hash_table->size);
669   hash_table->values             = hash_table->keys;
670   hash_table->hashes             = g_new0 (guint, hash_table->size);
671
672   return hash_table;
673 }
674
675 /**
676  * g_hash_table_iter_init:
677  * @iter: an uninitialized #GHashTableIter
678  * @hash_table: a #GHashTable
679  *
680  * Initializes a key/value pair iterator and associates it with
681  * @hash_table. Modifying the hash table after calling this function
682  * invalidates the returned iterator.
683  * |[<!-- language="C" -->
684  * GHashTableIter iter;
685  * gpointer key, value;
686  *
687  * g_hash_table_iter_init (&iter, hash_table);
688  * while (g_hash_table_iter_next (&iter, &key, &value))
689  *   {
690  *     // do something with key and value
691  *   }
692  * ]|
693  *
694  * Since: 2.16
695  */
696 void
697 g_hash_table_iter_init (GHashTableIter *iter,
698                         GHashTable     *hash_table)
699 {
700   RealIter *ri = (RealIter *) iter;
701
702   g_return_if_fail (iter != NULL);
703   g_return_if_fail (hash_table != NULL);
704
705   ri->hash_table = hash_table;
706   ri->position = -1;
707 #ifndef G_DISABLE_ASSERT
708   ri->version = hash_table->version;
709 #endif
710 }
711
712 /**
713  * g_hash_table_iter_next:
714  * @iter: an initialized #GHashTableIter
715  * @key: (allow-none): a location to store the key, or %NULL
716  * @value: (allow-none): a location to store the value, or %NULL
717  *
718  * Advances @iter and retrieves the key and/or value that are now
719  * pointed to as a result of this advancement. If %FALSE is returned,
720  * @key and @value are not set, and the iterator becomes invalid.
721  *
722  * Returns: %FALSE if the end of the #GHashTable has been reached.
723  *
724  * Since: 2.16
725  */
726 gboolean
727 g_hash_table_iter_next (GHashTableIter *iter,
728                         gpointer       *key,
729                         gpointer       *value)
730 {
731   RealIter *ri = (RealIter *) iter;
732   gint position;
733
734   g_return_val_if_fail (iter != NULL, FALSE);
735 #ifndef G_DISABLE_ASSERT
736   g_return_val_if_fail (ri->version == ri->hash_table->version, FALSE);
737 #endif
738   g_return_val_if_fail (ri->position < ri->hash_table->size, FALSE);
739
740   position = ri->position;
741
742   do
743     {
744       position++;
745       if (position >= ri->hash_table->size)
746         {
747           ri->position = position;
748           return FALSE;
749         }
750     }
751   while (!HASH_IS_REAL (ri->hash_table->hashes[position]));
752
753   if (key != NULL)
754     *key = ri->hash_table->keys[position];
755   if (value != NULL)
756     *value = ri->hash_table->values[position];
757
758   ri->position = position;
759   return TRUE;
760 }
761
762 /**
763  * g_hash_table_iter_get_hash_table:
764  * @iter: an initialized #GHashTableIter
765  *
766  * Returns the #GHashTable associated with @iter.
767  *
768  * Returns: the #GHashTable associated with @iter.
769  *
770  * Since: 2.16
771  */
772 GHashTable *
773 g_hash_table_iter_get_hash_table (GHashTableIter *iter)
774 {
775   g_return_val_if_fail (iter != NULL, NULL);
776
777   return ((RealIter *) iter)->hash_table;
778 }
779
780 static void
781 iter_remove_or_steal (RealIter *ri, gboolean notify)
782 {
783   g_return_if_fail (ri != NULL);
784 #ifndef G_DISABLE_ASSERT
785   g_return_if_fail (ri->version == ri->hash_table->version);
786 #endif
787   g_return_if_fail (ri->position >= 0);
788   g_return_if_fail (ri->position < ri->hash_table->size);
789
790   g_hash_table_remove_node (ri->hash_table, ri->position, notify);
791
792 #ifndef G_DISABLE_ASSERT
793   ri->version++;
794   ri->hash_table->version++;
795 #endif
796 }
797
798 /**
799  * g_hash_table_iter_remove:
800  * @iter: an initialized #GHashTableIter
801  *
802  * Removes the key/value pair currently pointed to by the iterator
803  * from its associated #GHashTable. Can only be called after
804  * g_hash_table_iter_next() returned %TRUE, and cannot be called
805  * more than once for the same key/value pair.
806  *
807  * If the #GHashTable was created using g_hash_table_new_full(),
808  * the key and value are freed using the supplied destroy functions,
809  * otherwise you have to make sure that any dynamically allocated
810  * values are freed yourself.
811  *
812  * Since: 2.16
813  */
814 void
815 g_hash_table_iter_remove (GHashTableIter *iter)
816 {
817   iter_remove_or_steal ((RealIter *) iter, TRUE);
818 }
819
820 /*
821  * g_hash_table_insert_node:
822  * @hash_table: our #GHashTable
823  * @node_index: pointer to node to insert/replace
824  * @key_hash: key hash
825  * @key: (allow-none): key to replace with, or %NULL
826  * @value: value to replace with
827  * @keep_new_key: whether to replace the key in the node with @key
828  * @reusing_key: whether @key was taken out of the existing node
829  *
830  * Inserts a value at @node_index in the hash table and updates it.
831  *
832  * If @key has been taken out of the existing node (ie it is not
833  * passed in via a g_hash_table_insert/replace) call, then @reusing_key
834  * should be %TRUE.
835  *
836  * Returns: %TRUE if the key did not exist yet
837  */
838 static gboolean
839 g_hash_table_insert_node (GHashTable *hash_table,
840                           guint       node_index,
841                           guint       key_hash,
842                           gpointer    new_key,
843                           gpointer    new_value,
844                           gboolean    keep_new_key,
845                           gboolean    reusing_key)
846 {
847   gboolean already_exists;
848   guint old_hash;
849   gpointer key_to_free = NULL;
850   gpointer value_to_free = NULL;
851
852   old_hash = hash_table->hashes[node_index];
853   already_exists = HASH_IS_REAL (old_hash);
854
855   /* Proceed in three steps.  First, deal with the key because it is the
856    * most complicated.  Then consider if we need to split the table in
857    * two (because writing the value will result in the set invariant
858    * becoming broken).  Then deal with the value.
859    *
860    * There are three cases for the key:
861    *
862    *  - entry already exists in table, reusing key:
863    *    free the just-passed-in new_key and use the existing value
864    *
865    *  - entry already exists in table, not reusing key:
866    *    free the entry in the table, use the new key
867    *
868    *  - entry not already in table:
869    *    use the new key, free nothing
870    *
871    * We update the hash at the same time...
872    */
873   if (already_exists)
874     {
875       /* Note: we must record the old value before writing the new key
876        * because we might change the value in the event that the two
877        * arrays are shared.
878        */
879       value_to_free = hash_table->values[node_index];
880
881       if (keep_new_key)
882         {
883           key_to_free = hash_table->keys[node_index];
884           hash_table->keys[node_index] = new_key;
885         }
886       else
887         key_to_free = new_key;
888     }
889   else
890     {
891       hash_table->hashes[node_index] = key_hash;
892       hash_table->keys[node_index] = new_key;
893     }
894
895   /* Step two: check if the value that we are about to write to the
896    * table is the same as the key in the same position.  If it's not,
897    * split the table.
898    */
899   if (G_UNLIKELY (hash_table->keys == hash_table->values && hash_table->keys[node_index] != new_value))
900     hash_table->values = g_memdup (hash_table->keys, sizeof (gpointer) * hash_table->size);
901
902   /* Step 3: Actually do the write */
903   hash_table->values[node_index] = new_value;
904
905   /* Now, the bookkeeping... */
906   if (!already_exists)
907     {
908       hash_table->nnodes++;
909
910       if (HASH_IS_UNUSED (old_hash))
911         {
912           /* We replaced an empty node, and not a tombstone */
913           hash_table->noccupied++;
914           g_hash_table_maybe_resize (hash_table);
915         }
916
917 #ifndef G_DISABLE_ASSERT
918       hash_table->version++;
919 #endif
920     }
921
922   if (already_exists)
923     {
924       if (hash_table->key_destroy_func && !reusing_key)
925         (* hash_table->key_destroy_func) (key_to_free);
926       if (hash_table->value_destroy_func)
927         (* hash_table->value_destroy_func) (value_to_free);
928     }
929
930   return !already_exists;
931 }
932
933 /**
934  * g_hash_table_iter_replace:
935  * @iter: an initialized #GHashTableIter
936  * @value: the value to replace with
937  *
938  * Replaces the value currently pointed to by the iterator
939  * from its associated #GHashTable. Can only be called after
940  * g_hash_table_iter_next() returned %TRUE.
941  *
942  * If you supplied a @value_destroy_func when creating the
943  * #GHashTable, the old value is freed using that function.
944  *
945  * Since: 2.30
946  */
947 void
948 g_hash_table_iter_replace (GHashTableIter *iter,
949                            gpointer        value)
950 {
951   RealIter *ri;
952   guint node_hash;
953   gpointer key;
954
955   ri = (RealIter *) iter;
956
957   g_return_if_fail (ri != NULL);
958 #ifndef G_DISABLE_ASSERT
959   g_return_if_fail (ri->version == ri->hash_table->version);
960 #endif
961   g_return_if_fail (ri->position >= 0);
962   g_return_if_fail (ri->position < ri->hash_table->size);
963
964   node_hash = ri->hash_table->hashes[ri->position];
965   key = ri->hash_table->keys[ri->position];
966
967   g_hash_table_insert_node (ri->hash_table, ri->position, node_hash, key, value, TRUE, TRUE);
968
969 #ifndef G_DISABLE_ASSERT
970   ri->version++;
971   ri->hash_table->version++;
972 #endif
973 }
974
975 /**
976  * g_hash_table_iter_steal:
977  * @iter: an initialized #GHashTableIter
978  *
979  * Removes the key/value pair currently pointed to by the
980  * iterator from its associated #GHashTable, without calling
981  * the key and value destroy functions. Can only be called
982  * after g_hash_table_iter_next() returned %TRUE, and cannot
983  * be called more than once for the same key/value pair.
984  *
985  * Since: 2.16
986  */
987 void
988 g_hash_table_iter_steal (GHashTableIter *iter)
989 {
990   iter_remove_or_steal ((RealIter *) iter, FALSE);
991 }
992
993
994 /**
995  * g_hash_table_ref:
996  * @hash_table: a valid #GHashTable
997  *
998  * Atomically increments the reference count of @hash_table by one.
999  * This function is MT-safe and may be called from any thread.
1000  *
1001  * Returns: the passed in #GHashTable
1002  *
1003  * Since: 2.10
1004  */
1005 GHashTable *
1006 g_hash_table_ref (GHashTable *hash_table)
1007 {
1008   g_return_val_if_fail (hash_table != NULL, NULL);
1009
1010   g_atomic_int_inc (&hash_table->ref_count);
1011
1012   return hash_table;
1013 }
1014
1015 /**
1016  * g_hash_table_unref:
1017  * @hash_table: a valid #GHashTable
1018  *
1019  * Atomically decrements the reference count of @hash_table by one.
1020  * If the reference count drops to 0, all keys and values will be
1021  * destroyed, and all memory allocated by the hash table is released.
1022  * This function is MT-safe and may be called from any thread.
1023  *
1024  * Since: 2.10
1025  */
1026 void
1027 g_hash_table_unref (GHashTable *hash_table)
1028 {
1029   g_return_if_fail (hash_table != NULL);
1030
1031   if (g_atomic_int_dec_and_test (&hash_table->ref_count))
1032     {
1033       g_hash_table_remove_all_nodes (hash_table, TRUE);
1034       if (hash_table->keys != hash_table->values)
1035         g_free (hash_table->values);
1036       g_free (hash_table->keys);
1037       g_free (hash_table->hashes);
1038       g_slice_free (GHashTable, hash_table);
1039     }
1040 }
1041
1042 /**
1043  * g_hash_table_destroy:
1044  * @hash_table: a #GHashTable
1045  *
1046  * Destroys all keys and values in the #GHashTable and decrements its
1047  * reference count by 1. If keys and/or values are dynamically allocated,
1048  * you should either free them first or create the #GHashTable with destroy
1049  * notifiers using g_hash_table_new_full(). In the latter case the destroy
1050  * functions you supplied will be called on all keys and values during the
1051  * destruction phase.
1052  */
1053 void
1054 g_hash_table_destroy (GHashTable *hash_table)
1055 {
1056   g_return_if_fail (hash_table != NULL);
1057
1058   g_hash_table_remove_all (hash_table);
1059   g_hash_table_unref (hash_table);
1060 }
1061
1062 /**
1063  * g_hash_table_lookup:
1064  * @hash_table: a #GHashTable
1065  * @key: the key to look up
1066  *
1067  * Looks up a key in a #GHashTable. Note that this function cannot
1068  * distinguish between a key that is not present and one which is present
1069  * and has the value %NULL. If you need this distinction, use
1070  * g_hash_table_lookup_extended().
1071  *
1072  * Returns: (allow-none): the associated value, or %NULL if the key is not found
1073  */
1074 gpointer
1075 g_hash_table_lookup (GHashTable    *hash_table,
1076                      gconstpointer  key)
1077 {
1078   guint node_index;
1079   guint node_hash;
1080
1081   g_return_val_if_fail (hash_table != NULL, NULL);
1082
1083   node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1084
1085   return HASH_IS_REAL (hash_table->hashes[node_index])
1086     ? hash_table->values[node_index]
1087     : NULL;
1088 }
1089
1090 /**
1091  * g_hash_table_lookup_extended:
1092  * @hash_table: a #GHashTable
1093  * @lookup_key: the key to look up
1094  * @orig_key: (allow-none): return location for the original key, or %NULL
1095  * @value: (allow-none): return location for the value associated with the key, or %NULL
1096  *
1097  * Looks up a key in the #GHashTable, returning the original key and the
1098  * associated value and a #gboolean which is %TRUE if the key was found. This
1099  * is useful if you need to free the memory allocated for the original key,
1100  * for example before calling g_hash_table_remove().
1101  *
1102  * You can actually pass %NULL for @lookup_key to test
1103  * whether the %NULL key exists, provided the hash and equal functions
1104  * of @hash_table are %NULL-safe.
1105  *
1106  * Returns: %TRUE if the key was found in the #GHashTable
1107  */
1108 gboolean
1109 g_hash_table_lookup_extended (GHashTable    *hash_table,
1110                               gconstpointer  lookup_key,
1111                               gpointer      *orig_key,
1112                               gpointer      *value)
1113 {
1114   guint node_index;
1115   guint node_hash;
1116
1117   g_return_val_if_fail (hash_table != NULL, FALSE);
1118
1119   node_index = g_hash_table_lookup_node (hash_table, lookup_key, &node_hash);
1120
1121   if (!HASH_IS_REAL (hash_table->hashes[node_index]))
1122     return FALSE;
1123
1124   if (orig_key)
1125     *orig_key = hash_table->keys[node_index];
1126
1127   if (value)
1128     *value = hash_table->values[node_index];
1129
1130   return TRUE;
1131 }
1132
1133 /*
1134  * g_hash_table_insert_internal:
1135  * @hash_table: our #GHashTable
1136  * @key: the key to insert
1137  * @value: the value to insert
1138  * @keep_new_key: if %TRUE and this key already exists in the table
1139  *   then call the destroy notify function on the old key.  If %FALSE
1140  *   then call the destroy notify function on the new key.
1141  *
1142  * Implements the common logic for the g_hash_table_insert() and
1143  * g_hash_table_replace() functions.
1144  *
1145  * Do a lookup of @key. If it is found, replace it with the new
1146  * @value (and perhaps the new @key). If it is not found, create
1147  * a new node.
1148  *
1149  * Returns: %TRUE if the key did not exist yet
1150  */
1151 static gboolean
1152 g_hash_table_insert_internal (GHashTable *hash_table,
1153                               gpointer    key,
1154                               gpointer    value,
1155                               gboolean    keep_new_key)
1156 {
1157   guint key_hash;
1158   guint node_index;
1159
1160   g_return_val_if_fail (hash_table != NULL, FALSE);
1161
1162   node_index = g_hash_table_lookup_node (hash_table, key, &key_hash);
1163
1164   return g_hash_table_insert_node (hash_table, node_index, key_hash, key, value, keep_new_key, FALSE);
1165 }
1166
1167 /**
1168  * g_hash_table_insert:
1169  * @hash_table: a #GHashTable
1170  * @key: a key to insert
1171  * @value: the value to associate with the key
1172  *
1173  * Inserts a new key and value into a #GHashTable.
1174  *
1175  * If the key already exists in the #GHashTable its current
1176  * value is replaced with the new value. If you supplied a
1177  * @value_destroy_func when creating the #GHashTable, the old
1178  * value is freed using that function. If you supplied a
1179  * @key_destroy_func when creating the #GHashTable, the passed
1180  * key is freed using that function.
1181  *
1182  * Returns: %TRUE if the key did not exist yet
1183  */
1184 gboolean
1185 g_hash_table_insert (GHashTable *hash_table,
1186                      gpointer    key,
1187                      gpointer    value)
1188 {
1189   return g_hash_table_insert_internal (hash_table, key, value, FALSE);
1190 }
1191
1192 /**
1193  * g_hash_table_replace:
1194  * @hash_table: a #GHashTable
1195  * @key: a key to insert
1196  * @value: the value to associate with the key
1197  *
1198  * Inserts a new key and value into a #GHashTable similar to
1199  * g_hash_table_insert(). The difference is that if the key
1200  * already exists in the #GHashTable, it gets replaced by the
1201  * new key. If you supplied a @value_destroy_func when creating
1202  * the #GHashTable, the old value is freed using that function.
1203  * If you supplied a @key_destroy_func when creating the
1204  * #GHashTable, the old key is freed using that function.
1205  *
1206  * Returns: %TRUE of the key did not exist yet
1207  */
1208 gboolean
1209 g_hash_table_replace (GHashTable *hash_table,
1210                       gpointer    key,
1211                       gpointer    value)
1212 {
1213   return g_hash_table_insert_internal (hash_table, key, value, TRUE);
1214 }
1215
1216 /**
1217  * g_hash_table_add:
1218  * @hash_table: a #GHashTable
1219  * @key: a key to insert
1220  *
1221  * This is a convenience function for using a #GHashTable as a set.  It
1222  * is equivalent to calling g_hash_table_replace() with @key as both the
1223  * key and the value.
1224  *
1225  * When a hash table only ever contains keys that have themselves as the
1226  * corresponding value it is able to be stored more efficiently.  See
1227  * the discussion in the section description.
1228  *
1229  * Returns: %TRUE if the key did not exist yet
1230  *
1231  * Since: 2.32
1232  */
1233 gboolean
1234 g_hash_table_add (GHashTable *hash_table,
1235                   gpointer    key)
1236 {
1237   return g_hash_table_insert_internal (hash_table, key, key, TRUE);
1238 }
1239
1240 /**
1241  * g_hash_table_contains:
1242  * @hash_table: a #GHashTable
1243  * @key: a key to check
1244  *
1245  * Checks if @key is in @hash_table.
1246  *
1247  * Since: 2.32
1248  **/
1249 gboolean
1250 g_hash_table_contains (GHashTable    *hash_table,
1251                        gconstpointer  key)
1252 {
1253   guint node_index;
1254   guint node_hash;
1255
1256   g_return_val_if_fail (hash_table != NULL, FALSE);
1257
1258   node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1259
1260   return HASH_IS_REAL (hash_table->hashes[node_index]);
1261 }
1262
1263 /*
1264  * g_hash_table_remove_internal:
1265  * @hash_table: our #GHashTable
1266  * @key: the key to remove
1267  * @notify: %TRUE if the destroy notify handlers are to be called
1268  * Returns: %TRUE if a node was found and removed, else %FALSE
1269  *
1270  * Implements the common logic for the g_hash_table_remove() and
1271  * g_hash_table_steal() functions.
1272  *
1273  * Do a lookup of @key and remove it if it is found, calling the
1274  * destroy notify handlers only if @notify is %TRUE.
1275  */
1276 static gboolean
1277 g_hash_table_remove_internal (GHashTable    *hash_table,
1278                               gconstpointer  key,
1279                               gboolean       notify)
1280 {
1281   guint node_index;
1282   guint node_hash;
1283
1284   g_return_val_if_fail (hash_table != NULL, FALSE);
1285
1286   node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1287
1288   if (!HASH_IS_REAL (hash_table->hashes[node_index]))
1289     return FALSE;
1290
1291   g_hash_table_remove_node (hash_table, node_index, notify);
1292   g_hash_table_maybe_resize (hash_table);
1293
1294 #ifndef G_DISABLE_ASSERT
1295   hash_table->version++;
1296 #endif
1297
1298   return TRUE;
1299 }
1300
1301 /**
1302  * g_hash_table_remove:
1303  * @hash_table: a #GHashTable
1304  * @key: the key to remove
1305  *
1306  * Removes a key and its associated value from a #GHashTable.
1307  *
1308  * If the #GHashTable was created using g_hash_table_new_full(), the
1309  * key and value are freed using the supplied destroy functions, otherwise
1310  * you have to make sure that any dynamically allocated values are freed
1311  * yourself.
1312  *
1313  * Returns: %TRUE if the key was found and removed from the #GHashTable
1314  */
1315 gboolean
1316 g_hash_table_remove (GHashTable    *hash_table,
1317                      gconstpointer  key)
1318 {
1319   return g_hash_table_remove_internal (hash_table, key, TRUE);
1320 }
1321
1322 /**
1323  * g_hash_table_steal:
1324  * @hash_table: a #GHashTable
1325  * @key: the key to remove
1326  *
1327  * Removes a key and its associated value from a #GHashTable without
1328  * calling the key and value destroy functions.
1329  *
1330  * Returns: %TRUE if the key was found and removed from the #GHashTable
1331  */
1332 gboolean
1333 g_hash_table_steal (GHashTable    *hash_table,
1334                     gconstpointer  key)
1335 {
1336   return g_hash_table_remove_internal (hash_table, key, FALSE);
1337 }
1338
1339 /**
1340  * g_hash_table_remove_all:
1341  * @hash_table: a #GHashTable
1342  *
1343  * Removes all keys and their associated values from a #GHashTable.
1344  *
1345  * If the #GHashTable was created using g_hash_table_new_full(),
1346  * the keys and values are freed using the supplied destroy functions,
1347  * otherwise you have to make sure that any dynamically allocated
1348  * values are freed yourself.
1349  *
1350  * Since: 2.12
1351  */
1352 void
1353 g_hash_table_remove_all (GHashTable *hash_table)
1354 {
1355   g_return_if_fail (hash_table != NULL);
1356
1357 #ifndef G_DISABLE_ASSERT
1358   if (hash_table->nnodes != 0)
1359     hash_table->version++;
1360 #endif
1361
1362   g_hash_table_remove_all_nodes (hash_table, TRUE);
1363   g_hash_table_maybe_resize (hash_table);
1364 }
1365
1366 /**
1367  * g_hash_table_steal_all:
1368  * @hash_table: a #GHashTable
1369  *
1370  * Removes all keys and their associated values from a #GHashTable
1371  * without calling the key and value destroy functions.
1372  *
1373  * Since: 2.12
1374  */
1375 void
1376 g_hash_table_steal_all (GHashTable *hash_table)
1377 {
1378   g_return_if_fail (hash_table != NULL);
1379
1380 #ifndef G_DISABLE_ASSERT
1381   if (hash_table->nnodes != 0)
1382     hash_table->version++;
1383 #endif
1384
1385   g_hash_table_remove_all_nodes (hash_table, FALSE);
1386   g_hash_table_maybe_resize (hash_table);
1387 }
1388
1389 /*
1390  * g_hash_table_foreach_remove_or_steal:
1391  * @hash_table: a #GHashTable
1392  * @func: the user's callback function
1393  * @user_data: data for @func
1394  * @notify: %TRUE if the destroy notify handlers are to be called
1395  *
1396  * Implements the common logic for g_hash_table_foreach_remove()
1397  * and g_hash_table_foreach_steal().
1398  *
1399  * Iterates over every node in the table, calling @func with the key
1400  * and value of the node (and @user_data). If @func returns %TRUE the
1401  * node is removed from the table.
1402  *
1403  * If @notify is true then the destroy notify handlers will be called
1404  * for each removed node.
1405  */
1406 static guint
1407 g_hash_table_foreach_remove_or_steal (GHashTable *hash_table,
1408                                       GHRFunc     func,
1409                                       gpointer    user_data,
1410                                       gboolean    notify)
1411 {
1412   guint deleted = 0;
1413   gint i;
1414 #ifndef G_DISABLE_ASSERT
1415   gint version = hash_table->version;
1416 #endif
1417
1418   for (i = 0; i < hash_table->size; i++)
1419     {
1420       guint node_hash = hash_table->hashes[i];
1421       gpointer node_key = hash_table->keys[i];
1422       gpointer node_value = hash_table->values[i];
1423
1424       if (HASH_IS_REAL (node_hash) &&
1425           (* func) (node_key, node_value, user_data))
1426         {
1427           g_hash_table_remove_node (hash_table, i, notify);
1428           deleted++;
1429         }
1430
1431 #ifndef G_DISABLE_ASSERT
1432       g_return_val_if_fail (version == hash_table->version, 0);
1433 #endif
1434     }
1435
1436   g_hash_table_maybe_resize (hash_table);
1437
1438 #ifndef G_DISABLE_ASSERT
1439   if (deleted > 0)
1440     hash_table->version++;
1441 #endif
1442
1443   return deleted;
1444 }
1445
1446 /**
1447  * g_hash_table_foreach_remove:
1448  * @hash_table: a #GHashTable
1449  * @func: the function to call for each key/value pair
1450  * @user_data: user data to pass to the function
1451  *
1452  * Calls the given function for each key/value pair in the
1453  * #GHashTable. If the function returns %TRUE, then the key/value
1454  * pair is removed from the #GHashTable. If you supplied key or
1455  * value destroy functions when creating the #GHashTable, they are
1456  * used to free the memory allocated for the removed keys and values.
1457  *
1458  * See #GHashTableIter for an alternative way to loop over the
1459  * key/value pairs in the hash table.
1460  *
1461  * Returns: the number of key/value pairs removed
1462  */
1463 guint
1464 g_hash_table_foreach_remove (GHashTable *hash_table,
1465                              GHRFunc     func,
1466                              gpointer    user_data)
1467 {
1468   g_return_val_if_fail (hash_table != NULL, 0);
1469   g_return_val_if_fail (func != NULL, 0);
1470
1471   return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, TRUE);
1472 }
1473
1474 /**
1475  * g_hash_table_foreach_steal:
1476  * @hash_table: a #GHashTable
1477  * @func: the function to call for each key/value pair
1478  * @user_data: user data to pass to the function
1479  *
1480  * Calls the given function for each key/value pair in the
1481  * #GHashTable. If the function returns %TRUE, then the key/value
1482  * pair is removed from the #GHashTable, but no key or value
1483  * destroy functions are called.
1484  *
1485  * See #GHashTableIter for an alternative way to loop over the
1486  * key/value pairs in the hash table.
1487  *
1488  * Returns: the number of key/value pairs removed.
1489  */
1490 guint
1491 g_hash_table_foreach_steal (GHashTable *hash_table,
1492                             GHRFunc     func,
1493                             gpointer    user_data)
1494 {
1495   g_return_val_if_fail (hash_table != NULL, 0);
1496   g_return_val_if_fail (func != NULL, 0);
1497
1498   return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, FALSE);
1499 }
1500
1501 /**
1502  * g_hash_table_foreach:
1503  * @hash_table: a #GHashTable
1504  * @func: the function to call for each key/value pair
1505  * @user_data: user data to pass to the function
1506  *
1507  * Calls the given function for each of the key/value pairs in the
1508  * #GHashTable.  The function is passed the key and value of each
1509  * pair, and the given @user_data parameter.  The hash table may not
1510  * be modified while iterating over it (you can't add/remove
1511  * items). To remove all items matching a predicate, use
1512  * g_hash_table_foreach_remove().
1513  *
1514  * See g_hash_table_find() for performance caveats for linear
1515  * order searches in contrast to g_hash_table_lookup().
1516  */
1517 void
1518 g_hash_table_foreach (GHashTable *hash_table,
1519                       GHFunc      func,
1520                       gpointer    user_data)
1521 {
1522   gint i;
1523 #ifndef G_DISABLE_ASSERT
1524   gint version;
1525 #endif
1526
1527   g_return_if_fail (hash_table != NULL);
1528   g_return_if_fail (func != NULL);
1529
1530 #ifndef G_DISABLE_ASSERT
1531   version = hash_table->version;
1532 #endif
1533
1534   for (i = 0; i < hash_table->size; i++)
1535     {
1536       guint node_hash = hash_table->hashes[i];
1537       gpointer node_key = hash_table->keys[i];
1538       gpointer node_value = hash_table->values[i];
1539
1540       if (HASH_IS_REAL (node_hash))
1541         (* func) (node_key, node_value, user_data);
1542
1543 #ifndef G_DISABLE_ASSERT
1544       g_return_if_fail (version == hash_table->version);
1545 #endif
1546     }
1547 }
1548
1549 /**
1550  * g_hash_table_find:
1551  * @hash_table: a #GHashTable
1552  * @predicate: function to test the key/value pairs for a certain property
1553  * @user_data: user data to pass to the function
1554  *
1555  * Calls the given function for key/value pairs in the #GHashTable
1556  * until @predicate returns %TRUE. The function is passed the key
1557  * and value of each pair, and the given @user_data parameter. The
1558  * hash table may not be modified while iterating over it (you can't
1559  * add/remove items).
1560  *
1561  * Note, that hash tables are really only optimized for forward
1562  * lookups, i.e. g_hash_table_lookup(). So code that frequently issues
1563  * g_hash_table_find() or g_hash_table_foreach() (e.g. in the order of
1564  * once per every entry in a hash table) should probably be reworked
1565  * to use additional or different data structures for reverse lookups
1566  * (keep in mind that an O(n) find/foreach operation issued for all n
1567  * values in a hash table ends up needing O(n*n) operations).
1568  *
1569  * Returns: (allow-none): The value of the first key/value pair is returned,
1570  *     for which @predicate evaluates to %TRUE. If no pair with the
1571  *     requested property is found, %NULL is returned.
1572  *
1573  * Since: 2.4
1574  */
1575 gpointer
1576 g_hash_table_find (GHashTable *hash_table,
1577                    GHRFunc     predicate,
1578                    gpointer    user_data)
1579 {
1580   gint i;
1581 #ifndef G_DISABLE_ASSERT
1582   gint version;
1583 #endif
1584   gboolean match;
1585
1586   g_return_val_if_fail (hash_table != NULL, NULL);
1587   g_return_val_if_fail (predicate != NULL, NULL);
1588
1589 #ifndef G_DISABLE_ASSERT
1590   version = hash_table->version;
1591 #endif
1592
1593   match = FALSE;
1594
1595   for (i = 0; i < hash_table->size; i++)
1596     {
1597       guint node_hash = hash_table->hashes[i];
1598       gpointer node_key = hash_table->keys[i];
1599       gpointer node_value = hash_table->values[i];
1600
1601       if (HASH_IS_REAL (node_hash))
1602         match = predicate (node_key, node_value, user_data);
1603
1604 #ifndef G_DISABLE_ASSERT
1605       g_return_val_if_fail (version == hash_table->version, NULL);
1606 #endif
1607
1608       if (match)
1609         return node_value;
1610     }
1611
1612   return NULL;
1613 }
1614
1615 /**
1616  * g_hash_table_size:
1617  * @hash_table: a #GHashTable
1618  *
1619  * Returns the number of elements contained in the #GHashTable.
1620  *
1621  * Returns: the number of key/value pairs in the #GHashTable.
1622  */
1623 guint
1624 g_hash_table_size (GHashTable *hash_table)
1625 {
1626   g_return_val_if_fail (hash_table != NULL, 0);
1627
1628   return hash_table->nnodes;
1629 }
1630
1631 /**
1632  * g_hash_table_get_keys:
1633  * @hash_table: a #GHashTable
1634  *
1635  * Retrieves every key inside @hash_table. The returned data is valid
1636  * until changes to the hash release those keys.
1637  *
1638  * Returns: a #GList containing all the keys inside the hash
1639  *     table. The content of the list is owned by the hash table and
1640  *     should not be modified or freed. Use g_list_free() when done
1641  *     using the list.
1642  *
1643  * Since: 2.14
1644  */
1645 GList *
1646 g_hash_table_get_keys (GHashTable *hash_table)
1647 {
1648   gint i;
1649   GList *retval;
1650
1651   g_return_val_if_fail (hash_table != NULL, NULL);
1652
1653   retval = NULL;
1654   for (i = 0; i < hash_table->size; i++)
1655     {
1656       if (HASH_IS_REAL (hash_table->hashes[i]))
1657         retval = g_list_prepend (retval, hash_table->keys[i]);
1658     }
1659
1660   return retval;
1661 }
1662
1663 /**
1664  * g_hash_table_get_keys_as_array:
1665  * @hash_table: a #GHashTable
1666  * @length: (out): the length of the returned array
1667  *
1668  * Retrieves every key inside @hash_table, as an array.
1669  *
1670  * The returned array is %NULL-terminated but may contain %NULL as a
1671  * key.  Use @length to determine the true length if it's possible that
1672  * %NULL was used as the value for a key.
1673  *
1674  * Note: in the common case of a string-keyed #GHashTable, the return
1675  * value of this function can be conveniently cast to (gchar **).
1676  *
1677  * You should always free the return result with g_free().  In the
1678  * above-mentioned case of a string-keyed hash table, it may be
1679  * appropriate to use g_strfreev() if you call g_hash_table_steal_all()
1680  * first to transfer ownership of the keys.
1681  *
1682  * Returns: (array length=length) (transfer container): a
1683  *   %NULL-terminated array containing each key from the table.
1684  *
1685  * Since: 2.40
1686  **/
1687 gpointer *
1688 g_hash_table_get_keys_as_array (GHashTable *hash_table,
1689                                 guint      *length)
1690 {
1691   gpointer *result;
1692   guint i, j = 0;
1693
1694   result = g_new (gpointer, hash_table->nnodes + 1);
1695   for (i = 0; i < hash_table->size; i++)
1696     {
1697       if (HASH_IS_REAL (hash_table->hashes[i]))
1698         result[j++] = hash_table->keys[i];
1699     }
1700   g_assert_cmpint (j, ==, hash_table->nnodes);
1701   result[j] = NULL;
1702
1703   if (length)
1704     *length = j;
1705
1706   return result;
1707 }
1708
1709 /**
1710  * g_hash_table_get_values:
1711  * @hash_table: a #GHashTable
1712  *
1713  * Retrieves every value inside @hash_table. The returned data
1714  * is valid until @hash_table is modified.
1715  *
1716  * Returns: a #GList containing all the values inside the hash
1717  *     table. The content of the list is owned by the hash table and
1718  *     should not be modified or freed. Use g_list_free() when done
1719  *     using the list.
1720  *
1721  * Since: 2.14
1722  */
1723 GList *
1724 g_hash_table_get_values (GHashTable *hash_table)
1725 {
1726   gint i;
1727   GList *retval;
1728
1729   g_return_val_if_fail (hash_table != NULL, NULL);
1730
1731   retval = NULL;
1732   for (i = 0; i < hash_table->size; i++)
1733     {
1734       if (HASH_IS_REAL (hash_table->hashes[i]))
1735         retval = g_list_prepend (retval, hash_table->values[i]);
1736     }
1737
1738   return retval;
1739 }
1740
1741 /* Hash functions.
1742  */
1743
1744 /**
1745  * g_str_equal:
1746  * @v1: a key
1747  * @v2: a key to compare with @v1
1748  *
1749  * Compares two strings for byte-by-byte equality and returns %TRUE
1750  * if they are equal. It can be passed to g_hash_table_new() as the
1751  * @key_equal_func parameter, when using non-%NULL strings as keys in a
1752  * #GHashTable.
1753  *
1754  * Note that this function is primarily meant as a hash table comparison
1755  * function. For a general-purpose, %NULL-safe string comparison function,
1756  * see g_strcmp0().
1757  *
1758  * Returns: %TRUE if the two keys match
1759  */
1760 gboolean
1761 g_str_equal (gconstpointer v1,
1762              gconstpointer v2)
1763 {
1764   const gchar *string1 = v1;
1765   const gchar *string2 = v2;
1766
1767   return strcmp (string1, string2) == 0;
1768 }
1769
1770 /**
1771  * g_str_hash:
1772  * @v: a string key
1773  *
1774  * Converts a string to a hash value.
1775  *
1776  * This function implements the widely used "djb" hash apparently
1777  * posted by Daniel Bernstein to comp.lang.c some time ago.  The 32
1778  * bit unsigned hash value starts at 5381 and for each byte 'c' in
1779  * the string, is updated: `hash = hash * 33 + c`. This function
1780  * uses the signed value of each byte.
1781  *
1782  * It can be passed to g_hash_table_new() as the @hash_func parameter,
1783  * when using non-%NULL strings as keys in a #GHashTable.
1784  *
1785  * Returns: a hash value corresponding to the key
1786  */
1787 guint
1788 g_str_hash (gconstpointer v)
1789 {
1790   const signed char *p;
1791   guint32 h = 5381;
1792
1793   for (p = v; *p != '\0'; p++)
1794     h = (h << 5) + h + *p;
1795
1796   return h;
1797 }
1798
1799 /**
1800  * g_direct_hash:
1801  * @v: (allow-none): a #gpointer key
1802  *
1803  * Converts a gpointer to a hash value.
1804  * It can be passed to g_hash_table_new() as the @hash_func parameter,
1805  * when using opaque pointers compared by pointer value as keys in a
1806  * #GHashTable.
1807  *
1808  * This hash function is also appropriate for keys that are integers
1809  * stored in pointers, such as `GINT_TO_POINTER (n)`.
1810  *
1811  * Returns: a hash value corresponding to the key.
1812  */
1813 guint
1814 g_direct_hash (gconstpointer v)
1815 {
1816   return GPOINTER_TO_UINT (v);
1817 }
1818
1819 /**
1820  * g_direct_equal:
1821  * @v1: (allow-none): a key
1822  * @v2: (allow-none): a key to compare with @v1
1823  *
1824  * Compares two #gpointer arguments and returns %TRUE if they are equal.
1825  * It can be passed to g_hash_table_new() as the @key_equal_func
1826  * parameter, when using opaque pointers compared by pointer value as
1827  * keys in a #GHashTable.
1828  *
1829  * This equality function is also appropriate for keys that are integers
1830  * stored in pointers, such as `GINT_TO_POINTER (n)`.
1831  *
1832  * Returns: %TRUE if the two keys match.
1833  */
1834 gboolean
1835 g_direct_equal (gconstpointer v1,
1836                 gconstpointer v2)
1837 {
1838   return v1 == v2;
1839 }
1840
1841 /**
1842  * g_int_equal:
1843  * @v1: a pointer to a #gint key
1844  * @v2: a pointer to a #gint key to compare with @v1
1845  *
1846  * Compares the two #gint values being pointed to and returns
1847  * %TRUE if they are equal.
1848  * It can be passed to g_hash_table_new() as the @key_equal_func
1849  * parameter, when using non-%NULL pointers to integers as keys in a
1850  * #GHashTable.
1851  *
1852  * Note that this function acts on pointers to #gint, not on #gint
1853  * directly: if your hash table's keys are of the form
1854  * `GINT_TO_POINTER (n)`, use g_direct_equal() instead.
1855  *
1856  * Returns: %TRUE if the two keys match.
1857  */
1858 gboolean
1859 g_int_equal (gconstpointer v1,
1860              gconstpointer v2)
1861 {
1862   return *((const gint*) v1) == *((const gint*) v2);
1863 }
1864
1865 /**
1866  * g_int_hash:
1867  * @v: a pointer to a #gint key
1868  *
1869  * Converts a pointer to a #gint to a hash value.
1870  * It can be passed to g_hash_table_new() as the @hash_func parameter,
1871  * when using non-%NULL pointers to integer values as keys in a #GHashTable.
1872  *
1873  * Note that this function acts on pointers to #gint, not on #gint
1874  * directly: if your hash table's keys are of the form
1875  * `GINT_TO_POINTER (n)`, use g_direct_hash() instead.
1876  *
1877  * Returns: a hash value corresponding to the key.
1878  */
1879 guint
1880 g_int_hash (gconstpointer v)
1881 {
1882   return *(const gint*) v;
1883 }
1884
1885 /**
1886  * g_int64_equal:
1887  * @v1: a pointer to a #gint64 key
1888  * @v2: a pointer to a #gint64 key to compare with @v1
1889  *
1890  * Compares the two #gint64 values being pointed to and returns
1891  * %TRUE if they are equal.
1892  * It can be passed to g_hash_table_new() as the @key_equal_func
1893  * parameter, when using non-%NULL pointers to 64-bit integers as keys in a
1894  * #GHashTable.
1895  *
1896  * Returns: %TRUE if the two keys match.
1897  *
1898  * Since: 2.22
1899  */
1900 gboolean
1901 g_int64_equal (gconstpointer v1,
1902                gconstpointer v2)
1903 {
1904   return *((const gint64*) v1) == *((const gint64*) v2);
1905 }
1906
1907 /**
1908  * g_int64_hash:
1909  * @v: a pointer to a #gint64 key
1910  *
1911  * Converts a pointer to a #gint64 to a hash value.
1912  *
1913  * It can be passed to g_hash_table_new() as the @hash_func parameter,
1914  * when using non-%NULL pointers to 64-bit integer values as keys in a
1915  * #GHashTable.
1916  *
1917  * Returns: a hash value corresponding to the key.
1918  *
1919  * Since: 2.22
1920  */
1921 guint
1922 g_int64_hash (gconstpointer v)
1923 {
1924   return (guint) *(const gint64*) v;
1925 }
1926
1927 /**
1928  * g_double_equal:
1929  * @v1: a pointer to a #gdouble key
1930  * @v2: a pointer to a #gdouble key to compare with @v1
1931  *
1932  * Compares the two #gdouble values being pointed to and returns
1933  * %TRUE if they are equal.
1934  * It can be passed to g_hash_table_new() as the @key_equal_func
1935  * parameter, when using non-%NULL pointers to doubles as keys in a
1936  * #GHashTable.
1937  *
1938  * Returns: %TRUE if the two keys match.
1939  *
1940  * Since: 2.22
1941  */
1942 gboolean
1943 g_double_equal (gconstpointer v1,
1944                 gconstpointer v2)
1945 {
1946   return *((const gdouble*) v1) == *((const gdouble*) v2);
1947 }
1948
1949 /**
1950  * g_double_hash:
1951  * @v: a pointer to a #gdouble key
1952  *
1953  * Converts a pointer to a #gdouble to a hash value.
1954  * It can be passed to g_hash_table_new() as the @hash_func parameter,
1955  * It can be passed to g_hash_table_new() as the @hash_func parameter,
1956  * when using non-%NULL pointers to doubles as keys in a #GHashTable.
1957  *
1958  * Returns: a hash value corresponding to the key.
1959  *
1960  * Since: 2.22
1961  */
1962 guint
1963 g_double_hash (gconstpointer v)
1964 {
1965   return (guint) *(const gdouble*) v;
1966 }