ghash.c: fix docs
[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    key,
838                           gpointer    value,
839                           gboolean    keep_new_key,
840                           gboolean    reusing_key)
841 {
842   guint old_hash;
843   gpointer old_key;
844   gpointer old_value;
845
846   if (G_UNLIKELY (hash_table->keys == hash_table->values && key != value))
847     hash_table->values = g_memdup (hash_table->keys, sizeof (gpointer) * hash_table->size);
848
849   old_hash = hash_table->hashes[node_index];
850   old_key = hash_table->keys[node_index];
851   old_value = hash_table->values[node_index];
852
853   if (HASH_IS_REAL (old_hash))
854     {
855       if (keep_new_key)
856         hash_table->keys[node_index] = key;
857       hash_table->values[node_index] = value;
858     }
859   else
860     {
861       hash_table->keys[node_index] = key;
862       hash_table->values[node_index] = value;
863       hash_table->hashes[node_index] = key_hash;
864
865       hash_table->nnodes++;
866
867       if (HASH_IS_UNUSED (old_hash))
868         {
869           /* We replaced an empty node, and not a tombstone */
870           hash_table->noccupied++;
871           g_hash_table_maybe_resize (hash_table);
872         }
873
874 #ifndef G_DISABLE_ASSERT
875       hash_table->version++;
876 #endif
877     }
878
879   if (HASH_IS_REAL (old_hash))
880     {
881       if (hash_table->key_destroy_func && !reusing_key)
882         hash_table->key_destroy_func (keep_new_key ? old_key : key);
883       if (hash_table->value_destroy_func)
884         hash_table->value_destroy_func (old_value);
885     }
886 }
887
888 /**
889  * g_hash_table_iter_replace:
890  * @iter: an initialized #GHashTableIter
891  * @value: the value to replace with
892  *
893  * Replaces the value currently pointed to by the iterator
894  * from its associated #GHashTable. Can only be called after
895  * g_hash_table_iter_next() returned %TRUE.
896  *
897  * If you supplied a @value_destroy_func when creating the
898  * #GHashTable, the old value is freed using that function.
899  *
900  * Since: 2.30
901  */
902 void
903 g_hash_table_iter_replace (GHashTableIter *iter,
904                            gpointer        value)
905 {
906   RealIter *ri;
907   guint node_hash;
908   gpointer key;
909
910   ri = (RealIter *) iter;
911
912   g_return_if_fail (ri != NULL);
913 #ifndef G_DISABLE_ASSERT
914   g_return_if_fail (ri->version == ri->hash_table->version);
915 #endif
916   g_return_if_fail (ri->position >= 0);
917   g_return_if_fail (ri->position < ri->hash_table->size);
918
919   node_hash = ri->hash_table->hashes[ri->position];
920   key = ri->hash_table->keys[ri->position];
921
922   g_hash_table_insert_node (ri->hash_table, ri->position, node_hash, key, value, TRUE, TRUE);
923
924 #ifndef G_DISABLE_ASSERT
925   ri->version++;
926   ri->hash_table->version++;
927 #endif
928 }
929
930 /**
931  * g_hash_table_iter_steal:
932  * @iter: an initialized #GHashTableIter
933  *
934  * Removes the key/value pair currently pointed to by the
935  * iterator from its associated #GHashTable, without calling
936  * the key and value destroy functions. Can only be called
937  * after g_hash_table_iter_next() returned %TRUE, and cannot
938  * be called more than once for the same key/value pair.
939  *
940  * Since: 2.16
941  */
942 void
943 g_hash_table_iter_steal (GHashTableIter *iter)
944 {
945   iter_remove_or_steal ((RealIter *) iter, FALSE);
946 }
947
948
949 /**
950  * g_hash_table_ref:
951  * @hash_table: a valid #GHashTable
952  *
953  * Atomically increments the reference count of @hash_table by one.
954  * This function is MT-safe and may be called from any thread.
955  *
956  * Return value: the passed in #GHashTable
957  *
958  * Since: 2.10
959  */
960 GHashTable *
961 g_hash_table_ref (GHashTable *hash_table)
962 {
963   g_return_val_if_fail (hash_table != NULL, NULL);
964
965   g_atomic_int_inc (&hash_table->ref_count);
966
967   return hash_table;
968 }
969
970 /**
971  * g_hash_table_unref:
972  * @hash_table: a valid #GHashTable
973  *
974  * Atomically decrements the reference count of @hash_table by one.
975  * If the reference count drops to 0, all keys and values will be
976  * destroyed, and all memory allocated by the hash table is released.
977  * This function is MT-safe and may be called from any thread.
978  *
979  * Since: 2.10
980  */
981 void
982 g_hash_table_unref (GHashTable *hash_table)
983 {
984   g_return_if_fail (hash_table != NULL);
985
986   if (g_atomic_int_dec_and_test (&hash_table->ref_count))
987     {
988       g_hash_table_remove_all_nodes (hash_table, TRUE);
989       if (hash_table->keys != hash_table->values)
990         g_free (hash_table->values);
991       g_free (hash_table->keys);
992       g_free (hash_table->hashes);
993       g_slice_free (GHashTable, hash_table);
994     }
995 }
996
997 /**
998  * g_hash_table_destroy:
999  * @hash_table: a #GHashTable
1000  *
1001  * Destroys all keys and values in the #GHashTable and decrements its
1002  * reference count by 1. If keys and/or values are dynamically allocated,
1003  * you should either free them first or create the #GHashTable with destroy
1004  * notifiers using g_hash_table_new_full(). In the latter case the destroy
1005  * functions you supplied will be called on all keys and values during the
1006  * destruction phase.
1007  */
1008 void
1009 g_hash_table_destroy (GHashTable *hash_table)
1010 {
1011   g_return_if_fail (hash_table != NULL);
1012
1013   g_hash_table_remove_all (hash_table);
1014   g_hash_table_unref (hash_table);
1015 }
1016
1017 /**
1018  * g_hash_table_lookup:
1019  * @hash_table: a #GHashTable
1020  * @key: the key to look up
1021  *
1022  * Looks up a key in a #GHashTable. Note that this function cannot
1023  * distinguish between a key that is not present and one which is present
1024  * and has the value %NULL. If you need this distinction, use
1025  * g_hash_table_lookup_extended().
1026  *
1027  * Return value: (allow-none): the associated value, or %NULL if the key is not found
1028  */
1029 gpointer
1030 g_hash_table_lookup (GHashTable    *hash_table,
1031                      gconstpointer  key)
1032 {
1033   guint node_index;
1034   guint node_hash;
1035
1036   g_return_val_if_fail (hash_table != NULL, NULL);
1037
1038   node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1039
1040   return HASH_IS_REAL (hash_table->hashes[node_index])
1041     ? hash_table->values[node_index]
1042     : NULL;
1043 }
1044
1045 /**
1046  * g_hash_table_lookup_extended:
1047  * @hash_table: a #GHashTable
1048  * @lookup_key: the key to look up
1049  * @orig_key: (allow-none): return location for the original key, or %NULL
1050  * @value: (allow-none): return location for the value associated with the key, or %NULL
1051  *
1052  * Looks up a key in the #GHashTable, returning the original key and the
1053  * associated value and a #gboolean which is %TRUE if the key was found. This
1054  * is useful if you need to free the memory allocated for the original key,
1055  * for example before calling g_hash_table_remove().
1056  *
1057  * You can actually pass %NULL for @lookup_key to test
1058  * whether the %NULL key exists, provided the hash and equal functions
1059  * of @hash_table are %NULL-safe.
1060  *
1061  * Return value: %TRUE if the key was found in the #GHashTable
1062  */
1063 gboolean
1064 g_hash_table_lookup_extended (GHashTable    *hash_table,
1065                               gconstpointer  lookup_key,
1066                               gpointer      *orig_key,
1067                               gpointer      *value)
1068 {
1069   guint node_index;
1070   guint node_hash;
1071
1072   g_return_val_if_fail (hash_table != NULL, FALSE);
1073
1074   node_index = g_hash_table_lookup_node (hash_table, lookup_key, &node_hash);
1075
1076   if (!HASH_IS_REAL (hash_table->hashes[node_index]))
1077     return FALSE;
1078
1079   if (orig_key)
1080     *orig_key = hash_table->keys[node_index];
1081
1082   if (value)
1083     *value = hash_table->values[node_index];
1084
1085   return TRUE;
1086 }
1087
1088 /*
1089  * g_hash_table_insert_internal:
1090  * @hash_table: our #GHashTable
1091  * @key: the key to insert
1092  * @value: the value to insert
1093  * @keep_new_key: if %TRUE and this key already exists in the table
1094  *   then call the destroy notify function on the old key.  If %FALSE
1095  *   then call the destroy notify function on the new key.
1096  *
1097  * Implements the common logic for the g_hash_table_insert() and
1098  * g_hash_table_replace() functions.
1099  *
1100  * Do a lookup of @key. If it is found, replace it with the new
1101  * @value (and perhaps the new @key). If it is not found, create
1102  * a new node.
1103  */
1104 static void
1105 g_hash_table_insert_internal (GHashTable *hash_table,
1106                               gpointer    key,
1107                               gpointer    value,
1108                               gboolean    keep_new_key)
1109 {
1110   guint key_hash;
1111   guint node_index;
1112
1113   g_return_if_fail (hash_table != NULL);
1114
1115   node_index = g_hash_table_lookup_node (hash_table, key, &key_hash);
1116
1117   g_hash_table_insert_node (hash_table, node_index, key_hash, key, value, keep_new_key, FALSE);
1118 }
1119
1120 /**
1121  * g_hash_table_insert:
1122  * @hash_table: a #GHashTable
1123  * @key: a key to insert
1124  * @value: the value to associate with the key
1125  *
1126  * Inserts a new key and value into a #GHashTable.
1127  *
1128  * If the key already exists in the #GHashTable its current
1129  * value is replaced with the new value. If you supplied a
1130  * @value_destroy_func when creating the #GHashTable, the old
1131  * value is freed using that function. If you supplied a
1132  * @key_destroy_func when creating the #GHashTable, the passed
1133  * key is freed using that function.
1134  */
1135 void
1136 g_hash_table_insert (GHashTable *hash_table,
1137                      gpointer    key,
1138                      gpointer    value)
1139 {
1140   g_hash_table_insert_internal (hash_table, key, value, FALSE);
1141 }
1142
1143 /**
1144  * g_hash_table_replace:
1145  * @hash_table: a #GHashTable
1146  * @key: a key to insert
1147  * @value: the value to associate with the key
1148  *
1149  * Inserts a new key and value into a #GHashTable similar to
1150  * g_hash_table_insert(). The difference is that if the key
1151  * already exists in the #GHashTable, it gets replaced by the
1152  * new key. If you supplied a @value_destroy_func when creating
1153  * the #GHashTable, the old value is freed using that function.
1154  * If you supplied a @key_destroy_func when creating the
1155  * #GHashTable, the old key is freed using that function.
1156  */
1157 void
1158 g_hash_table_replace (GHashTable *hash_table,
1159                       gpointer    key,
1160                       gpointer    value)
1161 {
1162   g_hash_table_insert_internal (hash_table, key, value, TRUE);
1163 }
1164
1165 /**
1166  * g_hash_table_add:
1167  * @hash_table: a #GHashTable
1168  * @key: a key to insert
1169  *
1170  * This is a convenience function for using a #GHashTable as a set.  It
1171  * is equivalent to calling g_hash_table_replace() with @key as both the
1172  * key and the value.
1173  *
1174  * When a hash table only ever contains keys that have themselves as the
1175  * corresponding value it is able to be stored more efficiently.  See
1176  * the discussion in the section description.
1177  *
1178  * Since: 2.32
1179  **/
1180 void
1181 g_hash_table_add (GHashTable *hash_table,
1182                   gpointer    key)
1183 {
1184   g_hash_table_insert_internal (hash_table, key, key, TRUE);
1185 }
1186
1187 /**
1188  * g_hash_table_contains:
1189  * @hash_table: a #GHashTable
1190  * @key: a key to check
1191  *
1192  * Checks if @key is in @hash_table.
1193  *
1194  * Since: 2.32
1195  **/
1196 gboolean
1197 g_hash_table_contains (GHashTable    *hash_table,
1198                        gconstpointer  key)
1199 {
1200   guint node_index;
1201   guint node_hash;
1202
1203   g_return_val_if_fail (hash_table != NULL, FALSE);
1204
1205   node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1206
1207   return HASH_IS_REAL (hash_table->hashes[node_index]);
1208 }
1209
1210 /*
1211  * g_hash_table_remove_internal:
1212  * @hash_table: our #GHashTable
1213  * @key: the key to remove
1214  * @notify: %TRUE if the destroy notify handlers are to be called
1215  * Return value: %TRUE if a node was found and removed, else %FALSE
1216  *
1217  * Implements the common logic for the g_hash_table_remove() and
1218  * g_hash_table_steal() functions.
1219  *
1220  * Do a lookup of @key and remove it if it is found, calling the
1221  * destroy notify handlers only if @notify is %TRUE.
1222  */
1223 static gboolean
1224 g_hash_table_remove_internal (GHashTable    *hash_table,
1225                               gconstpointer  key,
1226                               gboolean       notify)
1227 {
1228   guint node_index;
1229   guint node_hash;
1230
1231   g_return_val_if_fail (hash_table != NULL, FALSE);
1232
1233   node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1234
1235   if (!HASH_IS_REAL (hash_table->hashes[node_index]))
1236     return FALSE;
1237
1238   g_hash_table_remove_node (hash_table, node_index, notify);
1239   g_hash_table_maybe_resize (hash_table);
1240
1241 #ifndef G_DISABLE_ASSERT
1242   hash_table->version++;
1243 #endif
1244
1245   return TRUE;
1246 }
1247
1248 /**
1249  * g_hash_table_remove:
1250  * @hash_table: a #GHashTable
1251  * @key: the key to remove
1252  *
1253  * Removes a key and its associated value from a #GHashTable.
1254  *
1255  * If the #GHashTable was created using g_hash_table_new_full(), the
1256  * key and value are freed using the supplied destroy functions, otherwise
1257  * you have to make sure that any dynamically allocated values are freed
1258  * yourself.
1259  *
1260  * Returns: %TRUE if the key was found and removed from the #GHashTable
1261  */
1262 gboolean
1263 g_hash_table_remove (GHashTable    *hash_table,
1264                      gconstpointer  key)
1265 {
1266   return g_hash_table_remove_internal (hash_table, key, TRUE);
1267 }
1268
1269 /**
1270  * g_hash_table_steal:
1271  * @hash_table: a #GHashTable
1272  * @key: the key to remove
1273  *
1274  * Removes a key and its associated value from a #GHashTable without
1275  * calling the key and value destroy functions.
1276  *
1277  * Returns: %TRUE if the key was found and removed from the #GHashTable
1278  */
1279 gboolean
1280 g_hash_table_steal (GHashTable    *hash_table,
1281                     gconstpointer  key)
1282 {
1283   return g_hash_table_remove_internal (hash_table, key, FALSE);
1284 }
1285
1286 /**
1287  * g_hash_table_remove_all:
1288  * @hash_table: a #GHashTable
1289  *
1290  * Removes all keys and their associated values from a #GHashTable.
1291  *
1292  * If the #GHashTable was created using g_hash_table_new_full(),
1293  * the keys and values are freed using the supplied destroy functions,
1294  * otherwise you have to make sure that any dynamically allocated
1295  * values are freed yourself.
1296  *
1297  * Since: 2.12
1298  */
1299 void
1300 g_hash_table_remove_all (GHashTable *hash_table)
1301 {
1302   g_return_if_fail (hash_table != NULL);
1303
1304 #ifndef G_DISABLE_ASSERT
1305   if (hash_table->nnodes != 0)
1306     hash_table->version++;
1307 #endif
1308
1309   g_hash_table_remove_all_nodes (hash_table, TRUE);
1310   g_hash_table_maybe_resize (hash_table);
1311 }
1312
1313 /**
1314  * g_hash_table_steal_all:
1315  * @hash_table: a #GHashTable
1316  *
1317  * Removes all keys and their associated values from a #GHashTable
1318  * without calling the key and value destroy functions.
1319  *
1320  * Since: 2.12
1321  */
1322 void
1323 g_hash_table_steal_all (GHashTable *hash_table)
1324 {
1325   g_return_if_fail (hash_table != NULL);
1326
1327 #ifndef G_DISABLE_ASSERT
1328   if (hash_table->nnodes != 0)
1329     hash_table->version++;
1330 #endif
1331
1332   g_hash_table_remove_all_nodes (hash_table, FALSE);
1333   g_hash_table_maybe_resize (hash_table);
1334 }
1335
1336 /*
1337  * g_hash_table_foreach_remove_or_steal:
1338  * @hash_table: a #GHashTable
1339  * @func: the user's callback function
1340  * @user_data: data for @func
1341  * @notify: %TRUE if the destroy notify handlers are to be called
1342  *
1343  * Implements the common logic for g_hash_table_foreach_remove()
1344  * and g_hash_table_foreach_steal().
1345  *
1346  * Iterates over every node in the table, calling @func with the key
1347  * and value of the node (and @user_data). If @func returns %TRUE the
1348  * node is removed from the table.
1349  *
1350  * If @notify is true then the destroy notify handlers will be called
1351  * for each removed node.
1352  */
1353 static guint
1354 g_hash_table_foreach_remove_or_steal (GHashTable *hash_table,
1355                                       GHRFunc     func,
1356                                       gpointer    user_data,
1357                                       gboolean    notify)
1358 {
1359   guint deleted = 0;
1360   gint i;
1361 #ifndef G_DISABLE_ASSERT
1362   gint version = hash_table->version;
1363 #endif
1364
1365   for (i = 0; i < hash_table->size; i++)
1366     {
1367       guint node_hash = hash_table->hashes[i];
1368       gpointer node_key = hash_table->keys[i];
1369       gpointer node_value = hash_table->values[i];
1370
1371       if (HASH_IS_REAL (node_hash) &&
1372           (* func) (node_key, node_value, user_data))
1373         {
1374           g_hash_table_remove_node (hash_table, i, notify);
1375           deleted++;
1376         }
1377
1378 #ifndef G_DISABLE_ASSERT
1379       g_return_val_if_fail (version == hash_table->version, 0);
1380 #endif
1381     }
1382
1383   g_hash_table_maybe_resize (hash_table);
1384
1385 #ifndef G_DISABLE_ASSERT
1386   if (deleted > 0)
1387     hash_table->version++;
1388 #endif
1389
1390   return deleted;
1391 }
1392
1393 /**
1394  * g_hash_table_foreach_remove:
1395  * @hash_table: a #GHashTable
1396  * @func: the function to call for each key/value pair
1397  * @user_data: user data to pass to the function
1398  *
1399  * Calls the given function for each key/value pair in the
1400  * #GHashTable. If the function returns %TRUE, then the key/value
1401  * pair is removed from the #GHashTable. If you supplied key or
1402  * value destroy functions when creating the #GHashTable, they are
1403  * used to free the memory allocated for the removed keys and values.
1404  *
1405  * See #GHashTableIter for an alternative way to loop over the
1406  * key/value pairs in the hash table.
1407  *
1408  * Return value: the number of key/value pairs removed
1409  */
1410 guint
1411 g_hash_table_foreach_remove (GHashTable *hash_table,
1412                              GHRFunc     func,
1413                              gpointer    user_data)
1414 {
1415   g_return_val_if_fail (hash_table != NULL, 0);
1416   g_return_val_if_fail (func != NULL, 0);
1417
1418   return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, TRUE);
1419 }
1420
1421 /**
1422  * g_hash_table_foreach_steal:
1423  * @hash_table: a #GHashTable
1424  * @func: the function to call for each key/value pair
1425  * @user_data: user data to pass to the function
1426  *
1427  * Calls the given function for each key/value pair in the
1428  * #GHashTable. If the function returns %TRUE, then the key/value
1429  * pair is removed from the #GHashTable, but no key or value
1430  * destroy functions are called.
1431  *
1432  * See #GHashTableIter for an alternative way to loop over the
1433  * key/value pairs in the hash table.
1434  *
1435  * Return value: the number of key/value pairs removed.
1436  */
1437 guint
1438 g_hash_table_foreach_steal (GHashTable *hash_table,
1439                             GHRFunc     func,
1440                             gpointer    user_data)
1441 {
1442   g_return_val_if_fail (hash_table != NULL, 0);
1443   g_return_val_if_fail (func != NULL, 0);
1444
1445   return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, FALSE);
1446 }
1447
1448 /**
1449  * g_hash_table_foreach:
1450  * @hash_table: a #GHashTable
1451  * @func: the function to call for each key/value pair
1452  * @user_data: user data to pass to the function
1453  *
1454  * Calls the given function for each of the key/value pairs in the
1455  * #GHashTable.  The function is passed the key and value of each
1456  * pair, and the given @user_data parameter.  The hash table may not
1457  * be modified while iterating over it (you can't add/remove
1458  * items). To remove all items matching a predicate, use
1459  * g_hash_table_foreach_remove().
1460  *
1461  * See g_hash_table_find() for performance caveats for linear
1462  * order searches in contrast to g_hash_table_lookup().
1463  */
1464 void
1465 g_hash_table_foreach (GHashTable *hash_table,
1466                       GHFunc      func,
1467                       gpointer    user_data)
1468 {
1469   gint i;
1470 #ifndef G_DISABLE_ASSERT
1471   gint version;
1472 #endif
1473
1474   g_return_if_fail (hash_table != NULL);
1475   g_return_if_fail (func != NULL);
1476
1477 #ifndef G_DISABLE_ASSERT
1478   version = hash_table->version;
1479 #endif
1480
1481   for (i = 0; i < hash_table->size; i++)
1482     {
1483       guint node_hash = hash_table->hashes[i];
1484       gpointer node_key = hash_table->keys[i];
1485       gpointer node_value = hash_table->values[i];
1486
1487       if (HASH_IS_REAL (node_hash))
1488         (* func) (node_key, node_value, user_data);
1489
1490 #ifndef G_DISABLE_ASSERT
1491       g_return_if_fail (version == hash_table->version);
1492 #endif
1493     }
1494 }
1495
1496 /**
1497  * g_hash_table_find:
1498  * @hash_table: a #GHashTable
1499  * @predicate: function to test the key/value pairs for a certain property
1500  * @user_data: user data to pass to the function
1501  *
1502  * Calls the given function for key/value pairs in the #GHashTable
1503  * until @predicate returns %TRUE. The function is passed the key
1504  * and value of each pair, and the given @user_data parameter. The
1505  * hash table may not be modified while iterating over it (you can't
1506  * add/remove items).
1507  *
1508  * Note, that hash tables are really only optimized for forward
1509  * lookups, i.e. g_hash_table_lookup(). So code that frequently issues
1510  * g_hash_table_find() or g_hash_table_foreach() (e.g. in the order of
1511  * once per every entry in a hash table) should probably be reworked
1512  * to use additional or different data structures for reverse lookups
1513  * (keep in mind that an O(n) find/foreach operation issued for all n
1514  * values in a hash table ends up needing O(n*n) operations).
1515  *
1516  * Return value: (allow-none): The value of the first key/value pair is returned,
1517  *     for which @predicate evaluates to %TRUE. If no pair with the
1518  *     requested property is found, %NULL is returned.
1519  *
1520  * Since: 2.4
1521  */
1522 gpointer
1523 g_hash_table_find (GHashTable *hash_table,
1524                    GHRFunc     predicate,
1525                    gpointer    user_data)
1526 {
1527   gint i;
1528 #ifndef G_DISABLE_ASSERT
1529   gint version;
1530 #endif
1531   gboolean match;
1532
1533   g_return_val_if_fail (hash_table != NULL, NULL);
1534   g_return_val_if_fail (predicate != NULL, NULL);
1535
1536 #ifndef G_DISABLE_ASSERT
1537   version = hash_table->version;
1538 #endif
1539
1540   match = FALSE;
1541
1542   for (i = 0; i < hash_table->size; i++)
1543     {
1544       guint node_hash = hash_table->hashes[i];
1545       gpointer node_key = hash_table->keys[i];
1546       gpointer node_value = hash_table->values[i];
1547
1548       if (HASH_IS_REAL (node_hash))
1549         match = predicate (node_key, node_value, user_data);
1550
1551 #ifndef G_DISABLE_ASSERT
1552       g_return_val_if_fail (version == hash_table->version, NULL);
1553 #endif
1554
1555       if (match)
1556         return node_value;
1557     }
1558
1559   return NULL;
1560 }
1561
1562 /**
1563  * g_hash_table_size:
1564  * @hash_table: a #GHashTable
1565  *
1566  * Returns the number of elements contained in the #GHashTable.
1567  *
1568  * Return value: the number of key/value pairs in the #GHashTable.
1569  */
1570 guint
1571 g_hash_table_size (GHashTable *hash_table)
1572 {
1573   g_return_val_if_fail (hash_table != NULL, 0);
1574
1575   return hash_table->nnodes;
1576 }
1577
1578 /**
1579  * g_hash_table_get_keys:
1580  * @hash_table: a #GHashTable
1581  *
1582  * Retrieves every key inside @hash_table. The returned data
1583  * is valid until @hash_table is modified.
1584  *
1585  * Return value: a #GList containing all the keys inside the hash
1586  *     table. The content of the list is owned by the hash table and
1587  *     should not be modified or freed. Use g_list_free() when done
1588  *     using the list.
1589  *
1590  * Since: 2.14
1591  */
1592 GList *
1593 g_hash_table_get_keys (GHashTable *hash_table)
1594 {
1595   gint i;
1596   GList *retval;
1597
1598   g_return_val_if_fail (hash_table != NULL, NULL);
1599
1600   retval = NULL;
1601   for (i = 0; i < hash_table->size; i++)
1602     {
1603       if (HASH_IS_REAL (hash_table->hashes[i]))
1604         retval = g_list_prepend (retval, hash_table->keys[i]);
1605     }
1606
1607   return retval;
1608 }
1609
1610 /**
1611  * g_hash_table_get_values:
1612  * @hash_table: a #GHashTable
1613  *
1614  * Retrieves every value inside @hash_table. The returned data
1615  * is valid until @hash_table is modified.
1616  *
1617  * Return value: a #GList containing all the values inside the hash
1618  *     table. The content of the list is owned by the hash table and
1619  *     should not be modified or freed. Use g_list_free() when done
1620  *     using the list.
1621  *
1622  * Since: 2.14
1623  */
1624 GList *
1625 g_hash_table_get_values (GHashTable *hash_table)
1626 {
1627   gint i;
1628   GList *retval;
1629
1630   g_return_val_if_fail (hash_table != NULL, NULL);
1631
1632   retval = NULL;
1633   for (i = 0; i < hash_table->size; i++)
1634     {
1635       if (HASH_IS_REAL (hash_table->hashes[i]))
1636         retval = g_list_prepend (retval, hash_table->values[i]);
1637     }
1638
1639   return retval;
1640 }
1641
1642 /* Hash functions.
1643  */
1644
1645 /**
1646  * g_str_equal:
1647  * @v1: a key
1648  * @v2: a key to compare with @v1
1649  *
1650  * Compares two strings for byte-by-byte equality and returns %TRUE
1651  * if they are equal. It can be passed to g_hash_table_new() as the
1652  * @key_equal_func parameter, when using non-%NULL strings as keys in a
1653  * #GHashTable.
1654  *
1655  * Note that this function is primarily meant as a hash table comparison
1656  * function. For a general-purpose, %NULL-safe string comparison function,
1657  * see g_strcmp0().
1658  *
1659  * Returns: %TRUE if the two keys match
1660  */
1661 gboolean
1662 g_str_equal (gconstpointer v1,
1663              gconstpointer v2)
1664 {
1665   const gchar *string1 = v1;
1666   const gchar *string2 = v2;
1667
1668   return strcmp (string1, string2) == 0;
1669 }
1670
1671 /**
1672  * g_str_hash:
1673  * @v: a string key
1674  *
1675  * Converts a string to a hash value.
1676  *
1677  * This function implements the widely used "djb" hash apparently posted
1678  * by Daniel Bernstein to comp.lang.c some time ago.  The 32 bit
1679  * unsigned hash value starts at 5381 and for each byte 'c' in the
1680  * string, is updated: <literal>hash = hash * 33 + c</literal>.  This
1681  * function uses the signed value of each byte.
1682  *
1683  * It can be passed to g_hash_table_new() as the @hash_func parameter,
1684  * when using non-%NULL strings as keys in a #GHashTable.
1685  *
1686  * Returns: a hash value corresponding to the key
1687  */
1688 guint
1689 g_str_hash (gconstpointer v)
1690 {
1691   const signed char *p;
1692   guint32 h = 5381;
1693
1694   for (p = v; *p != '\0'; p++)
1695     h = (h << 5) + h + *p;
1696
1697   return h;
1698 }
1699
1700 /**
1701  * g_direct_hash:
1702  * @v: (allow-none): a #gpointer key
1703  *
1704  * Converts a gpointer to a hash value.
1705  * It can be passed to g_hash_table_new() as the @hash_func parameter,
1706  * when using opaque pointers compared by pointer value as keys in a
1707  * #GHashTable.
1708  *
1709  * This hash function is also appropriate for keys that are integers stored
1710  * in pointers, such as <literal>GINT_TO_POINTER (n)</literal>.
1711  *
1712  * Returns: a hash value corresponding to the key.
1713  */
1714 guint
1715 g_direct_hash (gconstpointer v)
1716 {
1717   return GPOINTER_TO_UINT (v);
1718 }
1719
1720 /**
1721  * g_direct_equal:
1722  * @v1: (allow-none): a key
1723  * @v2: (allow-none): a key to compare with @v1
1724  *
1725  * Compares two #gpointer arguments and returns %TRUE if they are equal.
1726  * It can be passed to g_hash_table_new() as the @key_equal_func
1727  * parameter, when using opaque pointers compared by pointer value as keys
1728  * in a #GHashTable.
1729  *
1730  * This equality function is also appropriate for keys that are integers stored
1731  * in pointers, such as <literal>GINT_TO_POINTER (n)</literal>.
1732  *
1733  * Returns: %TRUE if the two keys match.
1734  */
1735 gboolean
1736 g_direct_equal (gconstpointer v1,
1737                 gconstpointer v2)
1738 {
1739   return v1 == v2;
1740 }
1741
1742 /**
1743  * g_int_equal:
1744  * @v1: a pointer to a #gint key
1745  * @v2: a pointer to a #gint key to compare with @v1
1746  *
1747  * Compares the two #gint values being pointed to and returns
1748  * %TRUE if they are equal.
1749  * It can be passed to g_hash_table_new() as the @key_equal_func
1750  * parameter, when using non-%NULL pointers to integers as keys in a
1751  * #GHashTable.
1752  *
1753  * Note that this function acts on pointers to #gint, not on #gint directly:
1754  * if your hash table's keys are of the form
1755  * <literal>GINT_TO_POINTER (n)</literal>, use g_direct_equal() instead.
1756  *
1757  * Returns: %TRUE if the two keys match.
1758  */
1759 gboolean
1760 g_int_equal (gconstpointer v1,
1761              gconstpointer v2)
1762 {
1763   return *((const gint*) v1) == *((const gint*) v2);
1764 }
1765
1766 /**
1767  * g_int_hash:
1768  * @v: a pointer to a #gint key
1769  *
1770  * Converts a pointer to a #gint to a hash value.
1771  * It can be passed to g_hash_table_new() as the @hash_func parameter,
1772  * when using non-%NULL pointers to integer values as keys in a #GHashTable.
1773  *
1774  * Note that this function acts on pointers to #gint, not on #gint directly:
1775  * if your hash table's keys are of the form
1776  * <literal>GINT_TO_POINTER (n)</literal>, use g_direct_hash() instead.
1777  *
1778  * Returns: a hash value corresponding to the key.
1779  */
1780 guint
1781 g_int_hash (gconstpointer v)
1782 {
1783   return *(const gint*) v;
1784 }
1785
1786 /**
1787  * g_int64_equal:
1788  * @v1: a pointer to a #gint64 key
1789  * @v2: a pointer to a #gint64 key to compare with @v1
1790  *
1791  * Compares the two #gint64 values being pointed to and returns
1792  * %TRUE if they are equal.
1793  * It can be passed to g_hash_table_new() as the @key_equal_func
1794  * parameter, when using non-%NULL pointers to 64-bit integers as keys in a
1795  * #GHashTable.
1796  *
1797  * Returns: %TRUE if the two keys match.
1798  *
1799  * Since: 2.22
1800  */
1801 gboolean
1802 g_int64_equal (gconstpointer v1,
1803                gconstpointer v2)
1804 {
1805   return *((const gint64*) v1) == *((const gint64*) v2);
1806 }
1807
1808 /**
1809  * g_int64_hash:
1810  * @v: a pointer to a #gint64 key
1811  *
1812  * Converts a pointer to a #gint64 to a hash value.
1813  *
1814  * It can be passed to g_hash_table_new() as the @hash_func parameter,
1815  * when using non-%NULL pointers to 64-bit integer values as keys in a
1816  * #GHashTable.
1817  *
1818  * Returns: a hash value corresponding to the key.
1819  *
1820  * Since: 2.22
1821  */
1822 guint
1823 g_int64_hash (gconstpointer v)
1824 {
1825   return (guint) *(const gint64*) v;
1826 }
1827
1828 /**
1829  * g_double_equal:
1830  * @v1: a pointer to a #gdouble key
1831  * @v2: a pointer to a #gdouble key to compare with @v1
1832  *
1833  * Compares the two #gdouble values being pointed to and returns
1834  * %TRUE if they are equal.
1835  * It can be passed to g_hash_table_new() as the @key_equal_func
1836  * parameter, when using non-%NULL pointers to doubles as keys in a
1837  * #GHashTable.
1838  *
1839  * Returns: %TRUE if the two keys match.
1840  *
1841  * Since: 2.22
1842  */
1843 gboolean
1844 g_double_equal (gconstpointer v1,
1845                 gconstpointer v2)
1846 {
1847   return *((const gdouble*) v1) == *((const gdouble*) v2);
1848 }
1849
1850 /**
1851  * g_double_hash:
1852  * @v: a pointer to a #gdouble key
1853  *
1854  * Converts a pointer to a #gdouble to a hash value.
1855  * It can be passed to g_hash_table_new() as the @hash_func parameter,
1856  * It can be passed to g_hash_table_new() as the @hash_func parameter,
1857  * when using non-%NULL pointers to doubles as keys in a #GHashTable.
1858  *
1859  * Returns: a hash value corresponding to the key.
1860  *
1861  * Since: 2.22
1862  */
1863 guint
1864 g_double_hash (gconstpointer v)
1865 {
1866   return (guint) *(const gdouble*) v;
1867 }