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