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