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