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