Merge remote-tracking branch 'gvdb/master'
[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 "gatomic.h"
38 #include "gtestutils.h"
39
40
41 /**
42  * SECTION:hash_tables
43  * @title: Hash Tables
44  * @short_description: associations between keys and values so that
45  *                     given a key the value can be found quickly
46  *
47  * A #GHashTable provides associations between keys and values which is
48  * optimized so that given a key, the associated value can be found
49  * very quickly.
50  *
51  * Note that neither keys nor values are copied when inserted into the
52  * #GHashTable, so they must exist for the lifetime of the #GHashTable.
53  * This means that the use of static strings is OK, but temporary
54  * strings (i.e. those created in buffers and those returned by GTK+
55  * widgets) should be copied with g_strdup() before being inserted.
56  *
57  * If keys or values are dynamically allocated, you must be careful to
58  * ensure that they are freed when they are removed from the
59  * #GHashTable, and also when they are overwritten by new insertions
60  * into the #GHashTable. It is also not advisable to mix static strings
61  * and dynamically-allocated strings in a #GHashTable, because it then
62  * becomes difficult to determine whether the string should be freed.
63  *
64  * To create a #GHashTable, use g_hash_table_new().
65  *
66  * To insert a key and value into a #GHashTable, use
67  * g_hash_table_insert().
68  *
69  * To lookup a value corresponding to a given key, use
70  * g_hash_table_lookup() and g_hash_table_lookup_extended().
71  *
72  * To remove a key and value, use g_hash_table_remove().
73  *
74  * To call a function for each key and value pair use
75  * g_hash_table_foreach() or use a iterator to iterate over the
76  * key/value pairs in the hash table, see #GHashTableIter.
77  *
78  * To destroy a #GHashTable use g_hash_table_destroy().
79  **/
80
81 /**
82  * GHashTable:
83  *
84  * The #GHashTable struct is an opaque data structure to represent a
85  * <link linkend="glib-Hash-Tables">Hash Table</link>. It should only be
86  * accessed via the following functions.
87  **/
88
89 /**
90  * GHashFunc:
91  * @key: a key.
92  * @Returns: the hash value corresponding to the key.
93  *
94  * Specifies the type of the hash function which is passed to
95  * g_hash_table_new() when a #GHashTable is created.
96  *
97  * The function is passed a key and should return a #guint hash value.
98  * The functions g_direct_hash(), g_int_hash() and g_str_hash() provide
99  * hash functions which can be used when the key is a #gpointer, #gint,
100  * and #gchar* respectively.
101  *
102  * <!-- FIXME: Need more here. --> The hash values should be evenly
103  * distributed over a fairly large range? The modulus is taken with the
104  * hash table size (a prime number) to find the 'bucket' to place each
105  * key into. The function should also be very fast, since it is called
106  * for each key lookup.
107  **/
108
109 /**
110  * GHFunc:
111  * @key: a key.
112  * @value: the value corresponding to the key.
113  * @user_data: user data passed to g_hash_table_foreach().
114  *
115  * Specifies the type of the function passed to g_hash_table_foreach().
116  * It is called with each key/value pair, together with the @user_data
117  * parameter which is passed to g_hash_table_foreach().
118  **/
119
120 /**
121  * GHRFunc:
122  * @key: a key.
123  * @value: the value associated with the key.
124  * @user_data: user data passed to g_hash_table_remove().
125  * @Returns: %TRUE if the key/value pair should be removed from the
126  *           #GHashTable.
127  *
128  * Specifies the type of the function passed to
129  * g_hash_table_foreach_remove(). It is called with each key/value
130  * pair, together with the @user_data parameter passed to
131  * g_hash_table_foreach_remove(). It should return %TRUE if the
132  * key/value pair should be removed from the #GHashTable.
133  **/
134
135 /**
136  * GEqualFunc:
137  * @a: a value.
138  * @b: a value to compare with.
139  * @Returns: %TRUE if @a = @b; %FALSE otherwise.
140  *
141  * Specifies the type of a function used to test two values for
142  * equality. The function should return %TRUE if both values are equal
143  * and %FALSE otherwise.
144  **/
145
146 /**
147  * GHashTableIter:
148  *
149  * A GHashTableIter structure represents an iterator that can be used
150  * to iterate over the elements of a #GHashTable. GHashTableIter
151  * structures are typically allocated on the stack and then initialized
152  * with g_hash_table_iter_init().
153  **/
154
155 #define HASH_TABLE_MIN_SHIFT 3  /* 1 << 3 == 8 buckets */
156
157 typedef struct _GHashNode      GHashNode;
158
159 struct _GHashNode
160 {
161   gpointer   key;
162   gpointer   value;
163
164   /* If key_hash == 0, node is not in use
165    * If key_hash == 1, node is a tombstone
166    * If key_hash >= 2, node contains data */
167   guint      key_hash;
168 };
169
170 struct _GHashTable
171 {
172   gint             size;
173   gint             mod;
174   guint            mask;
175   gint             nnodes;
176   gint             noccupied;  /* nnodes + tombstones */
177   GHashNode       *nodes;
178   GHashFunc        hash_func;
179   GEqualFunc       key_equal_func;
180   volatile gint    ref_count;
181 #ifndef G_DISABLE_ASSERT
182   /*
183    * Tracks the structure of the hash table, not its contents: is only
184    * incremented when a node is added or removed (is not incremented
185    * when the key or data of a node is modified).
186    */
187   int              version;
188 #endif
189   GDestroyNotify   key_destroy_func;
190   GDestroyNotify   value_destroy_func;
191 };
192
193 typedef struct
194 {
195   GHashTable  *hash_table;
196   gpointer     dummy1;
197   gpointer     dummy2;
198   int          position;
199   gboolean     dummy3;
200   int          version;
201 } RealIter;
202
203 /* Each table size has an associated prime modulo (the first prime
204  * lower than the table size) used to find the initial bucket. Probing
205  * then works modulo 2^n. The prime modulo is necessary to get a
206  * good distribution with poor hash functions. */
207 static const gint prime_mod [] =
208 {
209   1,          /* For 1 << 0 */
210   2,
211   3,
212   7,
213   13,
214   31,
215   61,
216   127,
217   251,
218   509,
219   1021,
220   2039,
221   4093,
222   8191,
223   16381,
224   32749,
225   65521,      /* For 1 << 16 */
226   131071,
227   262139,
228   524287,
229   1048573,
230   2097143,
231   4194301,
232   8388593,
233   16777213,
234   33554393,
235   67108859,
236   134217689,
237   268435399,
238   536870909,
239   1073741789,
240   2147483647  /* For 1 << 31 */
241 };
242
243 static void
244 g_hash_table_set_shift (GHashTable *hash_table, gint shift)
245 {
246   gint i;
247   guint mask = 0;
248
249   hash_table->size = 1 << shift;
250   hash_table->mod  = prime_mod [shift];
251
252   for (i = 0; i < shift; i++)
253     {
254       mask <<= 1;
255       mask |= 1;
256     }
257
258   hash_table->mask = mask;
259 }
260
261 static gint
262 g_hash_table_find_closest_shift (gint n)
263 {
264   gint i;
265
266   for (i = 0; n; i++)
267     n >>= 1;
268
269   return i;
270 }
271
272 static void
273 g_hash_table_set_shift_from_size (GHashTable *hash_table, gint size)
274 {
275   gint shift;
276
277   shift = g_hash_table_find_closest_shift (size);
278   shift = MAX (shift, HASH_TABLE_MIN_SHIFT);
279
280   g_hash_table_set_shift (hash_table, shift);
281 }
282
283 /*
284  * g_hash_table_lookup_node:
285  * @hash_table: our #GHashTable
286  * @key: the key to lookup against (may be %NULL)
287  * @hash_return: optional key hash return location
288  * Return value: index of the described #GHashNode
289  *
290  * Performs a lookup in the hash table.
291  *
292  * Virtually all hash operations will use this function internally.
293  *
294  * This function first computes the hash value of the key using the
295  * user's hash function.
296  *
297  * If an entry in the table matching @key is found then this function
298  * returns the index of that entry in the table, and if not, the
299  * index of an empty node (never a tombstone).
300  */
301 static inline guint
302 g_hash_table_lookup_node (GHashTable    *hash_table,
303                           gconstpointer  key)
304 {
305   GHashNode *node;
306   guint node_index;
307   guint hash_value;
308   guint step = 0;
309
310   /* Empty buckets have hash_value set to 0, and for tombstones, it's 1.
311    * We need to make sure our hash value is not one of these. */
312
313   hash_value = (* hash_table->hash_func) (key);
314   if (G_UNLIKELY (hash_value <= 1))
315     hash_value = 2;
316
317   node_index = hash_value % hash_table->mod;
318   node = &hash_table->nodes [node_index];
319
320   while (node->key_hash)
321     {
322       /*  We first check if our full hash values
323        *  are equal so we can avoid calling the full-blown
324        *  key equality function in most cases.
325        */
326
327       if (node->key_hash == hash_value)
328         {
329           if (hash_table->key_equal_func)
330             {
331               if (hash_table->key_equal_func (node->key, key))
332                 break;
333             }
334           else if (node->key == key)
335             {
336               break;
337             }
338         }
339
340       step++;
341       node_index += step;
342       node_index &= hash_table->mask;
343       node = &hash_table->nodes [node_index];
344     }
345
346   return node_index;
347 }
348
349 /*
350  * g_hash_table_lookup_node_for_insertion:
351  * @hash_table: our #GHashTable
352  * @key: the key to lookup against
353  * @hash_return: key hash return location
354  * Return value: index of the described #GHashNode
355  *
356  * Performs a lookup in the hash table, preserving extra information
357  * usually needed for insertion.
358  *
359  * This function first computes the hash value of the key using the
360  * user's hash function.
361  *
362  * If an entry in the table matching @key is found then this function
363  * returns the index of that entry in the table, and if not, the
364  * index of an unused node (empty or tombstone) where the key can be
365  * inserted.
366  *
367  * The computed hash value is returned in the variable pointed to
368  * by @hash_return. This is to save insertions from having to compute
369  * the hash record again for the new record.
370  */
371 static inline guint
372 g_hash_table_lookup_node_for_insertion (GHashTable    *hash_table,
373                                         gconstpointer  key,
374                                         guint         *hash_return)
375 {
376   GHashNode *node;
377   guint node_index;
378   guint hash_value;
379   guint first_tombstone;
380   gboolean have_tombstone = FALSE;
381   guint step = 0;
382
383   /* Empty buckets have hash_value set to 0, and for tombstones, it's 1.
384    * We need to make sure our hash value is not one of these. */
385
386   hash_value = (* hash_table->hash_func) (key);
387   if (G_UNLIKELY (hash_value <= 1))
388     hash_value = 2;
389
390   *hash_return = hash_value;
391
392   node_index = hash_value % hash_table->mod;
393   node = &hash_table->nodes [node_index];
394
395   while (node->key_hash)
396     {
397       /*  We first check if our full hash values
398        *  are equal so we can avoid calling the full-blown
399        *  key equality function in most cases.
400        */
401
402       if (node->key_hash == hash_value)
403         {
404           if (hash_table->key_equal_func)
405             {
406               if (hash_table->key_equal_func (node->key, key))
407                 return node_index;
408             }
409           else if (node->key == key)
410             {
411               return node_index;
412             }
413         }
414       else if (node->key_hash == 1 && !have_tombstone)
415         {
416           first_tombstone = node_index;
417           have_tombstone = TRUE;
418         }
419
420       step++;
421       node_index += step;
422       node_index &= hash_table->mask;
423       node = &hash_table->nodes [node_index];
424     }
425
426   if (have_tombstone)
427     return first_tombstone;
428
429   return node_index;
430 }
431
432 /*
433  * g_hash_table_remove_node:
434  * @hash_table: our #GHashTable
435  * @node: pointer to node to remove
436  * @notify: %TRUE if the destroy notify handlers are to be called
437  *
438  * Removes a node from the hash table and updates the node count.
439  * The node is replaced by a tombstone. No table resize is performed.
440  *
441  * If @notify is %TRUE then the destroy notify functions are called
442  * for the key and value of the hash node.
443  */
444 static void
445 g_hash_table_remove_node (GHashTable   *hash_table,
446                           GHashNode    *node,
447                           gboolean      notify)
448 {
449   if (notify && hash_table->key_destroy_func)
450     hash_table->key_destroy_func (node->key);
451
452   if (notify && hash_table->value_destroy_func)
453     hash_table->value_destroy_func (node->value);
454
455   /* Erect tombstone */
456   node->key_hash = 1;
457
458   /* Be GC friendly */
459   node->key = NULL;
460   node->value = NULL;
461
462   hash_table->nnodes--;
463 }
464
465 /*
466  * g_hash_table_remove_all_nodes:
467  * @hash_table: our #GHashTable
468  * @notify: %TRUE if the destroy notify handlers are to be called
469  *
470  * Removes all nodes from the table.  Since this may be a precursor to
471  * freeing the table entirely, no resize is performed.
472  *
473  * If @notify is %TRUE then the destroy notify functions are called
474  * for the key and value of the hash node.
475  */
476 static void
477 g_hash_table_remove_all_nodes (GHashTable *hash_table,
478                                gboolean    notify)
479 {
480   int i;
481
482   for (i = 0; i < hash_table->size; i++)
483     {
484       GHashNode *node = &hash_table->nodes [i];
485
486       if (node->key_hash > 1)
487         {
488           if (notify && hash_table->key_destroy_func)
489             hash_table->key_destroy_func (node->key);
490
491           if (notify && hash_table->value_destroy_func)
492             hash_table->value_destroy_func (node->value);
493         }
494     }
495
496   /* We need to set node->key_hash = 0 for all nodes - might as well be GC
497    * friendly and clear everything */
498   memset (hash_table->nodes, 0, hash_table->size * sizeof (GHashNode));
499
500   hash_table->nnodes = 0;
501   hash_table->noccupied = 0;
502 }
503
504 /*
505  * g_hash_table_resize:
506  * @hash_table: our #GHashTable
507  *
508  * Resizes the hash table to the optimal size based on the number of
509  * nodes currently held.  If you call this function then a resize will
510  * occur, even if one does not need to occur.  Use
511  * g_hash_table_maybe_resize() instead.
512  *
513  * This function may "resize" the hash table to its current size, with
514  * the side effect of cleaning up tombstones and otherwise optimizing
515  * the probe sequences.
516  */
517 static void
518 g_hash_table_resize (GHashTable *hash_table)
519 {
520   GHashNode *new_nodes;
521   gint old_size;
522   gint i;
523
524   old_size = hash_table->size;
525   g_hash_table_set_shift_from_size (hash_table, hash_table->nnodes * 2);
526
527   new_nodes = g_new0 (GHashNode, hash_table->size);
528
529   for (i = 0; i < old_size; i++)
530     {
531       GHashNode *node = &hash_table->nodes [i];
532       GHashNode *new_node;
533       guint hash_val;
534       guint step = 0;
535
536       if (node->key_hash <= 1)
537         continue;
538
539       hash_val = node->key_hash % hash_table->mod;
540       new_node = &new_nodes [hash_val];
541
542       while (new_node->key_hash)
543         {
544           step++;
545           hash_val += step;
546           hash_val &= hash_table->mask;
547           new_node = &new_nodes [hash_val];
548         }
549
550       *new_node = *node;
551     }
552
553   g_free (hash_table->nodes);
554   hash_table->nodes = new_nodes;
555   hash_table->noccupied = hash_table->nnodes;
556 }
557
558 /*
559  * g_hash_table_maybe_resize:
560  * @hash_table: our #GHashTable
561  *
562  * Resizes the hash table, if needed.
563  *
564  * Essentially, calls g_hash_table_resize() if the table has strayed
565  * too far from its ideal size for its number of nodes.
566  */
567 static inline void
568 g_hash_table_maybe_resize (GHashTable *hash_table)
569 {
570   gint noccupied = hash_table->noccupied;
571   gint size = hash_table->size;
572
573   if ((size > hash_table->nnodes * 4 && size > 1 << HASH_TABLE_MIN_SHIFT) ||
574       (size <= noccupied + (noccupied / 16)))
575     g_hash_table_resize (hash_table);
576 }
577
578 /**
579  * g_hash_table_new:
580  * @hash_func: a function to create a hash value from a key.
581  *   Hash values are used to determine where keys are stored within the
582  *   #GHashTable data structure. The g_direct_hash(), g_int_hash(),
583  *   g_int64_hash(), g_double_hash() and g_str_hash() functions are provided
584  *   for some common types of keys.
585  *   If hash_func is %NULL, g_direct_hash() is used.
586  * @key_equal_func: a function to check two keys for equality.  This is
587  *   used when looking up keys in the #GHashTable.  The g_direct_equal(),
588  *   g_int_equal(), g_int64_equal(), g_double_equal() and g_str_equal()
589  *   functions are provided for the most common types of keys.
590  *   If @key_equal_func is %NULL, keys are compared directly in a similar
591  *   fashion to g_direct_equal(), but without the overhead of a function call.
592  *
593  * Creates a new #GHashTable with a reference count of 1.
594  *
595  * Return value: a new #GHashTable.
596  **/
597 GHashTable*
598 g_hash_table_new (GHashFunc    hash_func,
599                   GEqualFunc   key_equal_func)
600 {
601   return g_hash_table_new_full (hash_func, key_equal_func, NULL, NULL);
602 }
603
604
605 /**
606  * g_hash_table_new_full:
607  * @hash_func: a function to create a hash value from a key.
608  * @key_equal_func: a function to check two keys for equality.
609  * @key_destroy_func: a function to free the memory allocated for the key
610  *   used when removing the entry from the #GHashTable or %NULL if you
611  *   don't want to supply such a function.
612  * @value_destroy_func: a function to free the memory allocated for the
613  *   value used when removing the entry from the #GHashTable or %NULL if
614  *   you don't want to supply such a function.
615  *
616  * Creates a new #GHashTable like g_hash_table_new() with a reference count
617  * of 1 and allows to specify functions to free the memory allocated for the
618  * key and value that get called when removing the entry from the #GHashTable.
619  *
620  * Return value: a new #GHashTable.
621  **/
622 GHashTable*
623 g_hash_table_new_full (GHashFunc       hash_func,
624                        GEqualFunc      key_equal_func,
625                        GDestroyNotify  key_destroy_func,
626                        GDestroyNotify  value_destroy_func)
627 {
628   GHashTable *hash_table;
629
630   hash_table = g_slice_new (GHashTable);
631   g_hash_table_set_shift (hash_table, HASH_TABLE_MIN_SHIFT);
632   hash_table->nnodes             = 0;
633   hash_table->noccupied          = 0;
634   hash_table->hash_func          = hash_func ? hash_func : g_direct_hash;
635   hash_table->key_equal_func     = key_equal_func;
636   hash_table->ref_count          = 1;
637 #ifndef G_DISABLE_ASSERT
638   hash_table->version            = 0;
639 #endif
640   hash_table->key_destroy_func   = key_destroy_func;
641   hash_table->value_destroy_func = value_destroy_func;
642   hash_table->nodes              = g_new0 (GHashNode, hash_table->size);
643
644   return hash_table;
645 }
646
647 /**
648  * g_hash_table_iter_init:
649  * @iter: an uninitialized #GHashTableIter.
650  * @hash_table: a #GHashTable.
651  *
652  * Initializes a key/value pair iterator and associates it with
653  * @hash_table. Modifying the hash table after calling this function
654  * invalidates the returned iterator.
655  * |[
656  * GHashTableIter iter;
657  * gpointer key, value;
658  *
659  * g_hash_table_iter_init (&iter, hash_table);
660  * while (g_hash_table_iter_next (&iter, &key, &value)) 
661  *   {
662  *     /&ast; do something with key and value &ast;/
663  *   }
664  * ]|
665  *
666  * Since: 2.16
667  **/
668 void
669 g_hash_table_iter_init (GHashTableIter *iter,
670                         GHashTable     *hash_table)
671 {
672   RealIter *ri = (RealIter *) iter;
673
674   g_return_if_fail (iter != NULL);
675   g_return_if_fail (hash_table != NULL);
676
677   ri->hash_table = hash_table;
678   ri->position = -1;
679 #ifndef G_DISABLE_ASSERT
680   ri->version = hash_table->version;
681 #endif
682 }
683
684 /**
685  * g_hash_table_iter_next:
686  * @iter: an initialized #GHashTableIter.
687  * @key: a location to store the key, or %NULL.
688  * @value: a location to store the value, or %NULL.
689  *
690  * Advances @iter and retrieves the key and/or value that are now
691  * pointed to as a result of this advancement. If %FALSE is returned,
692  * @key and @value are not set, and the iterator becomes invalid.
693  *
694  * Return value: %FALSE if the end of the #GHashTable has been reached.
695  *
696  * Since: 2.16
697  **/
698 gboolean
699 g_hash_table_iter_next (GHashTableIter *iter,
700                         gpointer       *key,
701                         gpointer       *value)
702 {
703   RealIter *ri = (RealIter *) iter;
704   GHashNode *node;
705   gint position;
706
707   g_return_val_if_fail (iter != NULL, FALSE);
708 #ifndef G_DISABLE_ASSERT
709   g_return_val_if_fail (ri->version == ri->hash_table->version, FALSE);
710 #endif
711   g_return_val_if_fail (ri->position < ri->hash_table->size, FALSE);
712
713   position = ri->position;
714
715   do
716     {
717       position++;
718       if (position >= ri->hash_table->size)
719         {
720           ri->position = position;
721           return FALSE;
722         }
723
724       node = &ri->hash_table->nodes [position];
725     }
726   while (node->key_hash <= 1);
727
728   if (key != NULL)
729     *key = node->key;
730   if (value != NULL)
731     *value = node->value;
732
733   ri->position = position;
734   return TRUE;
735 }
736
737 /**
738  * g_hash_table_iter_get_hash_table:
739  * @iter: an initialized #GHashTableIter.
740  *
741  * Returns the #GHashTable associated with @iter.
742  *
743  * Return value: the #GHashTable associated with @iter.
744  *
745  * Since: 2.16
746  **/
747 GHashTable *
748 g_hash_table_iter_get_hash_table (GHashTableIter *iter)
749 {
750   g_return_val_if_fail (iter != NULL, NULL);
751
752   return ((RealIter *) iter)->hash_table;
753 }
754
755 static void
756 iter_remove_or_steal (RealIter *ri, gboolean notify)
757 {
758   g_return_if_fail (ri != NULL);
759 #ifndef G_DISABLE_ASSERT
760   g_return_if_fail (ri->version == ri->hash_table->version);
761 #endif
762   g_return_if_fail (ri->position >= 0);
763   g_return_if_fail (ri->position < ri->hash_table->size);
764
765   g_hash_table_remove_node (ri->hash_table, &ri->hash_table->nodes [ri->position], notify);
766
767 #ifndef G_DISABLE_ASSERT
768   ri->version++;
769   ri->hash_table->version++;
770 #endif
771 }
772
773 /**
774  * g_hash_table_iter_remove:
775  * @iter: an initialized #GHashTableIter.
776  *
777  * Removes the key/value pair currently pointed to by the iterator
778  * from its associated #GHashTable. Can only be called after
779  * g_hash_table_iter_next() returned %TRUE, and cannot be called more
780  * than once for the same key/value pair.
781  *
782  * If the #GHashTable was created using g_hash_table_new_full(), the
783  * key and value are freed using the supplied destroy functions, otherwise
784  * you have to make sure that any dynamically allocated values are freed 
785  * yourself.
786  *
787  * Since: 2.16
788  **/
789 void
790 g_hash_table_iter_remove (GHashTableIter *iter)
791 {
792   iter_remove_or_steal ((RealIter *) iter, TRUE);
793 }
794
795 /**
796  * g_hash_table_iter_steal:
797  * @iter: an initialized #GHashTableIter.
798  *
799  * Removes the key/value pair currently pointed to by the iterator
800  * from its associated #GHashTable, without calling the key and value
801  * destroy functions. Can only be called after
802  * g_hash_table_iter_next() returned %TRUE, and cannot be called more
803  * than once for the same key/value pair.
804  *
805  * Since: 2.16
806  **/
807 void
808 g_hash_table_iter_steal (GHashTableIter *iter)
809 {
810   iter_remove_or_steal ((RealIter *) iter, FALSE);
811 }
812
813
814 /**
815  * g_hash_table_ref:
816  * @hash_table: a valid #GHashTable.
817  *
818  * Atomically increments the reference count of @hash_table by one.
819  * This function is MT-safe and may be called from any thread.
820  *
821  * Return value: the passed in #GHashTable.
822  *
823  * Since: 2.10
824  **/
825 GHashTable*
826 g_hash_table_ref (GHashTable *hash_table)
827 {
828   g_return_val_if_fail (hash_table != NULL, NULL);
829   g_return_val_if_fail (hash_table->ref_count > 0, hash_table);
830
831   g_atomic_int_add (&hash_table->ref_count, 1);
832   return hash_table;
833 }
834
835 /**
836  * g_hash_table_unref:
837  * @hash_table: a valid #GHashTable.
838  *
839  * Atomically decrements the reference count of @hash_table by one.
840  * If the reference count drops to 0, all keys and values will be
841  * destroyed, and all memory allocated by the hash table is released.
842  * This function is MT-safe and may be called from any thread.
843  *
844  * Since: 2.10
845  **/
846 void
847 g_hash_table_unref (GHashTable *hash_table)
848 {
849   g_return_if_fail (hash_table != NULL);
850   g_return_if_fail (hash_table->ref_count > 0);
851
852   if (g_atomic_int_exchange_and_add (&hash_table->ref_count, -1) - 1 == 0)
853     {
854       g_hash_table_remove_all_nodes (hash_table, TRUE);
855       g_free (hash_table->nodes);
856       g_slice_free (GHashTable, hash_table);
857     }
858 }
859
860 /**
861  * g_hash_table_destroy:
862  * @hash_table: a #GHashTable.
863  *
864  * Destroys all keys and values in the #GHashTable and decrements its
865  * reference count by 1. If keys and/or values are dynamically allocated,
866  * you should either free them first or create the #GHashTable with destroy
867  * notifiers using g_hash_table_new_full(). In the latter case the destroy
868  * functions you supplied will be called on all keys and values during the
869  * destruction phase.
870  **/
871 void
872 g_hash_table_destroy (GHashTable *hash_table)
873 {
874   g_return_if_fail (hash_table != NULL);
875   g_return_if_fail (hash_table->ref_count > 0);
876
877   g_hash_table_remove_all (hash_table);
878   g_hash_table_unref (hash_table);
879 }
880
881 /**
882  * g_hash_table_lookup:
883  * @hash_table: a #GHashTable.
884  * @key: the key to look up.
885  *
886  * Looks up a key in a #GHashTable. Note that this function cannot
887  * distinguish between a key that is not present and one which is present
888  * and has the value %NULL. If you need this distinction, use
889  * g_hash_table_lookup_extended().
890  *
891  * Return value: the associated value, or %NULL if the key is not found.
892  **/
893 gpointer
894 g_hash_table_lookup (GHashTable   *hash_table,
895                      gconstpointer key)
896 {
897   GHashNode *node;
898   guint      node_index;
899
900   g_return_val_if_fail (hash_table != NULL, NULL);
901
902   node_index = g_hash_table_lookup_node (hash_table, key);
903   node = &hash_table->nodes [node_index];
904
905   return node->key_hash ? node->value : NULL;
906 }
907
908 /**
909  * g_hash_table_lookup_extended:
910  * @hash_table: a #GHashTable
911  * @lookup_key: the key to look up
912  * @orig_key: return location for the original key, or %NULL
913  * @value: return location for the value associated with the key, or %NULL
914  *
915  * Looks up a key in the #GHashTable, returning the original key and the
916  * associated value and a #gboolean which is %TRUE if the key was found. This
917  * is useful if you need to free the memory allocated for the original key,
918  * for example before calling g_hash_table_remove().
919  *
920  * You can actually pass %NULL for @lookup_key to test
921  * whether the %NULL key exists, provided the hash and equal functions
922  * of @hash_table are %NULL-safe.
923  *
924  * Return value: %TRUE if the key was found in the #GHashTable.
925  **/
926 gboolean
927 g_hash_table_lookup_extended (GHashTable    *hash_table,
928                               gconstpointer  lookup_key,
929                               gpointer      *orig_key,
930                               gpointer      *value)
931 {
932   GHashNode *node;
933   guint      node_index;
934
935   g_return_val_if_fail (hash_table != NULL, FALSE);
936
937   node_index = g_hash_table_lookup_node (hash_table, lookup_key);
938   node = &hash_table->nodes [node_index];
939
940   if (!node->key_hash)
941     return FALSE;
942
943   if (orig_key)
944     *orig_key = node->key;
945
946   if (value)
947     *value = node->value;
948
949   return TRUE;
950 }
951
952 /*
953  * g_hash_table_insert_internal:
954  * @hash_table: our #GHashTable
955  * @key: the key to insert
956  * @value: the value to insert
957  * @keep_new_key: if %TRUE and this key already exists in the table
958  *   then call the destroy notify function on the old key.  If %FALSE
959  *   then call the destroy notify function on the new key.
960  *
961  * Implements the common logic for the g_hash_table_insert() and
962  * g_hash_table_replace() functions.
963  *
964  * Do a lookup of @key.  If it is found, replace it with the new
965  * @value (and perhaps the new @key).  If it is not found, create a
966  * new node.
967  */
968 static void
969 g_hash_table_insert_internal (GHashTable *hash_table,
970                               gpointer    key,
971                               gpointer    value,
972                               gboolean    keep_new_key)
973 {
974   GHashNode *node;
975   guint node_index;
976   guint key_hash;
977   guint old_hash;
978
979   g_return_if_fail (hash_table != NULL);
980   g_return_if_fail (hash_table->ref_count > 0);
981
982   node_index = g_hash_table_lookup_node_for_insertion (hash_table, key, &key_hash);
983   node = &hash_table->nodes [node_index];
984
985   old_hash = node->key_hash;
986
987   if (old_hash > 1)
988     {
989       if (keep_new_key)
990         {
991           if (hash_table->key_destroy_func)
992             hash_table->key_destroy_func (node->key);
993           node->key = key;
994         }
995       else
996         {
997           if (hash_table->key_destroy_func)
998             hash_table->key_destroy_func (key);
999         }
1000
1001       if (hash_table->value_destroy_func)
1002         hash_table->value_destroy_func (node->value);
1003
1004       node->value = value;
1005     }
1006   else
1007     {
1008       node->key = key;
1009       node->value = value;
1010       node->key_hash = key_hash;
1011
1012       hash_table->nnodes++;
1013
1014       if (old_hash == 0)
1015         {
1016           /* We replaced an empty node, and not a tombstone */
1017           hash_table->noccupied++;
1018           g_hash_table_maybe_resize (hash_table);
1019         }
1020
1021 #ifndef G_DISABLE_ASSERT
1022       hash_table->version++;
1023 #endif
1024     }
1025 }
1026
1027 /**
1028  * g_hash_table_insert:
1029  * @hash_table: a #GHashTable.
1030  * @key: a key to insert.
1031  * @value: the value to associate with the key.
1032  *
1033  * Inserts a new key and value into a #GHashTable.
1034  *
1035  * If the key already exists in the #GHashTable its current value is replaced
1036  * with the new value. If you supplied a @value_destroy_func when creating the
1037  * #GHashTable, the old value is freed using that function. If you supplied
1038  * a @key_destroy_func when creating the #GHashTable, the passed key is freed
1039  * using that function.
1040  **/
1041 void
1042 g_hash_table_insert (GHashTable *hash_table,
1043                      gpointer    key,
1044                      gpointer    value)
1045 {
1046   g_hash_table_insert_internal (hash_table, key, value, FALSE);
1047 }
1048
1049 /**
1050  * g_hash_table_replace:
1051  * @hash_table: a #GHashTable.
1052  * @key: a key to insert.
1053  * @value: the value to associate with the key.
1054  *
1055  * Inserts a new key and value into a #GHashTable similar to
1056  * g_hash_table_insert(). The difference is that if the key already exists
1057  * in the #GHashTable, it gets replaced by the new key. If you supplied a
1058  * @value_destroy_func when creating the #GHashTable, the old value is freed
1059  * using that function. If you supplied a @key_destroy_func when creating the
1060  * #GHashTable, the old key is freed using that function.
1061  **/
1062 void
1063 g_hash_table_replace (GHashTable *hash_table,
1064                       gpointer    key,
1065                       gpointer    value)
1066 {
1067   g_hash_table_insert_internal (hash_table, key, value, TRUE);
1068 }
1069
1070 /*
1071  * g_hash_table_remove_internal:
1072  * @hash_table: our #GHashTable
1073  * @key: the key to remove
1074  * @notify: %TRUE if the destroy notify handlers are to be called
1075  * Return value: %TRUE if a node was found and removed, else %FALSE
1076  *
1077  * Implements the common logic for the g_hash_table_remove() and
1078  * g_hash_table_steal() functions.
1079  *
1080  * Do a lookup of @key and remove it if it is found, calling the
1081  * destroy notify handlers only if @notify is %TRUE.
1082  */
1083 static gboolean
1084 g_hash_table_remove_internal (GHashTable    *hash_table,
1085                               gconstpointer  key,
1086                               gboolean       notify)
1087 {
1088   GHashNode *node;
1089   guint node_index;
1090
1091   g_return_val_if_fail (hash_table != NULL, FALSE);
1092
1093   node_index = g_hash_table_lookup_node (hash_table, key);
1094   node = &hash_table->nodes [node_index];
1095
1096   /* g_hash_table_lookup_node() never returns a tombstone, so this is safe */
1097   if (!node->key_hash)
1098     return FALSE;
1099
1100   g_hash_table_remove_node (hash_table, node, notify);
1101   g_hash_table_maybe_resize (hash_table);
1102
1103 #ifndef G_DISABLE_ASSERT
1104   hash_table->version++;
1105 #endif
1106
1107   return TRUE;
1108 }
1109
1110 /**
1111  * g_hash_table_remove:
1112  * @hash_table: a #GHashTable.
1113  * @key: the key to remove.
1114  *
1115  * Removes a key and its associated value from a #GHashTable.
1116  *
1117  * If the #GHashTable was created using g_hash_table_new_full(), the
1118  * key and value are freed using the supplied destroy functions, otherwise
1119  * you have to make sure that any dynamically allocated values are freed
1120  * yourself.
1121  *
1122  * Return value: %TRUE if the key was found and removed from the #GHashTable.
1123  **/
1124 gboolean
1125 g_hash_table_remove (GHashTable    *hash_table,
1126                      gconstpointer  key)
1127 {
1128   return g_hash_table_remove_internal (hash_table, key, TRUE);
1129 }
1130
1131 /**
1132  * g_hash_table_steal:
1133  * @hash_table: a #GHashTable.
1134  * @key: the key to remove.
1135  *
1136  * Removes a key and its associated value from a #GHashTable without
1137  * calling the key and value destroy functions.
1138  *
1139  * Return value: %TRUE if the key was found and removed from the #GHashTable.
1140  **/
1141 gboolean
1142 g_hash_table_steal (GHashTable    *hash_table,
1143                     gconstpointer  key)
1144 {
1145   return g_hash_table_remove_internal (hash_table, key, FALSE);
1146 }
1147
1148 /**
1149  * g_hash_table_remove_all:
1150  * @hash_table: a #GHashTable
1151  *
1152  * Removes all keys and their associated values from a #GHashTable.
1153  *
1154  * If the #GHashTable was created using g_hash_table_new_full(), the keys
1155  * and values are freed using the supplied destroy functions, otherwise you
1156  * have to make sure that any dynamically allocated values are freed
1157  * yourself.
1158  *
1159  * Since: 2.12
1160  **/
1161 void
1162 g_hash_table_remove_all (GHashTable *hash_table)
1163 {
1164   g_return_if_fail (hash_table != NULL);
1165
1166 #ifndef G_DISABLE_ASSERT
1167   if (hash_table->nnodes != 0)
1168     hash_table->version++;
1169 #endif
1170
1171   g_hash_table_remove_all_nodes (hash_table, TRUE);
1172   g_hash_table_maybe_resize (hash_table);
1173 }
1174
1175 /**
1176  * g_hash_table_steal_all:
1177  * @hash_table: a #GHashTable.
1178  *
1179  * Removes all keys and their associated values from a #GHashTable
1180  * without calling the key and value destroy functions.
1181  *
1182  * Since: 2.12
1183  **/
1184 void
1185 g_hash_table_steal_all (GHashTable *hash_table)
1186 {
1187   g_return_if_fail (hash_table != NULL);
1188
1189 #ifndef G_DISABLE_ASSERT
1190   if (hash_table->nnodes != 0)
1191     hash_table->version++;
1192 #endif
1193
1194   g_hash_table_remove_all_nodes (hash_table, FALSE);
1195   g_hash_table_maybe_resize (hash_table);
1196 }
1197
1198 /*
1199  * g_hash_table_foreach_remove_or_steal:
1200  * @hash_table: our #GHashTable
1201  * @func: the user's callback function
1202  * @user_data: data for @func
1203  * @notify: %TRUE if the destroy notify handlers are to be called
1204  *
1205  * Implements the common logic for g_hash_table_foreach_remove() and
1206  * g_hash_table_foreach_steal().
1207  *
1208  * Iterates over every node in the table, calling @func with the key
1209  * and value of the node (and @user_data).  If @func returns %TRUE the
1210  * node is removed from the table.
1211  *
1212  * If @notify is true then the destroy notify handlers will be called
1213  * for each removed node.
1214  */
1215 static guint
1216 g_hash_table_foreach_remove_or_steal (GHashTable *hash_table,
1217                                       GHRFunc     func,
1218                                       gpointer    user_data,
1219                                       gboolean    notify)
1220 {
1221   guint deleted = 0;
1222   gint i;
1223
1224   for (i = 0; i < hash_table->size; i++)
1225     {
1226       GHashNode *node = &hash_table->nodes [i];
1227
1228       if (node->key_hash > 1 && (* func) (node->key, node->value, user_data))
1229         {
1230           g_hash_table_remove_node (hash_table, node, notify);
1231           deleted++;
1232         }
1233     }
1234
1235   g_hash_table_maybe_resize (hash_table);
1236
1237 #ifndef G_DISABLE_ASSERT
1238   if (deleted > 0)
1239     hash_table->version++;
1240 #endif
1241
1242   return deleted;
1243 }
1244
1245 /**
1246  * g_hash_table_foreach_remove:
1247  * @hash_table: a #GHashTable.
1248  * @func: the function to call for each key/value pair.
1249  * @user_data: user data to pass to the function.
1250  *
1251  * Calls the given function for each key/value pair in the #GHashTable.
1252  * If the function returns %TRUE, then the key/value pair is removed from the
1253  * #GHashTable. If you supplied key or value destroy functions when creating
1254  * the #GHashTable, they are used to free the memory allocated for the removed
1255  * keys and values.
1256  *
1257  * See #GHashTableIter for an alternative way to loop over the 
1258  * key/value pairs in the hash table.
1259  *
1260  * Return value: the number of key/value pairs removed.
1261  **/
1262 guint
1263 g_hash_table_foreach_remove (GHashTable *hash_table,
1264                              GHRFunc     func,
1265                              gpointer    user_data)
1266 {
1267   g_return_val_if_fail (hash_table != NULL, 0);
1268   g_return_val_if_fail (func != NULL, 0);
1269
1270   return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, TRUE);
1271 }
1272
1273 /**
1274  * g_hash_table_foreach_steal:
1275  * @hash_table: a #GHashTable.
1276  * @func: the function to call for each key/value pair.
1277  * @user_data: user data to pass to the function.
1278  *
1279  * Calls the given function for each key/value pair in the #GHashTable.
1280  * If the function returns %TRUE, then the key/value pair is removed from the
1281  * #GHashTable, but no key or value destroy functions are called.
1282  *
1283  * See #GHashTableIter for an alternative way to loop over the 
1284  * key/value pairs in the hash table.
1285  *
1286  * Return value: the number of key/value pairs removed.
1287  **/
1288 guint
1289 g_hash_table_foreach_steal (GHashTable *hash_table,
1290                             GHRFunc     func,
1291                             gpointer    user_data)
1292 {
1293   g_return_val_if_fail (hash_table != NULL, 0);
1294   g_return_val_if_fail (func != NULL, 0);
1295
1296   return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, FALSE);
1297 }
1298
1299 /**
1300  * g_hash_table_foreach:
1301  * @hash_table: a #GHashTable.
1302  * @func: the function to call for each key/value pair.
1303  * @user_data: user data to pass to the function.
1304  *
1305  * Calls the given function for each of the key/value pairs in the
1306  * #GHashTable.  The function is passed the key and value of each
1307  * pair, and the given @user_data parameter.  The hash table may not
1308  * be modified while iterating over it (you can't add/remove
1309  * items). To remove all items matching a predicate, use
1310  * g_hash_table_foreach_remove().
1311  *
1312  * See g_hash_table_find() for performance caveats for linear
1313  * order searches in contrast to g_hash_table_lookup().
1314  **/
1315 void
1316 g_hash_table_foreach (GHashTable *hash_table,
1317                       GHFunc      func,
1318                       gpointer    user_data)
1319 {
1320   gint i;
1321
1322   g_return_if_fail (hash_table != NULL);
1323   g_return_if_fail (func != NULL);
1324
1325   for (i = 0; i < hash_table->size; i++)
1326     {
1327       GHashNode *node = &hash_table->nodes [i];
1328
1329       if (node->key_hash > 1)
1330         (* func) (node->key, node->value, user_data);
1331     }
1332 }
1333
1334 /**
1335  * g_hash_table_find:
1336  * @hash_table: a #GHashTable.
1337  * @predicate:  function to test the key/value pairs for a certain property.
1338  * @user_data:  user data to pass to the function.
1339  *
1340  * Calls the given function for key/value pairs in the #GHashTable until
1341  * @predicate returns %TRUE.  The function is passed the key and value of
1342  * each pair, and the given @user_data parameter. The hash table may not
1343  * be modified while iterating over it (you can't add/remove items).
1344  *
1345  * Note, that hash tables are really only optimized for forward lookups,
1346  * i.e. g_hash_table_lookup().
1347  * So code that frequently issues g_hash_table_find() or
1348  * g_hash_table_foreach() (e.g. in the order of once per every entry in a
1349  * hash table) should probably be reworked to use additional or different
1350  * data structures for reverse lookups (keep in mind that an O(n) find/foreach
1351  * operation issued for all n values in a hash table ends up needing O(n*n)
1352  * operations).
1353  *
1354  * Return value: The value of the first key/value pair is returned, for which
1355  * func evaluates to %TRUE. If no pair with the requested property is found,
1356  * %NULL is returned.
1357  *
1358  * Since: 2.4
1359  **/
1360 gpointer
1361 g_hash_table_find (GHashTable      *hash_table,
1362                    GHRFunc          predicate,
1363                    gpointer         user_data)
1364 {
1365   gint i;
1366
1367   g_return_val_if_fail (hash_table != NULL, NULL);
1368   g_return_val_if_fail (predicate != NULL, NULL);
1369
1370   for (i = 0; i < hash_table->size; i++)
1371     {
1372       GHashNode *node = &hash_table->nodes [i];
1373
1374       if (node->key_hash > 1 && predicate (node->key, node->value, user_data))
1375         return node->value;
1376     }
1377
1378   return NULL;
1379 }
1380
1381 /**
1382  * g_hash_table_size:
1383  * @hash_table: a #GHashTable.
1384  *
1385  * Returns the number of elements contained in the #GHashTable.
1386  *
1387  * Return value: the number of key/value pairs in the #GHashTable.
1388  **/
1389 guint
1390 g_hash_table_size (GHashTable *hash_table)
1391 {
1392   g_return_val_if_fail (hash_table != NULL, 0);
1393
1394   return hash_table->nnodes;
1395 }
1396
1397 /**
1398  * g_hash_table_get_keys:
1399  * @hash_table: a #GHashTable
1400  *
1401  * Retrieves every key inside @hash_table. The returned data is valid
1402  * until @hash_table is modified.
1403  *
1404  * Return value: a #GList containing all the keys inside the hash
1405  *   table. The content of the list is owned by the hash table and
1406  *   should not be modified or freed. Use g_list_free() when done
1407  *   using the list.
1408  *
1409  * Since: 2.14
1410  */
1411 GList *
1412 g_hash_table_get_keys (GHashTable *hash_table)
1413 {
1414   gint i;
1415   GList *retval;
1416
1417   g_return_val_if_fail (hash_table != NULL, NULL);
1418
1419   retval = NULL;
1420   for (i = 0; i < hash_table->size; i++)
1421     {
1422       GHashNode *node = &hash_table->nodes [i];
1423
1424       if (node->key_hash > 1)
1425         retval = g_list_prepend (retval, node->key);
1426     }
1427
1428   return retval;
1429 }
1430
1431 /**
1432  * g_hash_table_get_values:
1433  * @hash_table: a #GHashTable
1434  *
1435  * Retrieves every value inside @hash_table. The returned data is
1436  * valid until @hash_table is modified.
1437  *
1438  * Return value: a #GList containing all the values inside the hash
1439  *   table. The content of the list is owned by the hash table and
1440  *   should not be modified or freed. Use g_list_free() when done
1441  *   using the list.
1442  *
1443  * Since: 2.14
1444  */
1445 GList *
1446 g_hash_table_get_values (GHashTable *hash_table)
1447 {
1448   gint i;
1449   GList *retval;
1450
1451   g_return_val_if_fail (hash_table != NULL, NULL);
1452
1453   retval = NULL;
1454   for (i = 0; i < hash_table->size; i++)
1455     {
1456       GHashNode *node = &hash_table->nodes [i];
1457
1458       if (node->key_hash > 1)
1459         retval = g_list_prepend (retval, node->value);
1460     }
1461
1462   return retval;
1463 }