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