Imported Upstream version 2.74.3
[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  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
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 #include "gmacros.h"
37 #include "glib-private.h"
38 #include "gstrfuncs.h"
39 #include "gatomic.h"
40 #include "gtestutils.h"
41 #include "gslice.h"
42 #include "grefcount.h"
43 #include "gvalgrind.h"
44
45 /* The following #pragma is here so we can do this...
46  *
47  *   #ifndef USE_SMALL_ARRAYS
48  *     is_big = TRUE;
49  *   #endif
50  *     return is_big ? *(((gpointer *) a) + index) : GUINT_TO_POINTER (*(((guint *) a) + index));
51  *
52  * ...instead of this...
53  *
54  *   #ifndef USE_SMALL_ARRAYS
55  *     return *(((gpointer *) a) + index);
56  *   #else
57  *     return is_big ? *(((gpointer *) a) + index) : GUINT_TO_POINTER (*(((guint *) a) + index));
58  *   #endif
59  *
60  * ...and still compile successfully when -Werror=duplicated-branches is passed. */
61
62 #if defined(__GNUC__) && __GNUC__ > 6
63 #pragma GCC diagnostic ignored "-Wduplicated-branches"
64 #endif
65
66 /**
67  * SECTION:hash_tables
68  * @title: Hash Tables
69  * @short_description: associations between keys and values so that
70  *     given a key the value can be found quickly
71  *
72  * A #GHashTable provides associations between keys and values which is
73  * optimized so that given a key, the associated value can be found,
74  * inserted or removed in amortized O(1). All operations going through
75  * each element take O(n) time (list all keys/values, table resize, etc.).
76  *
77  * Note that neither keys nor values are copied when inserted into the
78  * #GHashTable, so they must exist for the lifetime of the #GHashTable.
79  * This means that the use of static strings is OK, but temporary
80  * strings (i.e. those created in buffers and those returned by GTK
81  * widgets) should be copied with g_strdup() before being inserted.
82  *
83  * If keys or values are dynamically allocated, you must be careful to
84  * ensure that they are freed when they are removed from the
85  * #GHashTable, and also when they are overwritten by new insertions
86  * into the #GHashTable. It is also not advisable to mix static strings
87  * and dynamically-allocated strings in a #GHashTable, because it then
88  * becomes difficult to determine whether the string should be freed.
89  *
90  * To create a #GHashTable, use g_hash_table_new().
91  *
92  * To insert a key and value into a #GHashTable, use
93  * g_hash_table_insert().
94  *
95  * To look up a value corresponding to a given key, use
96  * g_hash_table_lookup() and g_hash_table_lookup_extended().
97  *
98  * g_hash_table_lookup_extended() can also be used to simply
99  * check if a key is present in the hash table.
100  *
101  * To remove a key and value, use g_hash_table_remove().
102  *
103  * To call a function for each key and value pair use
104  * g_hash_table_foreach() or use an iterator to iterate over the
105  * key/value pairs in the hash table, see #GHashTableIter. The iteration order
106  * of a hash table is not defined, and you must not rely on iterating over
107  * keys/values in the same order as they were inserted.
108  *
109  * To destroy a #GHashTable use g_hash_table_destroy().
110  *
111  * A common use-case for hash tables is to store information about a
112  * set of keys, without associating any particular value with each
113  * key. GHashTable optimizes one way of doing so: If you store only
114  * key-value pairs where key == value, then GHashTable does not
115  * allocate memory to store the values, which can be a considerable
116  * space saving, if your set is large. The functions
117  * g_hash_table_add() and g_hash_table_contains() are designed to be
118  * used when using #GHashTable this way.
119  *
120  * #GHashTable is not designed to be statically initialised with keys and
121  * values known at compile time. To build a static hash table, use a tool such
122  * as [gperf](https://www.gnu.org/software/gperf/).
123  */
124
125 /**
126  * GHashTable:
127  *
128  * The #GHashTable struct is an opaque data structure to represent a
129  * [Hash Table][glib-Hash-Tables]. It should only be accessed via the
130  * following functions.
131  */
132
133 /**
134  * GHashFunc:
135  * @key: a key
136  *
137  * Specifies the type of the hash function which is passed to
138  * g_hash_table_new() when a #GHashTable is created.
139  *
140  * The function is passed a key and should return a #guint hash value.
141  * The functions g_direct_hash(), g_int_hash() and g_str_hash() provide
142  * hash functions which can be used when the key is a #gpointer, #gint*,
143  * and #gchar* respectively.
144  *
145  * g_direct_hash() is also the appropriate hash function for keys
146  * of the form `GINT_TO_POINTER (n)` (or similar macros).
147  *
148  * A good hash functions should produce
149  * hash values that are evenly distributed over a fairly large range.
150  * The modulus is taken with the hash table size (a prime number) to
151  * find the 'bucket' to place each key into. The function should also
152  * be very fast, since it is called for each key lookup.
153  *
154  * Note that the hash functions provided by GLib have these qualities,
155  * but are not particularly robust against manufactured keys that
156  * cause hash collisions. Therefore, you should consider choosing
157  * a more secure hash function when using a GHashTable with keys
158  * that originate in untrusted data (such as HTTP requests).
159  * Using g_str_hash() in that situation might make your application
160  * vulnerable to
161  * [Algorithmic Complexity Attacks](https://lwn.net/Articles/474912/).
162  *
163  * The key to choosing a good hash is unpredictability.  Even
164  * cryptographic hashes are very easy to find collisions for when the
165  * remainder is taken modulo a somewhat predictable prime number.  There
166  * must be an element of randomness that an attacker is unable to guess.
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  * The iteration order of a #GHashTableIter over the keys/values in a hash
219  * table is not defined.
220  */
221
222 /**
223  * g_hash_table_freeze:
224  * @hash_table: a #GHashTable
225  *
226  * This function is deprecated and will be removed in the next major
227  * release of GLib. It does nothing.
228  */
229
230 /**
231  * g_hash_table_thaw:
232  * @hash_table: a #GHashTable
233  *
234  * This function is deprecated and will be removed in the next major
235  * release of GLib. It does nothing.
236  */
237
238 #define HASH_TABLE_MIN_SHIFT 3  /* 1 << 3 == 8 buckets */
239
240 #define UNUSED_HASH_VALUE 0
241 #define TOMBSTONE_HASH_VALUE 1
242 #define HASH_IS_UNUSED(h_) ((h_) == UNUSED_HASH_VALUE)
243 #define HASH_IS_TOMBSTONE(h_) ((h_) == TOMBSTONE_HASH_VALUE)
244 #define HASH_IS_REAL(h_) ((h_) >= 2)
245
246 /* If int is smaller than void * on our arch, we start out with
247  * int-sized keys and values and resize to pointer-sized entries as
248  * needed. This saves a good amount of memory when the HT is being
249  * used with e.g. GUINT_TO_POINTER(). */
250
251 #define BIG_ENTRY_SIZE (SIZEOF_VOID_P)
252 #define SMALL_ENTRY_SIZE (SIZEOF_INT)
253
254 #if SMALL_ENTRY_SIZE < BIG_ENTRY_SIZE
255 # define USE_SMALL_ARRAYS
256 #endif
257
258 struct _GHashTable
259 {
260   gsize            size;
261   gint             mod;
262   guint            mask;
263   gint             nnodes;
264   gint             noccupied;  /* nnodes + tombstones */
265
266   guint            have_big_keys : 1;
267   guint            have_big_values : 1;
268
269   gpointer         keys;
270   guint           *hashes;
271   gpointer         values;
272
273   GHashFunc        hash_func;
274   GEqualFunc       key_equal_func;
275   gatomicrefcount  ref_count;
276 #ifndef G_DISABLE_ASSERT
277   /*
278    * Tracks the structure of the hash table, not its contents: is only
279    * incremented when a node is added or removed (is not incremented
280    * when the key or data of a node is modified).
281    */
282   int              version;
283 #endif
284   GDestroyNotify   key_destroy_func;
285   GDestroyNotify   value_destroy_func;
286 };
287
288 typedef struct
289 {
290   GHashTable  *hash_table;
291   gpointer     dummy1;
292   gpointer     dummy2;
293   gint         position;
294   gboolean     dummy3;
295   gint         version;
296 } RealIter;
297
298 G_STATIC_ASSERT (sizeof (GHashTableIter) == sizeof (RealIter));
299 G_STATIC_ASSERT (G_ALIGNOF (GHashTableIter) >= G_ALIGNOF (RealIter));
300
301 /* Each table size has an associated prime modulo (the first prime
302  * lower than the table size) used to find the initial bucket. Probing
303  * then works modulo 2^n. The prime modulo is necessary to get a
304  * good distribution with poor hash functions.
305  */
306 static const gint prime_mod [] =
307 {
308   1,          /* For 1 << 0 */
309   2,
310   3,
311   7,
312   13,
313   31,
314   61,
315   127,
316   251,
317   509,
318   1021,
319   2039,
320   4093,
321   8191,
322   16381,
323   32749,
324   65521,      /* For 1 << 16 */
325   131071,
326   262139,
327   524287,
328   1048573,
329   2097143,
330   4194301,
331   8388593,
332   16777213,
333   33554393,
334   67108859,
335   134217689,
336   268435399,
337   536870909,
338   1073741789,
339   2147483647  /* For 1 << 31 */
340 };
341
342 static void
343 g_hash_table_set_shift (GHashTable *hash_table, gint shift)
344 {
345   hash_table->size = 1 << shift;
346   hash_table->mod  = prime_mod [shift];
347
348   /* hash_table->size is always a power of two, so we can calculate the mask
349    * by simply subtracting 1 from it. The leading assertion ensures that
350    * we're really dealing with a power of two. */
351
352   g_assert ((hash_table->size & (hash_table->size - 1)) == 0);
353   hash_table->mask = hash_table->size - 1;
354 }
355
356 static gint
357 g_hash_table_find_closest_shift (gint n)
358 {
359   gint i;
360
361   for (i = 0; n; i++)
362     n >>= 1;
363
364   return i;
365 }
366
367 static void
368 g_hash_table_set_shift_from_size (GHashTable *hash_table, gint size)
369 {
370   gint shift;
371
372   shift = g_hash_table_find_closest_shift (size);
373   shift = MAX (shift, HASH_TABLE_MIN_SHIFT);
374
375   g_hash_table_set_shift (hash_table, shift);
376 }
377
378 static inline gpointer
379 g_hash_table_realloc_key_or_value_array (gpointer a, guint size, G_GNUC_UNUSED gboolean is_big)
380 {
381 #ifdef USE_SMALL_ARRAYS
382   return g_realloc (a, size * (is_big ? BIG_ENTRY_SIZE : SMALL_ENTRY_SIZE));
383 #else
384   return g_renew (gpointer, a, size);
385 #endif
386 }
387
388 static inline gpointer
389 g_hash_table_fetch_key_or_value (gpointer a, guint index, gboolean is_big)
390 {
391 #ifndef USE_SMALL_ARRAYS
392   is_big = TRUE;
393 #endif
394   return is_big ? *(((gpointer *) a) + index) : GUINT_TO_POINTER (*(((guint *) a) + index));
395 }
396
397 static inline void
398 g_hash_table_assign_key_or_value (gpointer a, guint index, gboolean is_big, gpointer v)
399 {
400 #ifndef USE_SMALL_ARRAYS
401   is_big = TRUE;
402 #endif
403   if (is_big)
404     *(((gpointer *) a) + index) = v;
405   else
406     *(((guint *) a) + index) = GPOINTER_TO_UINT (v);
407 }
408
409 static inline gpointer
410 g_hash_table_evict_key_or_value (gpointer a, guint index, gboolean is_big, gpointer v)
411 {
412 #ifndef USE_SMALL_ARRAYS
413   is_big = TRUE;
414 #endif
415   if (is_big)
416     {
417       gpointer r = *(((gpointer *) a) + index);
418       *(((gpointer *) a) + index) = v;
419       return r;
420     }
421   else
422     {
423       gpointer r = GUINT_TO_POINTER (*(((guint *) a) + index));
424       *(((guint *) a) + index) = GPOINTER_TO_UINT (v);
425       return r;
426     }
427 }
428
429 static inline guint
430 g_hash_table_hash_to_index (GHashTable *hash_table, guint hash)
431 {
432   /* Multiply the hash by a small prime before applying the modulo. This
433    * prevents the table from becoming densely packed, even with a poor hash
434    * function. A densely packed table would have poor performance on
435    * workloads with many failed lookups or a high degree of churn. */
436   return (hash * 11) % hash_table->mod;
437 }
438
439 /*
440  * g_hash_table_lookup_node:
441  * @hash_table: our #GHashTable
442  * @key: the key to look up against
443  * @hash_return: key hash return location
444  *
445  * Performs a lookup in the hash table, preserving extra information
446  * usually needed for insertion.
447  *
448  * This function first computes the hash value of the key using the
449  * user's hash function.
450  *
451  * If an entry in the table matching @key is found then this function
452  * returns the index of that entry in the table, and if not, the
453  * index of an unused node (empty or tombstone) where the key can be
454  * inserted.
455  *
456  * The computed hash value is returned in the variable pointed to
457  * by @hash_return. This is to save insertions from having to compute
458  * the hash record again for the new record.
459  *
460  * Returns: index of the described node
461  */
462 static inline guint
463 g_hash_table_lookup_node (GHashTable    *hash_table,
464                           gconstpointer  key,
465                           guint         *hash_return)
466 {
467   guint node_index;
468   guint node_hash;
469   guint hash_value;
470   guint first_tombstone = 0;
471   gboolean have_tombstone = FALSE;
472   guint step = 0;
473
474   hash_value = hash_table->hash_func (key);
475   if (G_UNLIKELY (!HASH_IS_REAL (hash_value)))
476     hash_value = 2;
477
478   *hash_return = hash_value;
479
480   node_index = g_hash_table_hash_to_index (hash_table, hash_value);
481   node_hash = hash_table->hashes[node_index];
482
483   while (!HASH_IS_UNUSED (node_hash))
484     {
485       /* We first check if our full hash values
486        * are equal so we can avoid calling the full-blown
487        * key equality function in most cases.
488        */
489       if (node_hash == hash_value)
490         {
491           gpointer node_key = g_hash_table_fetch_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys);
492
493           if (hash_table->key_equal_func)
494             {
495               if (hash_table->key_equal_func (node_key, key))
496                 return node_index;
497             }
498           else if (node_key == key)
499             {
500               return node_index;
501             }
502         }
503       else if (HASH_IS_TOMBSTONE (node_hash) && !have_tombstone)
504         {
505           first_tombstone = node_index;
506           have_tombstone = TRUE;
507         }
508
509       step++;
510       node_index += step;
511       node_index &= hash_table->mask;
512       node_hash = hash_table->hashes[node_index];
513     }
514
515   if (have_tombstone)
516     return first_tombstone;
517
518   return node_index;
519 }
520
521 /*
522  * g_hash_table_remove_node:
523  * @hash_table: our #GHashTable
524  * @node: pointer to node to remove
525  * @notify: %TRUE if the destroy notify handlers are to be called
526  *
527  * Removes a node from the hash table and updates the node count.
528  * The node is replaced by a tombstone. No table resize is performed.
529  *
530  * If @notify is %TRUE then the destroy notify functions are called
531  * for the key and value of the hash node.
532  */
533 static void
534 g_hash_table_remove_node (GHashTable   *hash_table,
535                           gint          i,
536                           gboolean      notify)
537 {
538   gpointer key;
539   gpointer value;
540
541   key = g_hash_table_fetch_key_or_value (hash_table->keys, i, hash_table->have_big_keys);
542   value = g_hash_table_fetch_key_or_value (hash_table->values, i, hash_table->have_big_values);
543
544   /* Erect tombstone */
545   hash_table->hashes[i] = TOMBSTONE_HASH_VALUE;
546
547   /* Be GC friendly */
548   g_hash_table_assign_key_or_value (hash_table->keys, i, hash_table->have_big_keys, NULL);
549   g_hash_table_assign_key_or_value (hash_table->values, i, hash_table->have_big_values, NULL);
550
551   hash_table->nnodes--;
552
553   if (notify && hash_table->key_destroy_func)
554     hash_table->key_destroy_func (key);
555
556   if (notify && hash_table->value_destroy_func)
557     hash_table->value_destroy_func (value);
558
559 }
560
561 /*
562  * g_hash_table_setup_storage:
563  * @hash_table: our #GHashTable
564  *
565  * Initialise the hash table size, mask, mod, and arrays.
566  */
567 static void
568 g_hash_table_setup_storage (GHashTable *hash_table)
569 {
570   gboolean small = FALSE;
571
572   /* We want to use small arrays only if:
573    *   - we are running on a system where that makes sense (64 bit); and
574    *   - we are not running under valgrind.
575    */
576
577 #ifdef USE_SMALL_ARRAYS
578   small = TRUE;
579
580 # ifdef ENABLE_VALGRIND
581   if (RUNNING_ON_VALGRIND)
582     small = FALSE;
583 # endif
584 #endif
585
586   g_hash_table_set_shift (hash_table, HASH_TABLE_MIN_SHIFT);
587
588   hash_table->have_big_keys = !small;
589   hash_table->have_big_values = !small;
590
591   hash_table->keys   = g_hash_table_realloc_key_or_value_array (NULL, hash_table->size, hash_table->have_big_keys);
592   hash_table->values = hash_table->keys;
593   hash_table->hashes = g_new0 (guint, hash_table->size);
594 }
595
596 /*
597  * g_hash_table_remove_all_nodes:
598  * @hash_table: our #GHashTable
599  * @notify: %TRUE if the destroy notify handlers are to be called
600  *
601  * Removes all nodes from the table.
602  *
603  * If @notify is %TRUE then the destroy notify functions are called
604  * for the key and value of the hash node.
605  *
606  * Since this may be a precursor to freeing the table entirely, we'd
607  * ideally perform no resize, and we can indeed avoid that in some
608  * cases.  However: in the case that we'll be making callbacks to user
609  * code (via destroy notifies) we need to consider that the user code
610  * might call back into the table again.  In this case, we setup a new
611  * set of arrays so that any callers will see an empty (but valid)
612  * table.
613  */
614 static void
615 g_hash_table_remove_all_nodes (GHashTable *hash_table,
616                                gboolean    notify,
617                                gboolean    destruction)
618 {
619   int i;
620   gpointer key;
621   gpointer value;
622   gint old_size;
623   gpointer *old_keys;
624   gpointer *old_values;
625   guint    *old_hashes;
626   gboolean  old_have_big_keys;
627   gboolean  old_have_big_values;
628
629   /* If the hash table is already empty, there is nothing to be done. */
630   if (hash_table->nnodes == 0)
631     return;
632
633   hash_table->nnodes = 0;
634   hash_table->noccupied = 0;
635
636   /* Easy case: no callbacks, so we just zero out the arrays */
637   if (!notify ||
638       (hash_table->key_destroy_func == NULL &&
639        hash_table->value_destroy_func == NULL))
640     {
641       if (!destruction)
642         {
643           memset (hash_table->hashes, 0, hash_table->size * sizeof (guint));
644
645 #ifdef USE_SMALL_ARRAYS
646           memset (hash_table->keys, 0, hash_table->size * (hash_table->have_big_keys ? BIG_ENTRY_SIZE : SMALL_ENTRY_SIZE));
647           memset (hash_table->values, 0, hash_table->size * (hash_table->have_big_values ? BIG_ENTRY_SIZE : SMALL_ENTRY_SIZE));
648 #else
649           memset (hash_table->keys, 0, hash_table->size * sizeof (gpointer));
650           memset (hash_table->values, 0, hash_table->size * sizeof (gpointer));
651 #endif
652         }
653
654       return;
655     }
656
657   /* Hard case: we need to do user callbacks.  There are two
658    * possibilities here:
659    *
660    *   1) there are no outstanding references on the table and therefore
661    *   nobody should be calling into it again (destroying == true)
662    *
663    *   2) there are outstanding references, and there may be future
664    *   calls into the table, either after we return, or from the destroy
665    *   notifies that we're about to do (destroying == false)
666    *
667    * We handle both cases by taking the current state of the table into
668    * local variables and replacing it with something else: in the "no
669    * outstanding references" cases we replace it with a bunch of
670    * null/zero values so that any access to the table will fail.  In the
671    * "may receive future calls" case, we reinitialise the struct to
672    * appear like a newly-created empty table.
673    *
674    * In both cases, we take over the references for the current state,
675    * freeing them below.
676    */
677   old_size = hash_table->size;
678   old_have_big_keys = hash_table->have_big_keys;
679   old_have_big_values = hash_table->have_big_values;
680   old_keys   = g_steal_pointer (&hash_table->keys);
681   old_values = g_steal_pointer (&hash_table->values);
682   old_hashes = g_steal_pointer (&hash_table->hashes);
683
684   if (!destruction)
685     /* Any accesses will see an empty table */
686     g_hash_table_setup_storage (hash_table);
687   else
688     /* Will cause a quick crash on any attempted access */
689     hash_table->size = hash_table->mod = hash_table->mask = 0;
690
691   /* Now do the actual destroy notifies */
692   for (i = 0; i < old_size; i++)
693     {
694       if (HASH_IS_REAL (old_hashes[i]))
695         {
696           key = g_hash_table_fetch_key_or_value (old_keys, i, old_have_big_keys);
697           value = g_hash_table_fetch_key_or_value (old_values, i, old_have_big_values);
698
699           old_hashes[i] = UNUSED_HASH_VALUE;
700
701           g_hash_table_assign_key_or_value (old_keys, i, old_have_big_keys, NULL);
702           g_hash_table_assign_key_or_value (old_values, i, old_have_big_values, NULL);
703
704           if (hash_table->key_destroy_func != NULL)
705             hash_table->key_destroy_func (key);
706
707           if (hash_table->value_destroy_func != NULL)
708             hash_table->value_destroy_func (value);
709         }
710     }
711
712   /* Destroy old storage space. */
713   if (old_keys != old_values)
714     g_free (old_values);
715
716   g_free (old_keys);
717   g_free (old_hashes);
718 }
719
720 static void
721 realloc_arrays (GHashTable *hash_table, gboolean is_a_set)
722 {
723   hash_table->hashes = g_renew (guint, hash_table->hashes, hash_table->size);
724   hash_table->keys = g_hash_table_realloc_key_or_value_array (hash_table->keys, hash_table->size, hash_table->have_big_keys);
725
726   if (is_a_set)
727     hash_table->values = hash_table->keys;
728   else
729     hash_table->values = g_hash_table_realloc_key_or_value_array (hash_table->values, hash_table->size, hash_table->have_big_values);
730 }
731
732 /* When resizing the table in place, we use a temporary bit array to keep
733  * track of which entries have been assigned a proper location in the new
734  * table layout.
735  *
736  * Each bit corresponds to a bucket. A bit is set if an entry was assigned
737  * its corresponding location during the resize and thus should not be
738  * evicted. The array starts out cleared to zero. */
739
740 static inline gboolean
741 get_status_bit (const guint32 *bitmap, guint index)
742 {
743   return (bitmap[index / 32] >> (index % 32)) & 1;
744 }
745
746 static inline void
747 set_status_bit (guint32 *bitmap, guint index)
748 {
749   bitmap[index / 32] |= 1U << (index % 32);
750 }
751
752 /* By calling dedicated resize functions for sets and maps, we avoid 2x
753  * test-and-branch per key in the inner loop. This yields a small
754  * performance improvement at the cost of a bit of macro gunk. */
755
756 #define DEFINE_RESIZE_FUNC(fname) \
757 static void fname (GHashTable *hash_table, guint old_size, guint32 *reallocated_buckets_bitmap) \
758 {                                                                       \
759   guint i;                                                              \
760                                                                         \
761   for (i = 0; i < old_size; i++)                                        \
762     {                                                                   \
763       guint node_hash = hash_table->hashes[i];                          \
764       gpointer key, value G_GNUC_UNUSED;                                \
765                                                                         \
766       if (!HASH_IS_REAL (node_hash))                                    \
767         {                                                               \
768           /* Clear tombstones */                                        \
769           hash_table->hashes[i] = UNUSED_HASH_VALUE;                    \
770           continue;                                                     \
771         }                                                               \
772                                                                         \
773       /* Skip entries relocated through eviction */                     \
774       if (get_status_bit (reallocated_buckets_bitmap, i))               \
775         continue;                                                       \
776                                                                         \
777       hash_table->hashes[i] = UNUSED_HASH_VALUE;                        \
778       EVICT_KEYVAL (hash_table, i, NULL, NULL, key, value);             \
779                                                                         \
780       for (;;)                                                          \
781         {                                                               \
782           guint hash_val;                                               \
783           guint replaced_hash;                                          \
784           guint step = 0;                                               \
785                                                                         \
786           hash_val = g_hash_table_hash_to_index (hash_table, node_hash); \
787                                                                         \
788           while (get_status_bit (reallocated_buckets_bitmap, hash_val)) \
789             {                                                           \
790               step++;                                                   \
791               hash_val += step;                                         \
792               hash_val &= hash_table->mask;                             \
793             }                                                           \
794                                                                         \
795           set_status_bit (reallocated_buckets_bitmap, hash_val);        \
796                                                                         \
797           replaced_hash = hash_table->hashes[hash_val];                 \
798           hash_table->hashes[hash_val] = node_hash;                     \
799           if (!HASH_IS_REAL (replaced_hash))                            \
800             {                                                           \
801               ASSIGN_KEYVAL (hash_table, hash_val, key, value);         \
802               break;                                                    \
803             }                                                           \
804                                                                         \
805           node_hash = replaced_hash;                                    \
806           EVICT_KEYVAL (hash_table, hash_val, key, value, key, value);  \
807         }                                                               \
808     }                                                                   \
809 }
810
811 #define ASSIGN_KEYVAL(ht, index, key, value) G_STMT_START{ \
812     g_hash_table_assign_key_or_value ((ht)->keys, (index), (ht)->have_big_keys, (key)); \
813     g_hash_table_assign_key_or_value ((ht)->values, (index), (ht)->have_big_values, (value)); \
814   }G_STMT_END
815
816 #define EVICT_KEYVAL(ht, index, key, value, outkey, outvalue) G_STMT_START{ \
817     (outkey) = g_hash_table_evict_key_or_value ((ht)->keys, (index), (ht)->have_big_keys, (key)); \
818     (outvalue) = g_hash_table_evict_key_or_value ((ht)->values, (index), (ht)->have_big_values, (value)); \
819   }G_STMT_END
820
821 DEFINE_RESIZE_FUNC (resize_map)
822
823 #undef ASSIGN_KEYVAL
824 #undef EVICT_KEYVAL
825
826 #define ASSIGN_KEYVAL(ht, index, key, value) G_STMT_START{ \
827     g_hash_table_assign_key_or_value ((ht)->keys, (index), (ht)->have_big_keys, (key)); \
828   }G_STMT_END
829
830 #define EVICT_KEYVAL(ht, index, key, value, outkey, outvalue) G_STMT_START{ \
831     (outkey) = g_hash_table_evict_key_or_value ((ht)->keys, (index), (ht)->have_big_keys, (key)); \
832   }G_STMT_END
833
834 DEFINE_RESIZE_FUNC (resize_set)
835
836 #undef ASSIGN_KEYVAL
837 #undef EVICT_KEYVAL
838
839 /*
840  * g_hash_table_resize:
841  * @hash_table: our #GHashTable
842  *
843  * Resizes the hash table to the optimal size based on the number of
844  * nodes currently held. If you call this function then a resize will
845  * occur, even if one does not need to occur.
846  * Use g_hash_table_maybe_resize() instead.
847  *
848  * This function may "resize" the hash table to its current size, with
849  * the side effect of cleaning up tombstones and otherwise optimizing
850  * the probe sequences.
851  */
852 static void
853 g_hash_table_resize (GHashTable *hash_table)
854 {
855   guint32 *reallocated_buckets_bitmap;
856   gsize old_size;
857   gboolean is_a_set;
858
859   old_size = hash_table->size;
860   is_a_set = hash_table->keys == hash_table->values;
861
862   /* The outer checks in g_hash_table_maybe_resize() will only consider
863    * cleanup/resize when the load factor goes below .25 (1/4, ignoring
864    * tombstones) or above .9375 (15/16, including tombstones).
865    *
866    * Once this happens, tombstones will always be cleaned out. If our
867    * load sans tombstones is greater than .75 (1/1.333, see below), we'll
868    * take this opportunity to grow the table too.
869    *
870    * Immediately after growing, the load factor will be in the range
871    * .375 .. .469. After shrinking, it will be exactly .5. */
872
873   g_hash_table_set_shift_from_size (hash_table, hash_table->nnodes * 1.333);
874
875   if (hash_table->size > old_size)
876     {
877       realloc_arrays (hash_table, is_a_set);
878       memset (&hash_table->hashes[old_size], 0, (hash_table->size - old_size) * sizeof (guint));
879
880       reallocated_buckets_bitmap = g_new0 (guint32, (hash_table->size + 31) / 32);
881     }
882   else
883     {
884       reallocated_buckets_bitmap = g_new0 (guint32, (old_size + 31) / 32);
885     }
886
887   if (is_a_set)
888     resize_set (hash_table, old_size, reallocated_buckets_bitmap);
889   else
890     resize_map (hash_table, old_size, reallocated_buckets_bitmap);
891
892   g_free (reallocated_buckets_bitmap);
893
894   if (hash_table->size < old_size)
895     realloc_arrays (hash_table, is_a_set);
896
897   hash_table->noccupied = hash_table->nnodes;
898 }
899
900 /*
901  * g_hash_table_maybe_resize:
902  * @hash_table: our #GHashTable
903  *
904  * Resizes the hash table, if needed.
905  *
906  * Essentially, calls g_hash_table_resize() if the table has strayed
907  * too far from its ideal size for its number of nodes.
908  */
909 static inline void
910 g_hash_table_maybe_resize (GHashTable *hash_table)
911 {
912   gint noccupied = hash_table->noccupied;
913   gint size = hash_table->size;
914
915   if ((size > hash_table->nnodes * 4 && size > 1 << HASH_TABLE_MIN_SHIFT) ||
916       (size <= noccupied + (noccupied / 16)))
917     g_hash_table_resize (hash_table);
918 }
919
920 #ifdef USE_SMALL_ARRAYS
921
922 static inline gboolean
923 entry_is_big (gpointer v)
924 {
925   return (((guintptr) v) >> ((BIG_ENTRY_SIZE - SMALL_ENTRY_SIZE) * 8)) != 0;
926 }
927
928 static inline gboolean
929 g_hash_table_maybe_make_big_keys_or_values (gpointer *a_p, gpointer v, gint ht_size)
930 {
931   if (entry_is_big (v))
932     {
933       guint *a = (guint *) *a_p;
934       gpointer *a_new;
935       gint i;
936
937       a_new = g_new (gpointer, ht_size);
938
939       for (i = 0; i < ht_size; i++)
940         {
941           a_new[i] = GUINT_TO_POINTER (a[i]);
942         }
943
944       g_free (a);
945       *a_p = a_new;
946       return TRUE;
947     }
948
949   return FALSE;
950 }
951
952 #endif
953
954 static inline void
955 g_hash_table_ensure_keyval_fits (GHashTable *hash_table, gpointer key, gpointer value)
956 {
957   gboolean is_a_set = (hash_table->keys == hash_table->values);
958
959 #ifdef USE_SMALL_ARRAYS
960
961   /* Convert from set to map? */
962   if (is_a_set)
963     {
964       if (hash_table->have_big_keys)
965         {
966           if (key != value)
967             hash_table->values = g_memdup2 (hash_table->keys, sizeof (gpointer) * hash_table->size);
968           /* Keys and values are both big now, so no need for further checks */
969           return;
970         }
971       else
972         {
973           if (key != value)
974             {
975               hash_table->values = g_memdup2 (hash_table->keys, sizeof (guint) * hash_table->size);
976               is_a_set = FALSE;
977             }
978         }
979     }
980
981   /* Make keys big? */
982   if (!hash_table->have_big_keys)
983     {
984       hash_table->have_big_keys = g_hash_table_maybe_make_big_keys_or_values (&hash_table->keys, key, hash_table->size);
985
986       if (is_a_set)
987         {
988           hash_table->values = hash_table->keys;
989           hash_table->have_big_values = hash_table->have_big_keys;
990         }
991     }
992
993   /* Make values big? */
994   if (!is_a_set && !hash_table->have_big_values)
995     {
996       hash_table->have_big_values = g_hash_table_maybe_make_big_keys_or_values (&hash_table->values, value, hash_table->size);
997     }
998
999 #else
1000
1001   /* Just split if necessary */
1002   if (is_a_set && key != value)
1003     hash_table->values = g_memdup2 (hash_table->keys, sizeof (gpointer) * hash_table->size);
1004
1005 #endif
1006 }
1007
1008 /**
1009  * g_hash_table_new:
1010  * @hash_func: a function to create a hash value from a key
1011  * @key_equal_func: a function to check two keys for equality
1012  *
1013  * Creates a new #GHashTable with a reference count of 1.
1014  *
1015  * Hash values returned by @hash_func are used to determine where keys
1016  * are stored within the #GHashTable data structure. The g_direct_hash(),
1017  * g_int_hash(), g_int64_hash(), g_double_hash() and g_str_hash()
1018  * functions are provided for some common types of keys.
1019  * If @hash_func is %NULL, g_direct_hash() is used.
1020  *
1021  * @key_equal_func is used when looking up keys in the #GHashTable.
1022  * The g_direct_equal(), g_int_equal(), g_int64_equal(), g_double_equal()
1023  * and g_str_equal() functions are provided for the most common types
1024  * of keys. If @key_equal_func is %NULL, keys are compared directly in
1025  * a similar fashion to g_direct_equal(), but without the overhead of
1026  * a function call. @key_equal_func is called with the key from the hash table
1027  * as its first parameter, and the user-provided key to check against as
1028  * its second.
1029  *
1030  * Returns: a new #GHashTable
1031  */
1032 GHashTable *
1033 g_hash_table_new (GHashFunc  hash_func,
1034                   GEqualFunc key_equal_func)
1035 {
1036   return g_hash_table_new_full (hash_func, key_equal_func, NULL, NULL);
1037 }
1038
1039
1040 /**
1041  * g_hash_table_new_full:
1042  * @hash_func: a function to create a hash value from a key
1043  * @key_equal_func: a function to check two keys for equality
1044  * @key_destroy_func: (nullable): a function to free the memory allocated for the key
1045  *     used when removing the entry from the #GHashTable, or %NULL
1046  *     if you don't want to supply such a function.
1047  * @value_destroy_func: (nullable): a function to free the memory allocated for the
1048  *     value used when removing the entry from the #GHashTable, or %NULL
1049  *     if you don't want to supply such a function.
1050  *
1051  * Creates a new #GHashTable like g_hash_table_new() with a reference
1052  * count of 1 and allows to specify functions to free the memory
1053  * allocated for the key and value that get called when removing the
1054  * entry from the #GHashTable.
1055  *
1056  * Since version 2.42 it is permissible for destroy notify functions to
1057  * recursively remove further items from the hash table. This is only
1058  * permissible if the application still holds a reference to the hash table.
1059  * This means that you may need to ensure that the hash table is empty by
1060  * calling g_hash_table_remove_all() before releasing the last reference using
1061  * g_hash_table_unref().
1062  *
1063  * Returns: a new #GHashTable
1064  */
1065 GHashTable *
1066 g_hash_table_new_full (GHashFunc      hash_func,
1067                        GEqualFunc     key_equal_func,
1068                        GDestroyNotify key_destroy_func,
1069                        GDestroyNotify value_destroy_func)
1070 {
1071   GHashTable *hash_table;
1072
1073   hash_table = g_slice_new (GHashTable);
1074   g_atomic_ref_count_init (&hash_table->ref_count);
1075   hash_table->nnodes             = 0;
1076   hash_table->noccupied          = 0;
1077   hash_table->hash_func          = hash_func ? hash_func : g_direct_hash;
1078   hash_table->key_equal_func     = key_equal_func;
1079 #ifndef G_DISABLE_ASSERT
1080   hash_table->version            = 0;
1081 #endif
1082   hash_table->key_destroy_func   = key_destroy_func;
1083   hash_table->value_destroy_func = value_destroy_func;
1084
1085   g_hash_table_setup_storage (hash_table);
1086
1087   return hash_table;
1088 }
1089
1090 /**
1091  * g_hash_table_new_similar:
1092  * @other_hash_table: (not nullable) (transfer none): Another #GHashTable
1093  *
1094  * Creates a new #GHashTable like g_hash_table_new_full() with a reference
1095  * count of 1.
1096  *
1097  * It inherits the hash function, the key equal function, the key destroy function,
1098  * as well as the value destroy function, from @other_hash_table.
1099  *
1100  * The returned hash table will be empty; it will not contain the keys
1101  * or values from @other_hash_table.
1102  *
1103  * Returns: (transfer full) (not nullable): a new #GHashTable
1104  * Since: 2.72
1105  */
1106 GHashTable *
1107 g_hash_table_new_similar (GHashTable *other_hash_table)
1108 {
1109   g_return_val_if_fail (other_hash_table, NULL);
1110
1111   return g_hash_table_new_full (other_hash_table->hash_func,
1112                                 other_hash_table->key_equal_func,
1113                                 other_hash_table->key_destroy_func,
1114                                 other_hash_table->value_destroy_func);
1115 }
1116
1117 /**
1118  * g_hash_table_iter_init:
1119  * @iter: an uninitialized #GHashTableIter
1120  * @hash_table: a #GHashTable
1121  *
1122  * Initializes a key/value pair iterator and associates it with
1123  * @hash_table. Modifying the hash table after calling this function
1124  * invalidates the returned iterator.
1125  *
1126  * The iteration order of a #GHashTableIter over the keys/values in a hash
1127  * table is not defined.
1128  *
1129  * |[<!-- language="C" -->
1130  * GHashTableIter iter;
1131  * gpointer key, value;
1132  *
1133  * g_hash_table_iter_init (&iter, hash_table);
1134  * while (g_hash_table_iter_next (&iter, &key, &value))
1135  *   {
1136  *     // do something with key and value
1137  *   }
1138  * ]|
1139  *
1140  * Since: 2.16
1141  */
1142 void
1143 g_hash_table_iter_init (GHashTableIter *iter,
1144                         GHashTable     *hash_table)
1145 {
1146   RealIter *ri = (RealIter *) iter;
1147
1148   g_return_if_fail (iter != NULL);
1149   g_return_if_fail (hash_table != NULL);
1150
1151   ri->hash_table = hash_table;
1152   ri->position = -1;
1153 #ifndef G_DISABLE_ASSERT
1154   ri->version = hash_table->version;
1155 #endif
1156 }
1157
1158 /**
1159  * g_hash_table_iter_next:
1160  * @iter: an initialized #GHashTableIter
1161  * @key: (out) (optional): a location to store the key
1162  * @value: (out) (optional) (nullable): a location to store the value
1163  *
1164  * Advances @iter and retrieves the key and/or value that are now
1165  * pointed to as a result of this advancement. If %FALSE is returned,
1166  * @key and @value are not set, and the iterator becomes invalid.
1167  *
1168  * Returns: %FALSE if the end of the #GHashTable has been reached.
1169  *
1170  * Since: 2.16
1171  */
1172 gboolean
1173 g_hash_table_iter_next (GHashTableIter *iter,
1174                         gpointer       *key,
1175                         gpointer       *value)
1176 {
1177   RealIter *ri = (RealIter *) iter;
1178   gint position;
1179
1180   g_return_val_if_fail (iter != NULL, FALSE);
1181 #ifndef G_DISABLE_ASSERT
1182   g_return_val_if_fail (ri->version == ri->hash_table->version, FALSE);
1183 #endif
1184   g_return_val_if_fail (ri->position < (gssize) ri->hash_table->size, FALSE);
1185
1186   position = ri->position;
1187
1188   do
1189     {
1190       position++;
1191       if (position >= (gssize) ri->hash_table->size)
1192         {
1193           ri->position = position;
1194           return FALSE;
1195         }
1196     }
1197   while (!HASH_IS_REAL (ri->hash_table->hashes[position]));
1198
1199   if (key != NULL)
1200     *key = g_hash_table_fetch_key_or_value (ri->hash_table->keys, position, ri->hash_table->have_big_keys);
1201   if (value != NULL)
1202     *value = g_hash_table_fetch_key_or_value (ri->hash_table->values, position, ri->hash_table->have_big_values);
1203
1204   ri->position = position;
1205   return TRUE;
1206 }
1207
1208 /**
1209  * g_hash_table_iter_get_hash_table:
1210  * @iter: an initialized #GHashTableIter
1211  *
1212  * Returns the #GHashTable associated with @iter.
1213  *
1214  * Returns: the #GHashTable associated with @iter.
1215  *
1216  * Since: 2.16
1217  */
1218 GHashTable *
1219 g_hash_table_iter_get_hash_table (GHashTableIter *iter)
1220 {
1221   g_return_val_if_fail (iter != NULL, NULL);
1222
1223   return ((RealIter *) iter)->hash_table;
1224 }
1225
1226 static void
1227 iter_remove_or_steal (RealIter *ri, gboolean notify)
1228 {
1229   g_return_if_fail (ri != NULL);
1230 #ifndef G_DISABLE_ASSERT
1231   g_return_if_fail (ri->version == ri->hash_table->version);
1232 #endif
1233   g_return_if_fail (ri->position >= 0);
1234   g_return_if_fail ((gsize) ri->position < ri->hash_table->size);
1235
1236   g_hash_table_remove_node (ri->hash_table, ri->position, notify);
1237
1238 #ifndef G_DISABLE_ASSERT
1239   ri->version++;
1240   ri->hash_table->version++;
1241 #endif
1242 }
1243
1244 /**
1245  * g_hash_table_iter_remove:
1246  * @iter: an initialized #GHashTableIter
1247  *
1248  * Removes the key/value pair currently pointed to by the iterator
1249  * from its associated #GHashTable. Can only be called after
1250  * g_hash_table_iter_next() returned %TRUE, and cannot be called
1251  * more than once for the same key/value pair.
1252  *
1253  * If the #GHashTable was created using g_hash_table_new_full(),
1254  * the key and value are freed using the supplied destroy functions,
1255  * otherwise you have to make sure that any dynamically allocated
1256  * values are freed yourself.
1257  *
1258  * It is safe to continue iterating the #GHashTable afterward:
1259  * |[<!-- language="C" -->
1260  * while (g_hash_table_iter_next (&iter, &key, &value))
1261  *   {
1262  *     if (condition)
1263  *       g_hash_table_iter_remove (&iter);
1264  *   }
1265  * ]|
1266  *
1267  * Since: 2.16
1268  */
1269 void
1270 g_hash_table_iter_remove (GHashTableIter *iter)
1271 {
1272   iter_remove_or_steal ((RealIter *) iter, TRUE);
1273 }
1274
1275 /*
1276  * g_hash_table_insert_node:
1277  * @hash_table: our #GHashTable
1278  * @node_index: pointer to node to insert/replace
1279  * @key_hash: key hash
1280  * @key: (nullable): key to replace with, or %NULL
1281  * @value: value to replace with
1282  * @keep_new_key: whether to replace the key in the node with @key
1283  * @reusing_key: whether @key was taken out of the existing node
1284  *
1285  * Inserts a value at @node_index in the hash table and updates it.
1286  *
1287  * If @key has been taken out of the existing node (ie it is not
1288  * passed in via a g_hash_table_insert/replace) call, then @reusing_key
1289  * should be %TRUE.
1290  *
1291  * Returns: %TRUE if the key did not exist yet
1292  */
1293 static gboolean
1294 g_hash_table_insert_node (GHashTable *hash_table,
1295                           guint       node_index,
1296                           guint       key_hash,
1297                           gpointer    new_key,
1298                           gpointer    new_value,
1299                           gboolean    keep_new_key,
1300                           gboolean    reusing_key)
1301 {
1302   gboolean already_exists;
1303   guint old_hash;
1304   gpointer key_to_free = NULL;
1305   gpointer key_to_keep = NULL;
1306   gpointer value_to_free = NULL;
1307
1308   old_hash = hash_table->hashes[node_index];
1309   already_exists = HASH_IS_REAL (old_hash);
1310
1311   /* Proceed in three steps.  First, deal with the key because it is the
1312    * most complicated.  Then consider if we need to split the table in
1313    * two (because writing the value will result in the set invariant
1314    * becoming broken).  Then deal with the value.
1315    *
1316    * There are three cases for the key:
1317    *
1318    *  - entry already exists in table, reusing key:
1319    *    free the just-passed-in new_key and use the existing value
1320    *
1321    *  - entry already exists in table, not reusing key:
1322    *    free the entry in the table, use the new key
1323    *
1324    *  - entry not already in table:
1325    *    use the new key, free nothing
1326    *
1327    * We update the hash at the same time...
1328    */
1329   if (already_exists)
1330     {
1331       /* Note: we must record the old value before writing the new key
1332        * because we might change the value in the event that the two
1333        * arrays are shared.
1334        */
1335       value_to_free = g_hash_table_fetch_key_or_value (hash_table->values, node_index, hash_table->have_big_values);
1336
1337       if (keep_new_key)
1338         {
1339           key_to_free = g_hash_table_fetch_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys);
1340           key_to_keep = new_key;
1341         }
1342       else
1343         {
1344           key_to_free = new_key;
1345           key_to_keep = g_hash_table_fetch_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys);
1346         }
1347     }
1348   else
1349     {
1350       hash_table->hashes[node_index] = key_hash;
1351       key_to_keep = new_key;
1352     }
1353
1354   /* Resize key/value arrays and split table as necessary */
1355   g_hash_table_ensure_keyval_fits (hash_table, key_to_keep, new_value);
1356   g_hash_table_assign_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys, key_to_keep);
1357
1358   /* Step 3: Actually do the write */
1359   g_hash_table_assign_key_or_value (hash_table->values, node_index, hash_table->have_big_values, new_value);
1360
1361   /* Now, the bookkeeping... */
1362   if (!already_exists)
1363     {
1364       hash_table->nnodes++;
1365
1366       if (HASH_IS_UNUSED (old_hash))
1367         {
1368           /* We replaced an empty node, and not a tombstone */
1369           hash_table->noccupied++;
1370           g_hash_table_maybe_resize (hash_table);
1371         }
1372
1373 #ifndef G_DISABLE_ASSERT
1374       hash_table->version++;
1375 #endif
1376     }
1377
1378   if (already_exists)
1379     {
1380       if (hash_table->key_destroy_func && !reusing_key)
1381         (* hash_table->key_destroy_func) (key_to_free);
1382       if (hash_table->value_destroy_func)
1383         (* hash_table->value_destroy_func) (value_to_free);
1384     }
1385
1386   return !already_exists;
1387 }
1388
1389 /**
1390  * g_hash_table_iter_replace:
1391  * @iter: an initialized #GHashTableIter
1392  * @value: the value to replace with
1393  *
1394  * Replaces the value currently pointed to by the iterator
1395  * from its associated #GHashTable. Can only be called after
1396  * g_hash_table_iter_next() returned %TRUE.
1397  *
1398  * If you supplied a @value_destroy_func when creating the
1399  * #GHashTable, the old value is freed using that function.
1400  *
1401  * Since: 2.30
1402  */
1403 void
1404 g_hash_table_iter_replace (GHashTableIter *iter,
1405                            gpointer        value)
1406 {
1407   RealIter *ri;
1408   guint node_hash;
1409   gpointer key;
1410
1411   ri = (RealIter *) iter;
1412
1413   g_return_if_fail (ri != NULL);
1414 #ifndef G_DISABLE_ASSERT
1415   g_return_if_fail (ri->version == ri->hash_table->version);
1416 #endif
1417   g_return_if_fail (ri->position >= 0);
1418   g_return_if_fail ((gsize) ri->position < ri->hash_table->size);
1419
1420   node_hash = ri->hash_table->hashes[ri->position];
1421
1422   key = g_hash_table_fetch_key_or_value (ri->hash_table->keys, ri->position, ri->hash_table->have_big_keys);
1423
1424   g_hash_table_insert_node (ri->hash_table, ri->position, node_hash, key, value, TRUE, TRUE);
1425
1426 #ifndef G_DISABLE_ASSERT
1427   ri->version++;
1428   ri->hash_table->version++;
1429 #endif
1430 }
1431
1432 /**
1433  * g_hash_table_iter_steal:
1434  * @iter: an initialized #GHashTableIter
1435  *
1436  * Removes the key/value pair currently pointed to by the
1437  * iterator from its associated #GHashTable, without calling
1438  * the key and value destroy functions. Can only be called
1439  * after g_hash_table_iter_next() returned %TRUE, and cannot
1440  * be called more than once for the same key/value pair.
1441  *
1442  * Since: 2.16
1443  */
1444 void
1445 g_hash_table_iter_steal (GHashTableIter *iter)
1446 {
1447   iter_remove_or_steal ((RealIter *) iter, FALSE);
1448 }
1449
1450
1451 /**
1452  * g_hash_table_ref:
1453  * @hash_table: a valid #GHashTable
1454  *
1455  * Atomically increments the reference count of @hash_table by one.
1456  * This function is MT-safe and may be called from any thread.
1457  *
1458  * Returns: the passed in #GHashTable
1459  *
1460  * Since: 2.10
1461  */
1462 GHashTable *
1463 g_hash_table_ref (GHashTable *hash_table)
1464 {
1465   g_return_val_if_fail (hash_table != NULL, NULL);
1466
1467   g_atomic_ref_count_inc (&hash_table->ref_count);
1468
1469   return hash_table;
1470 }
1471
1472 /**
1473  * g_hash_table_unref:
1474  * @hash_table: a valid #GHashTable
1475  *
1476  * Atomically decrements the reference count of @hash_table by one.
1477  * If the reference count drops to 0, all keys and values will be
1478  * destroyed, and all memory allocated by the hash table is released.
1479  * This function is MT-safe and may be called from any thread.
1480  *
1481  * Since: 2.10
1482  */
1483 void
1484 g_hash_table_unref (GHashTable *hash_table)
1485 {
1486   g_return_if_fail (hash_table != NULL);
1487
1488   if (g_atomic_ref_count_dec (&hash_table->ref_count))
1489     {
1490       g_hash_table_remove_all_nodes (hash_table, TRUE, TRUE);
1491       if (hash_table->keys != hash_table->values)
1492         g_free (hash_table->values);
1493       g_free (hash_table->keys);
1494       g_free (hash_table->hashes);
1495       g_slice_free (GHashTable, hash_table);
1496     }
1497 }
1498
1499 /**
1500  * g_hash_table_destroy:
1501  * @hash_table: a #GHashTable
1502  *
1503  * Destroys all keys and values in the #GHashTable and decrements its
1504  * reference count by 1. If keys and/or values are dynamically allocated,
1505  * you should either free them first or create the #GHashTable with destroy
1506  * notifiers using g_hash_table_new_full(). In the latter case the destroy
1507  * functions you supplied will be called on all keys and values during the
1508  * destruction phase.
1509  */
1510 void
1511 g_hash_table_destroy (GHashTable *hash_table)
1512 {
1513   g_return_if_fail (hash_table != NULL);
1514
1515   g_hash_table_remove_all (hash_table);
1516   g_hash_table_unref (hash_table);
1517 }
1518
1519 /**
1520  * g_hash_table_lookup:
1521  * @hash_table: a #GHashTable
1522  * @key: the key to look up
1523  *
1524  * Looks up a key in a #GHashTable. Note that this function cannot
1525  * distinguish between a key that is not present and one which is present
1526  * and has the value %NULL. If you need this distinction, use
1527  * g_hash_table_lookup_extended().
1528  *
1529  * Returns: (nullable): the associated value, or %NULL if the key is not found
1530  */
1531 gpointer
1532 g_hash_table_lookup (GHashTable    *hash_table,
1533                      gconstpointer  key)
1534 {
1535   guint node_index;
1536   guint node_hash;
1537
1538   g_return_val_if_fail (hash_table != NULL, NULL);
1539
1540   node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1541
1542   return HASH_IS_REAL (hash_table->hashes[node_index])
1543     ? g_hash_table_fetch_key_or_value (hash_table->values, node_index, hash_table->have_big_values)
1544     : NULL;
1545 }
1546
1547 /**
1548  * g_hash_table_lookup_extended:
1549  * @hash_table: a #GHashTable
1550  * @lookup_key: the key to look up
1551  * @orig_key: (out) (optional): return location for the original key
1552  * @value: (out) (optional) (nullable): return location for the value associated
1553  * with the key
1554  *
1555  * Looks up a key in the #GHashTable, returning the original key and the
1556  * associated value and a #gboolean which is %TRUE if the key was found. This
1557  * is useful if you need to free the memory allocated for the original key,
1558  * for example before calling g_hash_table_remove().
1559  *
1560  * You can actually pass %NULL for @lookup_key to test
1561  * whether the %NULL key exists, provided the hash and equal functions
1562  * of @hash_table are %NULL-safe.
1563  *
1564  * Returns: %TRUE if the key was found in the #GHashTable
1565  */
1566 gboolean
1567 g_hash_table_lookup_extended (GHashTable    *hash_table,
1568                               gconstpointer  lookup_key,
1569                               gpointer      *orig_key,
1570                               gpointer      *value)
1571 {
1572   guint node_index;
1573   guint node_hash;
1574
1575   g_return_val_if_fail (hash_table != NULL, FALSE);
1576
1577   node_index = g_hash_table_lookup_node (hash_table, lookup_key, &node_hash);
1578
1579   if (!HASH_IS_REAL (hash_table->hashes[node_index]))
1580     {
1581       if (orig_key != NULL)
1582         *orig_key = NULL;
1583       if (value != NULL)
1584         *value = NULL;
1585
1586       return FALSE;
1587     }
1588
1589   if (orig_key)
1590     *orig_key = g_hash_table_fetch_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys);
1591
1592   if (value)
1593     *value = g_hash_table_fetch_key_or_value (hash_table->values, node_index, hash_table->have_big_values);
1594
1595   return TRUE;
1596 }
1597
1598 /*
1599  * g_hash_table_insert_internal:
1600  * @hash_table: our #GHashTable
1601  * @key: the key to insert
1602  * @value: the value to insert
1603  * @keep_new_key: if %TRUE and this key already exists in the table
1604  *   then call the destroy notify function on the old key.  If %FALSE
1605  *   then call the destroy notify function on the new key.
1606  *
1607  * Implements the common logic for the g_hash_table_insert() and
1608  * g_hash_table_replace() functions.
1609  *
1610  * Do a lookup of @key. If it is found, replace it with the new
1611  * @value (and perhaps the new @key). If it is not found, create
1612  * a new node.
1613  *
1614  * Returns: %TRUE if the key did not exist yet
1615  */
1616 static gboolean
1617 g_hash_table_insert_internal (GHashTable *hash_table,
1618                               gpointer    key,
1619                               gpointer    value,
1620                               gboolean    keep_new_key)
1621 {
1622   guint key_hash;
1623   guint node_index;
1624
1625   g_return_val_if_fail (hash_table != NULL, FALSE);
1626
1627   node_index = g_hash_table_lookup_node (hash_table, key, &key_hash);
1628
1629   return g_hash_table_insert_node (hash_table, node_index, key_hash, key, value, keep_new_key, FALSE);
1630 }
1631
1632 /**
1633  * g_hash_table_insert:
1634  * @hash_table: a #GHashTable
1635  * @key: a key to insert
1636  * @value: the value to associate with the key
1637  *
1638  * Inserts a new key and value into a #GHashTable.
1639  *
1640  * If the key already exists in the #GHashTable its current
1641  * value is replaced with the new value. If you supplied a
1642  * @value_destroy_func when creating the #GHashTable, the old
1643  * value is freed using that function. If you supplied a
1644  * @key_destroy_func when creating the #GHashTable, the passed
1645  * key is freed using that function.
1646  *
1647  * Starting from GLib 2.40, this function returns a boolean value to
1648  * indicate whether the newly added value was already in the hash table
1649  * or not.
1650  *
1651  * Returns: %TRUE if the key did not exist yet
1652  */
1653 gboolean
1654 g_hash_table_insert (GHashTable *hash_table,
1655                      gpointer    key,
1656                      gpointer    value)
1657 {
1658   return g_hash_table_insert_internal (hash_table, key, value, FALSE);
1659 }
1660
1661 /**
1662  * g_hash_table_replace:
1663  * @hash_table: a #GHashTable
1664  * @key: a key to insert
1665  * @value: the value to associate with the key
1666  *
1667  * Inserts a new key and value into a #GHashTable similar to
1668  * g_hash_table_insert(). The difference is that if the key
1669  * already exists in the #GHashTable, it gets replaced by the
1670  * new key. If you supplied a @value_destroy_func when creating
1671  * the #GHashTable, the old value is freed using that function.
1672  * If you supplied a @key_destroy_func when creating the
1673  * #GHashTable, the old key is freed using that function.
1674  *
1675  * Starting from GLib 2.40, this function returns a boolean value to
1676  * indicate whether the newly added value was already in the hash table
1677  * or not.
1678  *
1679  * Returns: %TRUE if the key did not exist yet
1680  */
1681 gboolean
1682 g_hash_table_replace (GHashTable *hash_table,
1683                       gpointer    key,
1684                       gpointer    value)
1685 {
1686   return g_hash_table_insert_internal (hash_table, key, value, TRUE);
1687 }
1688
1689 /**
1690  * g_hash_table_add:
1691  * @hash_table: a #GHashTable
1692  * @key: (transfer full): a key to insert
1693  *
1694  * This is a convenience function for using a #GHashTable as a set.  It
1695  * is equivalent to calling g_hash_table_replace() with @key as both the
1696  * key and the value.
1697  *
1698  * In particular, this means that if @key already exists in the hash table, then
1699  * the old copy of @key in the hash table is freed and @key replaces it in the
1700  * table.
1701  *
1702  * When a hash table only ever contains keys that have themselves as the
1703  * corresponding value it is able to be stored more efficiently.  See
1704  * the discussion in the section description.
1705  *
1706  * Starting from GLib 2.40, this function returns a boolean value to
1707  * indicate whether the newly added value was already in the hash table
1708  * or not.
1709  *
1710  * Returns: %TRUE if the key did not exist yet
1711  *
1712  * Since: 2.32
1713  */
1714 gboolean
1715 g_hash_table_add (GHashTable *hash_table,
1716                   gpointer    key)
1717 {
1718   return g_hash_table_insert_internal (hash_table, key, key, TRUE);
1719 }
1720
1721 /**
1722  * g_hash_table_contains:
1723  * @hash_table: a #GHashTable
1724  * @key: a key to check
1725  *
1726  * Checks if @key is in @hash_table.
1727  *
1728  * Returns: %TRUE if @key is in @hash_table, %FALSE otherwise.
1729  *
1730  * Since: 2.32
1731  **/
1732 gboolean
1733 g_hash_table_contains (GHashTable    *hash_table,
1734                        gconstpointer  key)
1735 {
1736   guint node_index;
1737   guint node_hash;
1738
1739   g_return_val_if_fail (hash_table != NULL, FALSE);
1740
1741   node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1742
1743   return HASH_IS_REAL (hash_table->hashes[node_index]);
1744 }
1745
1746 /*
1747  * g_hash_table_remove_internal:
1748  * @hash_table: our #GHashTable
1749  * @key: the key to remove
1750  * @notify: %TRUE if the destroy notify handlers are to be called
1751  * Returns: %TRUE if a node was found and removed, else %FALSE
1752  *
1753  * Implements the common logic for the g_hash_table_remove() and
1754  * g_hash_table_steal() functions.
1755  *
1756  * Do a lookup of @key and remove it if it is found, calling the
1757  * destroy notify handlers only if @notify is %TRUE.
1758  */
1759 static gboolean
1760 g_hash_table_remove_internal (GHashTable    *hash_table,
1761                               gconstpointer  key,
1762                               gboolean       notify)
1763 {
1764   guint node_index;
1765   guint node_hash;
1766
1767   g_return_val_if_fail (hash_table != NULL, FALSE);
1768
1769   node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1770
1771   if (!HASH_IS_REAL (hash_table->hashes[node_index]))
1772     return FALSE;
1773
1774   g_hash_table_remove_node (hash_table, node_index, notify);
1775   g_hash_table_maybe_resize (hash_table);
1776
1777 #ifndef G_DISABLE_ASSERT
1778   hash_table->version++;
1779 #endif
1780
1781   return TRUE;
1782 }
1783
1784 /**
1785  * g_hash_table_remove:
1786  * @hash_table: a #GHashTable
1787  * @key: the key to remove
1788  *
1789  * Removes a key and its associated value from a #GHashTable.
1790  *
1791  * If the #GHashTable was created using g_hash_table_new_full(), the
1792  * key and value are freed using the supplied destroy functions, otherwise
1793  * you have to make sure that any dynamically allocated values are freed
1794  * yourself.
1795  *
1796  * Returns: %TRUE if the key was found and removed from the #GHashTable
1797  */
1798 gboolean
1799 g_hash_table_remove (GHashTable    *hash_table,
1800                      gconstpointer  key)
1801 {
1802   return g_hash_table_remove_internal (hash_table, key, TRUE);
1803 }
1804
1805 /**
1806  * g_hash_table_steal:
1807  * @hash_table: a #GHashTable
1808  * @key: the key to remove
1809  *
1810  * Removes a key and its associated value from a #GHashTable without
1811  * calling the key and value destroy functions.
1812  *
1813  * Returns: %TRUE if the key was found and removed from the #GHashTable
1814  */
1815 gboolean
1816 g_hash_table_steal (GHashTable    *hash_table,
1817                     gconstpointer  key)
1818 {
1819   return g_hash_table_remove_internal (hash_table, key, FALSE);
1820 }
1821
1822 /**
1823  * g_hash_table_steal_extended:
1824  * @hash_table: a #GHashTable
1825  * @lookup_key: the key to look up
1826  * @stolen_key: (out) (optional) (transfer full): return location for the
1827  *    original key
1828  * @stolen_value: (out) (optional) (nullable) (transfer full): return location
1829  *    for the value associated with the key
1830  *
1831  * Looks up a key in the #GHashTable, stealing the original key and the
1832  * associated value and returning %TRUE if the key was found. If the key was
1833  * not found, %FALSE is returned.
1834  *
1835  * If found, the stolen key and value are removed from the hash table without
1836  * calling the key and value destroy functions, and ownership is transferred to
1837  * the caller of this method; as with g_hash_table_steal().
1838  *
1839  * You can pass %NULL for @lookup_key, provided the hash and equal functions
1840  * of @hash_table are %NULL-safe.
1841  *
1842  * The dictionary implementation optimizes for having all values identical to
1843  * their keys, for example by using g_hash_table_add(). When stealing both the
1844  * key and the value from such a dictionary, the value will be %NULL.
1845  *
1846  * Returns: %TRUE if the key was found in the #GHashTable
1847  * Since: 2.58
1848  */
1849 gboolean
1850 g_hash_table_steal_extended (GHashTable    *hash_table,
1851                              gconstpointer  lookup_key,
1852                              gpointer      *stolen_key,
1853                              gpointer      *stolen_value)
1854 {
1855   guint node_index;
1856   guint node_hash;
1857
1858   g_return_val_if_fail (hash_table != NULL, FALSE);
1859
1860   node_index = g_hash_table_lookup_node (hash_table, lookup_key, &node_hash);
1861
1862   if (!HASH_IS_REAL (hash_table->hashes[node_index]))
1863     {
1864       if (stolen_key != NULL)
1865         *stolen_key = NULL;
1866       if (stolen_value != NULL)
1867         *stolen_value = NULL;
1868       return FALSE;
1869     }
1870
1871   if (stolen_key != NULL)
1872   {
1873     *stolen_key = g_hash_table_fetch_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys);
1874     g_hash_table_assign_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys, NULL);
1875   }
1876
1877   if (stolen_value != NULL)
1878   {
1879     *stolen_value = g_hash_table_fetch_key_or_value (hash_table->values, node_index, hash_table->have_big_values);
1880     g_hash_table_assign_key_or_value (hash_table->values, node_index, hash_table->have_big_values, NULL);
1881   }
1882
1883   g_hash_table_remove_node (hash_table, node_index, FALSE);
1884   g_hash_table_maybe_resize (hash_table);
1885
1886 #ifndef G_DISABLE_ASSERT
1887   hash_table->version++;
1888 #endif
1889
1890   return TRUE;
1891 }
1892
1893 /**
1894  * g_hash_table_remove_all:
1895  * @hash_table: a #GHashTable
1896  *
1897  * Removes all keys and their associated values from a #GHashTable.
1898  *
1899  * If the #GHashTable was created using g_hash_table_new_full(),
1900  * the keys and values are freed using the supplied destroy functions,
1901  * otherwise you have to make sure that any dynamically allocated
1902  * values are freed yourself.
1903  *
1904  * Since: 2.12
1905  */
1906 void
1907 g_hash_table_remove_all (GHashTable *hash_table)
1908 {
1909   g_return_if_fail (hash_table != NULL);
1910
1911 #ifndef G_DISABLE_ASSERT
1912   if (hash_table->nnodes != 0)
1913     hash_table->version++;
1914 #endif
1915
1916   g_hash_table_remove_all_nodes (hash_table, TRUE, FALSE);
1917   g_hash_table_maybe_resize (hash_table);
1918 }
1919
1920 /**
1921  * g_hash_table_steal_all:
1922  * @hash_table: a #GHashTable
1923  *
1924  * Removes all keys and their associated values from a #GHashTable
1925  * without calling the key and value destroy functions.
1926  *
1927  * Since: 2.12
1928  */
1929 void
1930 g_hash_table_steal_all (GHashTable *hash_table)
1931 {
1932   g_return_if_fail (hash_table != NULL);
1933
1934 #ifndef G_DISABLE_ASSERT
1935   if (hash_table->nnodes != 0)
1936     hash_table->version++;
1937 #endif
1938
1939   g_hash_table_remove_all_nodes (hash_table, FALSE, FALSE);
1940   g_hash_table_maybe_resize (hash_table);
1941 }
1942
1943 /*
1944  * g_hash_table_foreach_remove_or_steal:
1945  * @hash_table: a #GHashTable
1946  * @func: the user's callback function
1947  * @user_data: data for @func
1948  * @notify: %TRUE if the destroy notify handlers are to be called
1949  *
1950  * Implements the common logic for g_hash_table_foreach_remove()
1951  * and g_hash_table_foreach_steal().
1952  *
1953  * Iterates over every node in the table, calling @func with the key
1954  * and value of the node (and @user_data). If @func returns %TRUE the
1955  * node is removed from the table.
1956  *
1957  * If @notify is true then the destroy notify handlers will be called
1958  * for each removed node.
1959  */
1960 static guint
1961 g_hash_table_foreach_remove_or_steal (GHashTable *hash_table,
1962                                       GHRFunc     func,
1963                                       gpointer    user_data,
1964                                       gboolean    notify)
1965 {
1966   guint deleted = 0;
1967   gsize i;
1968 #ifndef G_DISABLE_ASSERT
1969   gint version = hash_table->version;
1970 #endif
1971
1972   for (i = 0; i < hash_table->size; i++)
1973     {
1974       guint node_hash = hash_table->hashes[i];
1975       gpointer node_key = g_hash_table_fetch_key_or_value (hash_table->keys, i, hash_table->have_big_keys);
1976       gpointer node_value = g_hash_table_fetch_key_or_value (hash_table->values, i, hash_table->have_big_values);
1977
1978       if (HASH_IS_REAL (node_hash) &&
1979           (* func) (node_key, node_value, user_data))
1980         {
1981           g_hash_table_remove_node (hash_table, i, notify);
1982           deleted++;
1983         }
1984
1985 #ifndef G_DISABLE_ASSERT
1986       g_return_val_if_fail (version == hash_table->version, 0);
1987 #endif
1988     }
1989
1990   g_hash_table_maybe_resize (hash_table);
1991
1992 #ifndef G_DISABLE_ASSERT
1993   if (deleted > 0)
1994     hash_table->version++;
1995 #endif
1996
1997   return deleted;
1998 }
1999
2000 /**
2001  * g_hash_table_foreach_remove:
2002  * @hash_table: a #GHashTable
2003  * @func: the function to call for each key/value pair
2004  * @user_data: user data to pass to the function
2005  *
2006  * Calls the given function for each key/value pair in the
2007  * #GHashTable. If the function returns %TRUE, then the key/value
2008  * pair is removed from the #GHashTable. If you supplied key or
2009  * value destroy functions when creating the #GHashTable, they are
2010  * used to free the memory allocated for the removed keys and values.
2011  *
2012  * See #GHashTableIter for an alternative way to loop over the
2013  * key/value pairs in the hash table.
2014  *
2015  * Returns: the number of key/value pairs removed
2016  */
2017 guint
2018 g_hash_table_foreach_remove (GHashTable *hash_table,
2019                              GHRFunc     func,
2020                              gpointer    user_data)
2021 {
2022   g_return_val_if_fail (hash_table != NULL, 0);
2023   g_return_val_if_fail (func != NULL, 0);
2024
2025   return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, TRUE);
2026 }
2027
2028 /**
2029  * g_hash_table_foreach_steal:
2030  * @hash_table: a #GHashTable
2031  * @func: the function to call for each key/value pair
2032  * @user_data: user data to pass to the function
2033  *
2034  * Calls the given function for each key/value pair in the
2035  * #GHashTable. If the function returns %TRUE, then the key/value
2036  * pair is removed from the #GHashTable, but no key or value
2037  * destroy functions are called.
2038  *
2039  * See #GHashTableIter for an alternative way to loop over the
2040  * key/value pairs in the hash table.
2041  *
2042  * Returns: the number of key/value pairs removed.
2043  */
2044 guint
2045 g_hash_table_foreach_steal (GHashTable *hash_table,
2046                             GHRFunc     func,
2047                             gpointer    user_data)
2048 {
2049   g_return_val_if_fail (hash_table != NULL, 0);
2050   g_return_val_if_fail (func != NULL, 0);
2051
2052   return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, FALSE);
2053 }
2054
2055 /**
2056  * g_hash_table_foreach:
2057  * @hash_table: a #GHashTable
2058  * @func: the function to call for each key/value pair
2059  * @user_data: user data to pass to the function
2060  *
2061  * Calls the given function for each of the key/value pairs in the
2062  * #GHashTable.  The function is passed the key and value of each
2063  * pair, and the given @user_data parameter.  The hash table may not
2064  * be modified while iterating over it (you can't add/remove
2065  * items). To remove all items matching a predicate, use
2066  * g_hash_table_foreach_remove().
2067  *
2068  * The order in which g_hash_table_foreach() iterates over the keys/values in
2069  * the hash table is not defined.
2070  *
2071  * See g_hash_table_find() for performance caveats for linear
2072  * order searches in contrast to g_hash_table_lookup().
2073  */
2074 void
2075 g_hash_table_foreach (GHashTable *hash_table,
2076                       GHFunc      func,
2077                       gpointer    user_data)
2078 {
2079   gsize i;
2080 #ifndef G_DISABLE_ASSERT
2081   gint version;
2082 #endif
2083
2084   g_return_if_fail (hash_table != NULL);
2085   g_return_if_fail (func != NULL);
2086
2087 #ifndef G_DISABLE_ASSERT
2088   version = hash_table->version;
2089 #endif
2090
2091   for (i = 0; i < hash_table->size; i++)
2092     {
2093       guint node_hash = hash_table->hashes[i];
2094       gpointer node_key = g_hash_table_fetch_key_or_value (hash_table->keys, i, hash_table->have_big_keys);
2095       gpointer node_value = g_hash_table_fetch_key_or_value (hash_table->values, i, hash_table->have_big_values);
2096
2097       if (HASH_IS_REAL (node_hash))
2098         (* func) (node_key, node_value, user_data);
2099
2100 #ifndef G_DISABLE_ASSERT
2101       g_return_if_fail (version == hash_table->version);
2102 #endif
2103     }
2104 }
2105
2106 /**
2107  * g_hash_table_find:
2108  * @hash_table: a #GHashTable
2109  * @predicate: function to test the key/value pairs for a certain property
2110  * @user_data: user data to pass to the function
2111  *
2112  * Calls the given function for key/value pairs in the #GHashTable
2113  * until @predicate returns %TRUE. The function is passed the key
2114  * and value of each pair, and the given @user_data parameter. The
2115  * hash table may not be modified while iterating over it (you can't
2116  * add/remove items).
2117  *
2118  * Note, that hash tables are really only optimized for forward
2119  * lookups, i.e. g_hash_table_lookup(). So code that frequently issues
2120  * g_hash_table_find() or g_hash_table_foreach() (e.g. in the order of
2121  * once per every entry in a hash table) should probably be reworked
2122  * to use additional or different data structures for reverse lookups
2123  * (keep in mind that an O(n) find/foreach operation issued for all n
2124  * values in a hash table ends up needing O(n*n) operations).
2125  *
2126  * Returns: (nullable): The value of the first key/value pair is returned,
2127  *     for which @predicate evaluates to %TRUE. If no pair with the
2128  *     requested property is found, %NULL is returned.
2129  *
2130  * Since: 2.4
2131  */
2132 gpointer
2133 g_hash_table_find (GHashTable *hash_table,
2134                    GHRFunc     predicate,
2135                    gpointer    user_data)
2136 {
2137   gsize i;
2138 #ifndef G_DISABLE_ASSERT
2139   gint version;
2140 #endif
2141   gboolean match;
2142
2143   g_return_val_if_fail (hash_table != NULL, NULL);
2144   g_return_val_if_fail (predicate != NULL, NULL);
2145
2146 #ifndef G_DISABLE_ASSERT
2147   version = hash_table->version;
2148 #endif
2149
2150   match = FALSE;
2151
2152   for (i = 0; i < hash_table->size; i++)
2153     {
2154       guint node_hash = hash_table->hashes[i];
2155       gpointer node_key = g_hash_table_fetch_key_or_value (hash_table->keys, i, hash_table->have_big_keys);
2156       gpointer node_value = g_hash_table_fetch_key_or_value (hash_table->values, i, hash_table->have_big_values);
2157
2158       if (HASH_IS_REAL (node_hash))
2159         match = predicate (node_key, node_value, user_data);
2160
2161 #ifndef G_DISABLE_ASSERT
2162       g_return_val_if_fail (version == hash_table->version, NULL);
2163 #endif
2164
2165       if (match)
2166         return node_value;
2167     }
2168
2169   return NULL;
2170 }
2171
2172 /**
2173  * g_hash_table_size:
2174  * @hash_table: a #GHashTable
2175  *
2176  * Returns the number of elements contained in the #GHashTable.
2177  *
2178  * Returns: the number of key/value pairs in the #GHashTable.
2179  */
2180 guint
2181 g_hash_table_size (GHashTable *hash_table)
2182 {
2183   g_return_val_if_fail (hash_table != NULL, 0);
2184
2185   return hash_table->nnodes;
2186 }
2187
2188 /**
2189  * g_hash_table_get_keys:
2190  * @hash_table: a #GHashTable
2191  *
2192  * Retrieves every key inside @hash_table. The returned data is valid
2193  * until changes to the hash release those keys.
2194  *
2195  * This iterates over every entry in the hash table to build its return value.
2196  * To iterate over the entries in a #GHashTable more efficiently, use a
2197  * #GHashTableIter.
2198  *
2199  * Returns: (transfer container): a #GList containing all the keys
2200  *     inside the hash table. The content of the list is owned by the
2201  *     hash table and should not be modified or freed. Use g_list_free()
2202  *     when done using the list.
2203  *
2204  * Since: 2.14
2205  */
2206 GList *
2207 g_hash_table_get_keys (GHashTable *hash_table)
2208 {
2209   gsize i;
2210   GList *retval;
2211
2212   g_return_val_if_fail (hash_table != NULL, NULL);
2213
2214   retval = NULL;
2215   for (i = 0; i < hash_table->size; i++)
2216     {
2217       if (HASH_IS_REAL (hash_table->hashes[i]))
2218         retval = g_list_prepend (retval, g_hash_table_fetch_key_or_value (hash_table->keys, i, hash_table->have_big_keys));
2219     }
2220
2221   return retval;
2222 }
2223
2224 /**
2225  * g_hash_table_get_keys_as_array:
2226  * @hash_table: a #GHashTable
2227  * @length: (out) (optional): the length of the returned array
2228  *
2229  * Retrieves every key inside @hash_table, as an array.
2230  *
2231  * The returned array is %NULL-terminated but may contain %NULL as a
2232  * key.  Use @length to determine the true length if it's possible that
2233  * %NULL was used as the value for a key.
2234  *
2235  * Note: in the common case of a string-keyed #GHashTable, the return
2236  * value of this function can be conveniently cast to (const gchar **).
2237  *
2238  * This iterates over every entry in the hash table to build its return value.
2239  * To iterate over the entries in a #GHashTable more efficiently, use a
2240  * #GHashTableIter.
2241  *
2242  * You should always free the return result with g_free().  In the
2243  * above-mentioned case of a string-keyed hash table, it may be
2244  * appropriate to use g_strfreev() if you call g_hash_table_steal_all()
2245  * first to transfer ownership of the keys.
2246  *
2247  * Returns: (array length=length) (transfer container): a
2248  *   %NULL-terminated array containing each key from the table.
2249  *
2250  * Since: 2.40
2251  **/
2252 gpointer *
2253 g_hash_table_get_keys_as_array (GHashTable *hash_table,
2254                                 guint      *length)
2255 {
2256   gpointer *result;
2257   gsize i, j = 0;
2258
2259   result = g_new (gpointer, hash_table->nnodes + 1);
2260   for (i = 0; i < hash_table->size; i++)
2261     {
2262       if (HASH_IS_REAL (hash_table->hashes[i]))
2263         result[j++] = g_hash_table_fetch_key_or_value (hash_table->keys, i, hash_table->have_big_keys);
2264     }
2265   g_assert_cmpint (j, ==, hash_table->nnodes);
2266   result[j] = NULL;
2267
2268   if (length)
2269     *length = j;
2270
2271   return result;
2272 }
2273
2274 /**
2275  * g_hash_table_get_values:
2276  * @hash_table: a #GHashTable
2277  *
2278  * Retrieves every value inside @hash_table. The returned data
2279  * is valid until @hash_table is modified.
2280  *
2281  * This iterates over every entry in the hash table to build its return value.
2282  * To iterate over the entries in a #GHashTable more efficiently, use a
2283  * #GHashTableIter.
2284  *
2285  * Returns: (transfer container): a #GList containing all the values
2286  *     inside the hash table. The content of the list is owned by the
2287  *     hash table and should not be modified or freed. Use g_list_free()
2288  *     when done using the list.
2289  *
2290  * Since: 2.14
2291  */
2292 GList *
2293 g_hash_table_get_values (GHashTable *hash_table)
2294 {
2295   gsize i;
2296   GList *retval;
2297
2298   g_return_val_if_fail (hash_table != NULL, NULL);
2299
2300   retval = NULL;
2301   for (i = 0; i < hash_table->size; i++)
2302     {
2303       if (HASH_IS_REAL (hash_table->hashes[i]))
2304         retval = g_list_prepend (retval, g_hash_table_fetch_key_or_value (hash_table->values, i, hash_table->have_big_values));
2305     }
2306
2307   return retval;
2308 }
2309
2310 /* Hash functions.
2311  */
2312
2313 /**
2314  * g_str_equal:
2315  * @v1: (not nullable): a key
2316  * @v2: (not nullable): a key to compare with @v1
2317  *
2318  * Compares two strings for byte-by-byte equality and returns %TRUE
2319  * if they are equal. It can be passed to g_hash_table_new() as the
2320  * @key_equal_func parameter, when using non-%NULL strings as keys in a
2321  * #GHashTable.
2322  *
2323  * This function is typically used for hash table comparisons, but can be used
2324  * for general purpose comparisons of non-%NULL strings. For a %NULL-safe string
2325  * comparison function, see g_strcmp0().
2326  *
2327  * Returns: %TRUE if the two keys match
2328  */
2329 gboolean
2330 (g_str_equal) (gconstpointer v1,
2331                gconstpointer v2)
2332 {
2333   const gchar *string1 = v1;
2334   const gchar *string2 = v2;
2335
2336   return strcmp (string1, string2) == 0;
2337 }
2338
2339 /**
2340  * g_str_hash:
2341  * @v: (not nullable): a string key
2342  *
2343  * Converts a string to a hash value.
2344  *
2345  * This function implements the widely used "djb" hash apparently
2346  * posted by Daniel Bernstein to comp.lang.c some time ago.  The 32
2347  * bit unsigned hash value starts at 5381 and for each byte 'c' in
2348  * the string, is updated: `hash = hash * 33 + c`. This function
2349  * uses the signed value of each byte.
2350  *
2351  * It can be passed to g_hash_table_new() as the @hash_func parameter,
2352  * when using non-%NULL strings as keys in a #GHashTable.
2353  *
2354  * Note that this function may not be a perfect fit for all use cases.
2355  * For example, it produces some hash collisions with strings as short
2356  * as 2.
2357  *
2358  * Returns: a hash value corresponding to the key
2359  */
2360 guint
2361 g_str_hash (gconstpointer v)
2362 {
2363   const signed char *p;
2364   guint32 h = 5381;
2365
2366   for (p = v; *p != '\0'; p++)
2367     h = (h << 5) + h + *p;
2368
2369   return h;
2370 }
2371
2372 /**
2373  * g_direct_hash:
2374  * @v: (nullable): a #gpointer key
2375  *
2376  * Converts a gpointer to a hash value.
2377  * It can be passed to g_hash_table_new() as the @hash_func parameter,
2378  * when using opaque pointers compared by pointer value as keys in a
2379  * #GHashTable.
2380  *
2381  * This hash function is also appropriate for keys that are integers
2382  * stored in pointers, such as `GINT_TO_POINTER (n)`.
2383  *
2384  * Returns: a hash value corresponding to the key.
2385  */
2386 guint
2387 g_direct_hash (gconstpointer v)
2388 {
2389   return GPOINTER_TO_UINT (v);
2390 }
2391
2392 /**
2393  * g_direct_equal:
2394  * @v1: (nullable): a key
2395  * @v2: (nullable): a key to compare with @v1
2396  *
2397  * Compares two #gpointer arguments and returns %TRUE if they are equal.
2398  * It can be passed to g_hash_table_new() as the @key_equal_func
2399  * parameter, when using opaque pointers compared by pointer value as
2400  * keys in a #GHashTable.
2401  *
2402  * This equality function is also appropriate for keys that are integers
2403  * stored in pointers, such as `GINT_TO_POINTER (n)`.
2404  *
2405  * Returns: %TRUE if the two keys match.
2406  */
2407 gboolean
2408 g_direct_equal (gconstpointer v1,
2409                 gconstpointer v2)
2410 {
2411   return v1 == v2;
2412 }
2413
2414 /**
2415  * g_int_equal:
2416  * @v1: (not nullable): a pointer to a #gint key
2417  * @v2: (not nullable): a pointer to a #gint key to compare with @v1
2418  *
2419  * Compares the two #gint values being pointed to and returns
2420  * %TRUE if they are equal.
2421  * It can be passed to g_hash_table_new() as the @key_equal_func
2422  * parameter, when using non-%NULL pointers to integers as keys in a
2423  * #GHashTable.
2424  *
2425  * Note that this function acts on pointers to #gint, not on #gint
2426  * directly: if your hash table's keys are of the form
2427  * `GINT_TO_POINTER (n)`, use g_direct_equal() instead.
2428  *
2429  * Returns: %TRUE if the two keys match.
2430  */
2431 gboolean
2432 g_int_equal (gconstpointer v1,
2433              gconstpointer v2)
2434 {
2435   return *((const gint*) v1) == *((const gint*) v2);
2436 }
2437
2438 /**
2439  * g_int_hash:
2440  * @v: (not nullable): a pointer to a #gint key
2441  *
2442  * Converts a pointer to a #gint to a hash value.
2443  * It can be passed to g_hash_table_new() as the @hash_func parameter,
2444  * when using non-%NULL pointers to integer values as keys in a #GHashTable.
2445  *
2446  * Note that this function acts on pointers to #gint, not on #gint
2447  * directly: if your hash table's keys are of the form
2448  * `GINT_TO_POINTER (n)`, use g_direct_hash() instead.
2449  *
2450  * Returns: a hash value corresponding to the key.
2451  */
2452 guint
2453 g_int_hash (gconstpointer v)
2454 {
2455   return *(const gint*) v;
2456 }
2457
2458 /**
2459  * g_int64_equal:
2460  * @v1: (not nullable): a pointer to a #gint64 key
2461  * @v2: (not nullable): a pointer to a #gint64 key to compare with @v1
2462  *
2463  * Compares the two #gint64 values being pointed to and returns
2464  * %TRUE if they are equal.
2465  * It can be passed to g_hash_table_new() as the @key_equal_func
2466  * parameter, when using non-%NULL pointers to 64-bit integers as keys in a
2467  * #GHashTable.
2468  *
2469  * Returns: %TRUE if the two keys match.
2470  *
2471  * Since: 2.22
2472  */
2473 gboolean
2474 g_int64_equal (gconstpointer v1,
2475                gconstpointer v2)
2476 {
2477   return *((const gint64*) v1) == *((const gint64*) v2);
2478 }
2479
2480 /**
2481  * g_int64_hash:
2482  * @v: (not nullable): a pointer to a #gint64 key
2483  *
2484  * Converts a pointer to a #gint64 to a hash value.
2485  *
2486  * It can be passed to g_hash_table_new() as the @hash_func parameter,
2487  * when using non-%NULL pointers to 64-bit integer values as keys in a
2488  * #GHashTable.
2489  *
2490  * Returns: a hash value corresponding to the key.
2491  *
2492  * Since: 2.22
2493  */
2494 guint
2495 g_int64_hash (gconstpointer v)
2496 {
2497   return (guint) *(const gint64*) v;
2498 }
2499
2500 /**
2501  * g_double_equal:
2502  * @v1: (not nullable): a pointer to a #gdouble key
2503  * @v2: (not nullable): a pointer to a #gdouble key to compare with @v1
2504  *
2505  * Compares the two #gdouble values being pointed to and returns
2506  * %TRUE if they are equal.
2507  * It can be passed to g_hash_table_new() as the @key_equal_func
2508  * parameter, when using non-%NULL pointers to doubles as keys in a
2509  * #GHashTable.
2510  *
2511  * Returns: %TRUE if the two keys match.
2512  *
2513  * Since: 2.22
2514  */
2515 gboolean
2516 g_double_equal (gconstpointer v1,
2517                 gconstpointer v2)
2518 {
2519   return *((const gdouble*) v1) == *((const gdouble*) v2);
2520 }
2521
2522 /**
2523  * g_double_hash:
2524  * @v: (not nullable): a pointer to a #gdouble key
2525  *
2526  * Converts a pointer to a #gdouble to a hash value.
2527  * It can be passed to g_hash_table_new() as the @hash_func parameter,
2528  * It can be passed to g_hash_table_new() as the @hash_func parameter,
2529  * when using non-%NULL pointers to doubles as keys in a #GHashTable.
2530  *
2531  * Returns: a hash value corresponding to the key.
2532  *
2533  * Since: 2.22
2534  */
2535 guint
2536 g_double_hash (gconstpointer v)
2537 {
2538   return (guint) *(const gdouble*) v;
2539 }