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