GHashTable: Small optimization of remove-all
[glib.git] / glib / ghash.c
blobd62db574d6fc8b139425af5f61e56032e505ab75
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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.
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/.
28 * MT safe
31 #include "config.h"
33 #include <string.h> /* memset */
35 #include "ghash.h"
37 #include "gatomic.h"
38 #include "gtestutils.h"
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
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.
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.
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.
64 * To create a #GHashTable, use g_hash_table_new().
66 * To insert a key and value into a #GHashTable, use
67 * g_hash_table_insert().
69 * To lookup a value corresponding to a given key, use
70 * g_hash_table_lookup() and g_hash_table_lookup_extended().
72 * To remove a key and value, use g_hash_table_remove().
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.
78 * To destroy a #GHashTable use g_hash_table_destroy().
79 **/
81 /**
82 * GHashTable:
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 **/
89 /**
90 * GHashFunc:
91 * @key: a key.
92 * @Returns: the hash value corresponding to the key.
94 * Specifies the type of the hash function which is passed to
95 * g_hash_table_new() when a #GHashTable is created.
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.
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.
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().
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().
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.
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.
136 * GEqualFunc:
137 * @a: a value.
138 * @b: a value to compare with.
139 * @Returns: %TRUE if @a = @b; %FALSE otherwise.
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.
147 * GHashTableIter:
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().
155 #define HASH_TABLE_MIN_SHIFT 3 /* 1 << 3 == 8 buckets */
157 typedef struct _GHashNode GHashNode;
159 struct _GHashNode
161 gpointer key;
162 gpointer value;
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;
170 struct _GHashTable
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
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).
187 int version;
188 #endif
189 GDestroyNotify key_destroy_func;
190 GDestroyNotify value_destroy_func;
193 typedef struct
195 GHashTable *hash_table;
196 gpointer dummy1;
197 gpointer dummy2;
198 int position;
199 gboolean dummy3;
200 int version;
201 } RealIter;
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 [] =
209 1, /* For 1 << 0 */
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 */
243 static void
244 g_hash_table_set_shift (GHashTable *hash_table, gint shift)
246 gint i;
247 guint mask = 0;
249 hash_table->size = 1 << shift;
250 hash_table->mod = prime_mod [shift];
252 for (i = 0; i < shift; i++)
254 mask <<= 1;
255 mask |= 1;
258 hash_table->mask = mask;
261 static gint
262 g_hash_table_find_closest_shift (gint n)
264 gint i;
266 for (i = 0; n; i++)
267 n >>= 1;
269 return i;
272 static void
273 g_hash_table_set_shift_from_size (GHashTable *hash_table, gint size)
275 gint shift;
277 shift = g_hash_table_find_closest_shift (size);
278 shift = MAX (shift, HASH_TABLE_MIN_SHIFT);
280 g_hash_table_set_shift (hash_table, shift);
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
290 * Performs a lookup in the hash table.
292 * Virtually all hash operations will use this function internally.
294 * This function first computes the hash value of the key using the
295 * user's hash function.
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).
301 static inline guint
302 g_hash_table_lookup_node (GHashTable *hash_table,
303 gconstpointer key)
305 GHashNode *node;
306 guint node_index;
307 guint hash_value;
308 guint step = 0;
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. */
313 hash_value = (* hash_table->hash_func) (key);
314 if (G_UNLIKELY (hash_value <= 1))
315 hash_value = 2;
317 node_index = hash_value % hash_table->mod;
318 node = &hash_table->nodes [node_index];
320 while (node->key_hash)
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.
327 if (node->key_hash == hash_value)
329 if (hash_table->key_equal_func)
331 if (hash_table->key_equal_func (node->key, key))
332 break;
334 else if (node->key == key)
336 break;
340 step++;
341 node_index += step;
342 node_index &= hash_table->mask;
343 node = &hash_table->nodes [node_index];
346 return node_index;
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
356 * Performs a lookup in the hash table, preserving extra information
357 * usually needed for insertion.
359 * This function first computes the hash value of the key using the
360 * user's hash function.
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.
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.
371 static inline guint
372 g_hash_table_lookup_node_for_insertion (GHashTable *hash_table,
373 gconstpointer key,
374 guint *hash_return)
376 GHashNode *node;
377 guint node_index;
378 guint hash_value;
379 guint first_tombstone;
380 gboolean have_tombstone = FALSE;
381 guint step = 0;
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. */
386 hash_value = (* hash_table->hash_func) (key);
387 if (G_UNLIKELY (hash_value <= 1))
388 hash_value = 2;
390 *hash_return = hash_value;
392 node_index = hash_value % hash_table->mod;
393 node = &hash_table->nodes [node_index];
395 while (node->key_hash)
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.
402 if (node->key_hash == hash_value)
404 if (hash_table->key_equal_func)
406 if (hash_table->key_equal_func (node->key, key))
407 return node_index;
409 else if (node->key == key)
411 return node_index;
414 else if (node->key_hash == 1 && !have_tombstone)
416 first_tombstone = node_index;
417 have_tombstone = TRUE;
420 step++;
421 node_index += step;
422 node_index &= hash_table->mask;
423 node = &hash_table->nodes [node_index];
426 if (have_tombstone)
427 return first_tombstone;
429 return node_index;
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
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.
441 * If @notify is %TRUE then the destroy notify functions are called
442 * for the key and value of the hash node.
444 static void
445 g_hash_table_remove_node (GHashTable *hash_table,
446 GHashNode *node,
447 gboolean notify)
449 if (notify && hash_table->key_destroy_func)
450 hash_table->key_destroy_func (node->key);
452 if (notify && hash_table->value_destroy_func)
453 hash_table->value_destroy_func (node->value);
455 /* Erect tombstone */
456 node->key_hash = 1;
458 /* Be GC friendly */
459 node->key = NULL;
460 node->value = NULL;
462 hash_table->nnodes--;
466 * g_hash_table_remove_all_nodes:
467 * @hash_table: our #GHashTable
468 * @notify: %TRUE if the destroy notify handlers are to be called
470 * Removes all nodes from the table. Since this may be a precursor to
471 * freeing the table entirely, no resize is performed.
473 * If @notify is %TRUE then the destroy notify functions are called
474 * for the key and value of the hash node.
476 static void
477 g_hash_table_remove_all_nodes (GHashTable *hash_table,
478 gboolean notify)
480 int i;
482 if (notify &&
483 (hash_table->key_destroy_func != NULL ||
484 hash_table->value_destroy_func != NULL))
486 for (i = 0; i < hash_table->size; i++)
488 GHashNode *node = &hash_table->nodes [i];
490 if (node->key_hash > 1)
492 if (hash_table->key_destroy_func != NULL)
493 hash_table->key_destroy_func (node->key);
495 if (hash_table->value_destroy_func != NULL)
496 hash_table->value_destroy_func (node->value);
501 /* We need to set node->key_hash = 0 for all nodes - might as well be GC
502 * friendly and clear everything
504 memset (hash_table->nodes, 0, hash_table->size * sizeof (GHashNode));
506 hash_table->nnodes = 0;
507 hash_table->noccupied = 0;
511 * g_hash_table_resize:
512 * @hash_table: our #GHashTable
514 * Resizes the hash table to the optimal size based on the number of
515 * nodes currently held. If you call this function then a resize will
516 * occur, even if one does not need to occur. Use
517 * g_hash_table_maybe_resize() instead.
519 * This function may "resize" the hash table to its current size, with
520 * the side effect of cleaning up tombstones and otherwise optimizing
521 * the probe sequences.
523 static void
524 g_hash_table_resize (GHashTable *hash_table)
526 GHashNode *new_nodes;
527 gint old_size;
528 gint i;
530 old_size = hash_table->size;
531 g_hash_table_set_shift_from_size (hash_table, hash_table->nnodes * 2);
533 new_nodes = g_new0 (GHashNode, hash_table->size);
535 for (i = 0; i < old_size; i++)
537 GHashNode *node = &hash_table->nodes [i];
538 GHashNode *new_node;
539 guint hash_val;
540 guint step = 0;
542 if (node->key_hash <= 1)
543 continue;
545 hash_val = node->key_hash % hash_table->mod;
546 new_node = &new_nodes [hash_val];
548 while (new_node->key_hash)
550 step++;
551 hash_val += step;
552 hash_val &= hash_table->mask;
553 new_node = &new_nodes [hash_val];
556 *new_node = *node;
559 g_free (hash_table->nodes);
560 hash_table->nodes = new_nodes;
561 hash_table->noccupied = hash_table->nnodes;
565 * g_hash_table_maybe_resize:
566 * @hash_table: our #GHashTable
568 * Resizes the hash table, if needed.
570 * Essentially, calls g_hash_table_resize() if the table has strayed
571 * too far from its ideal size for its number of nodes.
573 static inline void
574 g_hash_table_maybe_resize (GHashTable *hash_table)
576 gint noccupied = hash_table->noccupied;
577 gint size = hash_table->size;
579 if ((size > hash_table->nnodes * 4 && size > 1 << HASH_TABLE_MIN_SHIFT) ||
580 (size <= noccupied + (noccupied / 16)))
581 g_hash_table_resize (hash_table);
585 * g_hash_table_new:
586 * @hash_func: a function to create a hash value from a key.
587 * Hash values are used to determine where keys are stored within the
588 * #GHashTable data structure. The g_direct_hash(), g_int_hash(),
589 * g_int64_hash(), g_double_hash() and g_str_hash() functions are provided
590 * for some common types of keys.
591 * If hash_func is %NULL, g_direct_hash() is used.
592 * @key_equal_func: a function to check two keys for equality. This is
593 * used when looking up keys in the #GHashTable. The g_direct_equal(),
594 * g_int_equal(), g_int64_equal(), g_double_equal() and g_str_equal()
595 * functions are provided for the most common types of keys.
596 * If @key_equal_func is %NULL, keys are compared directly in a similar
597 * fashion to g_direct_equal(), but without the overhead of a function call.
599 * Creates a new #GHashTable with a reference count of 1.
601 * Return value: a new #GHashTable.
603 GHashTable*
604 g_hash_table_new (GHashFunc hash_func,
605 GEqualFunc key_equal_func)
607 return g_hash_table_new_full (hash_func, key_equal_func, NULL, NULL);
612 * g_hash_table_new_full:
613 * @hash_func: a function to create a hash value from a key.
614 * @key_equal_func: a function to check two keys for equality.
615 * @key_destroy_func: a function to free the memory allocated for the key
616 * used when removing the entry from the #GHashTable or %NULL if you
617 * don't want to supply such a function.
618 * @value_destroy_func: a function to free the memory allocated for the
619 * value used when removing the entry from the #GHashTable or %NULL if
620 * you don't want to supply such a function.
622 * Creates a new #GHashTable like g_hash_table_new() with a reference count
623 * of 1 and allows to specify functions to free the memory allocated for the
624 * key and value that get called when removing the entry from the #GHashTable.
626 * Return value: a new #GHashTable.
628 GHashTable*
629 g_hash_table_new_full (GHashFunc hash_func,
630 GEqualFunc key_equal_func,
631 GDestroyNotify key_destroy_func,
632 GDestroyNotify value_destroy_func)
634 GHashTable *hash_table;
636 hash_table = g_slice_new (GHashTable);
637 g_hash_table_set_shift (hash_table, HASH_TABLE_MIN_SHIFT);
638 hash_table->nnodes = 0;
639 hash_table->noccupied = 0;
640 hash_table->hash_func = hash_func ? hash_func : g_direct_hash;
641 hash_table->key_equal_func = key_equal_func;
642 hash_table->ref_count = 1;
643 #ifndef G_DISABLE_ASSERT
644 hash_table->version = 0;
645 #endif
646 hash_table->key_destroy_func = key_destroy_func;
647 hash_table->value_destroy_func = value_destroy_func;
648 hash_table->nodes = g_new0 (GHashNode, hash_table->size);
650 return hash_table;
654 * g_hash_table_iter_init:
655 * @iter: an uninitialized #GHashTableIter.
656 * @hash_table: a #GHashTable.
658 * Initializes a key/value pair iterator and associates it with
659 * @hash_table. Modifying the hash table after calling this function
660 * invalidates the returned iterator.
661 * |[
662 * GHashTableIter iter;
663 * gpointer key, value;
665 * g_hash_table_iter_init (&iter, hash_table);
666 * while (g_hash_table_iter_next (&iter, &key, &value))
668 * /&ast; do something with key and value &ast;/
670 * ]|
672 * Since: 2.16
674 void
675 g_hash_table_iter_init (GHashTableIter *iter,
676 GHashTable *hash_table)
678 RealIter *ri = (RealIter *) iter;
680 g_return_if_fail (iter != NULL);
681 g_return_if_fail (hash_table != NULL);
683 ri->hash_table = hash_table;
684 ri->position = -1;
685 #ifndef G_DISABLE_ASSERT
686 ri->version = hash_table->version;
687 #endif
691 * g_hash_table_iter_next:
692 * @iter: an initialized #GHashTableIter.
693 * @key: a location to store the key, or %NULL.
694 * @value: a location to store the value, or %NULL.
696 * Advances @iter and retrieves the key and/or value that are now
697 * pointed to as a result of this advancement. If %FALSE is returned,
698 * @key and @value are not set, and the iterator becomes invalid.
700 * Return value: %FALSE if the end of the #GHashTable has been reached.
702 * Since: 2.16
704 gboolean
705 g_hash_table_iter_next (GHashTableIter *iter,
706 gpointer *key,
707 gpointer *value)
709 RealIter *ri = (RealIter *) iter;
710 GHashNode *node;
711 gint position;
713 g_return_val_if_fail (iter != NULL, FALSE);
714 #ifndef G_DISABLE_ASSERT
715 g_return_val_if_fail (ri->version == ri->hash_table->version, FALSE);
716 #endif
717 g_return_val_if_fail (ri->position < ri->hash_table->size, FALSE);
719 position = ri->position;
723 position++;
724 if (position >= ri->hash_table->size)
726 ri->position = position;
727 return FALSE;
730 node = &ri->hash_table->nodes [position];
732 while (node->key_hash <= 1);
734 if (key != NULL)
735 *key = node->key;
736 if (value != NULL)
737 *value = node->value;
739 ri->position = position;
740 return TRUE;
744 * g_hash_table_iter_get_hash_table:
745 * @iter: an initialized #GHashTableIter.
747 * Returns the #GHashTable associated with @iter.
749 * Return value: the #GHashTable associated with @iter.
751 * Since: 2.16
753 GHashTable *
754 g_hash_table_iter_get_hash_table (GHashTableIter *iter)
756 g_return_val_if_fail (iter != NULL, NULL);
758 return ((RealIter *) iter)->hash_table;
761 static void
762 iter_remove_or_steal (RealIter *ri, gboolean notify)
764 g_return_if_fail (ri != NULL);
765 #ifndef G_DISABLE_ASSERT
766 g_return_if_fail (ri->version == ri->hash_table->version);
767 #endif
768 g_return_if_fail (ri->position >= 0);
769 g_return_if_fail (ri->position < ri->hash_table->size);
771 g_hash_table_remove_node (ri->hash_table, &ri->hash_table->nodes [ri->position], notify);
773 #ifndef G_DISABLE_ASSERT
774 ri->version++;
775 ri->hash_table->version++;
776 #endif
780 * g_hash_table_iter_remove:
781 * @iter: an initialized #GHashTableIter.
783 * Removes the key/value pair currently pointed to by the iterator
784 * from its associated #GHashTable. Can only be called after
785 * g_hash_table_iter_next() returned %TRUE, and cannot be called more
786 * than once for the same key/value pair.
788 * If the #GHashTable was created using g_hash_table_new_full(), the
789 * key and value are freed using the supplied destroy functions, otherwise
790 * you have to make sure that any dynamically allocated values are freed
791 * yourself.
793 * Since: 2.16
795 void
796 g_hash_table_iter_remove (GHashTableIter *iter)
798 iter_remove_or_steal ((RealIter *) iter, TRUE);
802 * g_hash_table_iter_steal:
803 * @iter: an initialized #GHashTableIter.
805 * Removes the key/value pair currently pointed to by the iterator
806 * from its associated #GHashTable, without calling the key and value
807 * destroy functions. Can only be called after
808 * g_hash_table_iter_next() returned %TRUE, and cannot be called more
809 * than once for the same key/value pair.
811 * Since: 2.16
813 void
814 g_hash_table_iter_steal (GHashTableIter *iter)
816 iter_remove_or_steal ((RealIter *) iter, FALSE);
821 * g_hash_table_ref:
822 * @hash_table: a valid #GHashTable.
824 * Atomically increments the reference count of @hash_table by one.
825 * This function is MT-safe and may be called from any thread.
827 * Return value: the passed in #GHashTable.
829 * Since: 2.10
831 GHashTable*
832 g_hash_table_ref (GHashTable *hash_table)
834 g_return_val_if_fail (hash_table != NULL, NULL);
835 g_return_val_if_fail (hash_table->ref_count > 0, hash_table);
837 g_atomic_int_add (&hash_table->ref_count, 1);
838 return hash_table;
842 * g_hash_table_unref:
843 * @hash_table: a valid #GHashTable.
845 * Atomically decrements the reference count of @hash_table by one.
846 * If the reference count drops to 0, all keys and values will be
847 * destroyed, and all memory allocated by the hash table is released.
848 * This function is MT-safe and may be called from any thread.
850 * Since: 2.10
852 void
853 g_hash_table_unref (GHashTable *hash_table)
855 g_return_if_fail (hash_table != NULL);
856 g_return_if_fail (hash_table->ref_count > 0);
858 if (g_atomic_int_exchange_and_add (&hash_table->ref_count, -1) - 1 == 0)
860 g_hash_table_remove_all_nodes (hash_table, TRUE);
861 g_free (hash_table->nodes);
862 g_slice_free (GHashTable, hash_table);
867 * g_hash_table_destroy:
868 * @hash_table: a #GHashTable.
870 * Destroys all keys and values in the #GHashTable and decrements its
871 * reference count by 1. If keys and/or values are dynamically allocated,
872 * you should either free them first or create the #GHashTable with destroy
873 * notifiers using g_hash_table_new_full(). In the latter case the destroy
874 * functions you supplied will be called on all keys and values during the
875 * destruction phase.
877 void
878 g_hash_table_destroy (GHashTable *hash_table)
880 g_return_if_fail (hash_table != NULL);
881 g_return_if_fail (hash_table->ref_count > 0);
883 g_hash_table_remove_all (hash_table);
884 g_hash_table_unref (hash_table);
888 * g_hash_table_lookup:
889 * @hash_table: a #GHashTable.
890 * @key: the key to look up.
892 * Looks up a key in a #GHashTable. Note that this function cannot
893 * distinguish between a key that is not present and one which is present
894 * and has the value %NULL. If you need this distinction, use
895 * g_hash_table_lookup_extended().
897 * Return value: the associated value, or %NULL if the key is not found.
899 gpointer
900 g_hash_table_lookup (GHashTable *hash_table,
901 gconstpointer key)
903 GHashNode *node;
904 guint node_index;
906 g_return_val_if_fail (hash_table != NULL, NULL);
908 node_index = g_hash_table_lookup_node (hash_table, key);
909 node = &hash_table->nodes [node_index];
911 return node->key_hash ? node->value : NULL;
915 * g_hash_table_lookup_extended:
916 * @hash_table: a #GHashTable
917 * @lookup_key: the key to look up
918 * @orig_key: return location for the original key, or %NULL
919 * @value: return location for the value associated with the key, or %NULL
921 * Looks up a key in the #GHashTable, returning the original key and the
922 * associated value and a #gboolean which is %TRUE if the key was found. This
923 * is useful if you need to free the memory allocated for the original key,
924 * for example before calling g_hash_table_remove().
926 * You can actually pass %NULL for @lookup_key to test
927 * whether the %NULL key exists, provided the hash and equal functions
928 * of @hash_table are %NULL-safe.
930 * Return value: %TRUE if the key was found in the #GHashTable.
932 gboolean
933 g_hash_table_lookup_extended (GHashTable *hash_table,
934 gconstpointer lookup_key,
935 gpointer *orig_key,
936 gpointer *value)
938 GHashNode *node;
939 guint node_index;
941 g_return_val_if_fail (hash_table != NULL, FALSE);
943 node_index = g_hash_table_lookup_node (hash_table, lookup_key);
944 node = &hash_table->nodes [node_index];
946 if (!node->key_hash)
947 return FALSE;
949 if (orig_key)
950 *orig_key = node->key;
952 if (value)
953 *value = node->value;
955 return TRUE;
959 * g_hash_table_insert_internal:
960 * @hash_table: our #GHashTable
961 * @key: the key to insert
962 * @value: the value to insert
963 * @keep_new_key: if %TRUE and this key already exists in the table
964 * then call the destroy notify function on the old key. If %FALSE
965 * then call the destroy notify function on the new key.
967 * Implements the common logic for the g_hash_table_insert() and
968 * g_hash_table_replace() functions.
970 * Do a lookup of @key. If it is found, replace it with the new
971 * @value (and perhaps the new @key). If it is not found, create a
972 * new node.
974 static void
975 g_hash_table_insert_internal (GHashTable *hash_table,
976 gpointer key,
977 gpointer value,
978 gboolean keep_new_key)
980 GHashNode *node;
981 guint node_index;
982 guint key_hash;
983 guint old_hash;
985 g_return_if_fail (hash_table != NULL);
986 g_return_if_fail (hash_table->ref_count > 0);
988 node_index = g_hash_table_lookup_node_for_insertion (hash_table, key, &key_hash);
989 node = &hash_table->nodes [node_index];
991 old_hash = node->key_hash;
993 if (old_hash > 1)
995 if (keep_new_key)
997 if (hash_table->key_destroy_func)
998 hash_table->key_destroy_func (node->key);
999 node->key = key;
1001 else
1003 if (hash_table->key_destroy_func)
1004 hash_table->key_destroy_func (key);
1007 if (hash_table->value_destroy_func)
1008 hash_table->value_destroy_func (node->value);
1010 node->value = value;
1012 else
1014 node->key = key;
1015 node->value = value;
1016 node->key_hash = key_hash;
1018 hash_table->nnodes++;
1020 if (old_hash == 0)
1022 /* We replaced an empty node, and not a tombstone */
1023 hash_table->noccupied++;
1024 g_hash_table_maybe_resize (hash_table);
1027 #ifndef G_DISABLE_ASSERT
1028 hash_table->version++;
1029 #endif
1034 * g_hash_table_insert:
1035 * @hash_table: a #GHashTable.
1036 * @key: a key to insert.
1037 * @value: the value to associate with the key.
1039 * Inserts a new key and value into a #GHashTable.
1041 * If the key already exists in the #GHashTable its current value is replaced
1042 * with the new value. If you supplied a @value_destroy_func when creating the
1043 * #GHashTable, the old value is freed using that function. If you supplied
1044 * a @key_destroy_func when creating the #GHashTable, the passed key is freed
1045 * using that function.
1047 void
1048 g_hash_table_insert (GHashTable *hash_table,
1049 gpointer key,
1050 gpointer value)
1052 g_hash_table_insert_internal (hash_table, key, value, FALSE);
1056 * g_hash_table_replace:
1057 * @hash_table: a #GHashTable.
1058 * @key: a key to insert.
1059 * @value: the value to associate with the key.
1061 * Inserts a new key and value into a #GHashTable similar to
1062 * g_hash_table_insert(). The difference is that if the key already exists
1063 * in the #GHashTable, it gets replaced by the new key. If you supplied a
1064 * @value_destroy_func when creating the #GHashTable, the old value is freed
1065 * using that function. If you supplied a @key_destroy_func when creating the
1066 * #GHashTable, the old key is freed using that function.
1068 void
1069 g_hash_table_replace (GHashTable *hash_table,
1070 gpointer key,
1071 gpointer value)
1073 g_hash_table_insert_internal (hash_table, key, value, TRUE);
1077 * g_hash_table_remove_internal:
1078 * @hash_table: our #GHashTable
1079 * @key: the key to remove
1080 * @notify: %TRUE if the destroy notify handlers are to be called
1081 * Return value: %TRUE if a node was found and removed, else %FALSE
1083 * Implements the common logic for the g_hash_table_remove() and
1084 * g_hash_table_steal() functions.
1086 * Do a lookup of @key and remove it if it is found, calling the
1087 * destroy notify handlers only if @notify is %TRUE.
1089 static gboolean
1090 g_hash_table_remove_internal (GHashTable *hash_table,
1091 gconstpointer key,
1092 gboolean notify)
1094 GHashNode *node;
1095 guint node_index;
1097 g_return_val_if_fail (hash_table != NULL, FALSE);
1099 node_index = g_hash_table_lookup_node (hash_table, key);
1100 node = &hash_table->nodes [node_index];
1102 /* g_hash_table_lookup_node() never returns a tombstone, so this is safe */
1103 if (!node->key_hash)
1104 return FALSE;
1106 g_hash_table_remove_node (hash_table, node, notify);
1107 g_hash_table_maybe_resize (hash_table);
1109 #ifndef G_DISABLE_ASSERT
1110 hash_table->version++;
1111 #endif
1113 return TRUE;
1117 * g_hash_table_remove:
1118 * @hash_table: a #GHashTable.
1119 * @key: the key to remove.
1121 * Removes a key and its associated value from a #GHashTable.
1123 * If the #GHashTable was created using g_hash_table_new_full(), the
1124 * key and value are freed using the supplied destroy functions, otherwise
1125 * you have to make sure that any dynamically allocated values are freed
1126 * yourself.
1128 * Return value: %TRUE if the key was found and removed from the #GHashTable.
1130 gboolean
1131 g_hash_table_remove (GHashTable *hash_table,
1132 gconstpointer key)
1134 return g_hash_table_remove_internal (hash_table, key, TRUE);
1138 * g_hash_table_steal:
1139 * @hash_table: a #GHashTable.
1140 * @key: the key to remove.
1142 * Removes a key and its associated value from a #GHashTable without
1143 * calling the key and value destroy functions.
1145 * Return value: %TRUE if the key was found and removed from the #GHashTable.
1147 gboolean
1148 g_hash_table_steal (GHashTable *hash_table,
1149 gconstpointer key)
1151 return g_hash_table_remove_internal (hash_table, key, FALSE);
1155 * g_hash_table_remove_all:
1156 * @hash_table: a #GHashTable
1158 * Removes all keys and their associated values from a #GHashTable.
1160 * If the #GHashTable was created using g_hash_table_new_full(), the keys
1161 * and values are freed using the supplied destroy functions, otherwise you
1162 * have to make sure that any dynamically allocated values are freed
1163 * yourself.
1165 * Since: 2.12
1167 void
1168 g_hash_table_remove_all (GHashTable *hash_table)
1170 g_return_if_fail (hash_table != NULL);
1172 #ifndef G_DISABLE_ASSERT
1173 if (hash_table->nnodes != 0)
1174 hash_table->version++;
1175 #endif
1177 g_hash_table_remove_all_nodes (hash_table, TRUE);
1178 g_hash_table_maybe_resize (hash_table);
1182 * g_hash_table_steal_all:
1183 * @hash_table: a #GHashTable.
1185 * Removes all keys and their associated values from a #GHashTable
1186 * without calling the key and value destroy functions.
1188 * Since: 2.12
1190 void
1191 g_hash_table_steal_all (GHashTable *hash_table)
1193 g_return_if_fail (hash_table != NULL);
1195 #ifndef G_DISABLE_ASSERT
1196 if (hash_table->nnodes != 0)
1197 hash_table->version++;
1198 #endif
1200 g_hash_table_remove_all_nodes (hash_table, FALSE);
1201 g_hash_table_maybe_resize (hash_table);
1205 * g_hash_table_foreach_remove_or_steal:
1206 * @hash_table: our #GHashTable
1207 * @func: the user's callback function
1208 * @user_data: data for @func
1209 * @notify: %TRUE if the destroy notify handlers are to be called
1211 * Implements the common logic for g_hash_table_foreach_remove() and
1212 * g_hash_table_foreach_steal().
1214 * Iterates over every node in the table, calling @func with the key
1215 * and value of the node (and @user_data). If @func returns %TRUE the
1216 * node is removed from the table.
1218 * If @notify is true then the destroy notify handlers will be called
1219 * for each removed node.
1221 static guint
1222 g_hash_table_foreach_remove_or_steal (GHashTable *hash_table,
1223 GHRFunc func,
1224 gpointer user_data,
1225 gboolean notify)
1227 guint deleted = 0;
1228 gint i;
1230 for (i = 0; i < hash_table->size; i++)
1232 GHashNode *node = &hash_table->nodes [i];
1234 if (node->key_hash > 1 && (* func) (node->key, node->value, user_data))
1236 g_hash_table_remove_node (hash_table, node, notify);
1237 deleted++;
1241 g_hash_table_maybe_resize (hash_table);
1243 #ifndef G_DISABLE_ASSERT
1244 if (deleted > 0)
1245 hash_table->version++;
1246 #endif
1248 return deleted;
1252 * g_hash_table_foreach_remove:
1253 * @hash_table: a #GHashTable.
1254 * @func: the function to call for each key/value pair.
1255 * @user_data: user data to pass to the function.
1257 * Calls the given function for each key/value pair in the #GHashTable.
1258 * If the function returns %TRUE, then the key/value pair is removed from the
1259 * #GHashTable. If you supplied key or value destroy functions when creating
1260 * the #GHashTable, they are used to free the memory allocated for the removed
1261 * keys and values.
1263 * See #GHashTableIter for an alternative way to loop over the
1264 * key/value pairs in the hash table.
1266 * Return value: the number of key/value pairs removed.
1268 guint
1269 g_hash_table_foreach_remove (GHashTable *hash_table,
1270 GHRFunc func,
1271 gpointer user_data)
1273 g_return_val_if_fail (hash_table != NULL, 0);
1274 g_return_val_if_fail (func != NULL, 0);
1276 return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, TRUE);
1280 * g_hash_table_foreach_steal:
1281 * @hash_table: a #GHashTable.
1282 * @func: the function to call for each key/value pair.
1283 * @user_data: user data to pass to the function.
1285 * Calls the given function for each key/value pair in the #GHashTable.
1286 * If the function returns %TRUE, then the key/value pair is removed from the
1287 * #GHashTable, but no key or value destroy functions are called.
1289 * See #GHashTableIter for an alternative way to loop over the
1290 * key/value pairs in the hash table.
1292 * Return value: the number of key/value pairs removed.
1294 guint
1295 g_hash_table_foreach_steal (GHashTable *hash_table,
1296 GHRFunc func,
1297 gpointer user_data)
1299 g_return_val_if_fail (hash_table != NULL, 0);
1300 g_return_val_if_fail (func != NULL, 0);
1302 return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, FALSE);
1306 * g_hash_table_foreach:
1307 * @hash_table: a #GHashTable.
1308 * @func: the function to call for each key/value pair.
1309 * @user_data: user data to pass to the function.
1311 * Calls the given function for each of the key/value pairs in the
1312 * #GHashTable. The function is passed the key and value of each
1313 * pair, and the given @user_data parameter. The hash table may not
1314 * be modified while iterating over it (you can't add/remove
1315 * items). To remove all items matching a predicate, use
1316 * g_hash_table_foreach_remove().
1318 * See g_hash_table_find() for performance caveats for linear
1319 * order searches in contrast to g_hash_table_lookup().
1321 void
1322 g_hash_table_foreach (GHashTable *hash_table,
1323 GHFunc func,
1324 gpointer user_data)
1326 gint i;
1328 g_return_if_fail (hash_table != NULL);
1329 g_return_if_fail (func != NULL);
1331 for (i = 0; i < hash_table->size; i++)
1333 GHashNode *node = &hash_table->nodes [i];
1335 if (node->key_hash > 1)
1336 (* func) (node->key, node->value, user_data);
1341 * g_hash_table_find:
1342 * @hash_table: a #GHashTable.
1343 * @predicate: function to test the key/value pairs for a certain property.
1344 * @user_data: user data to pass to the function.
1346 * Calls the given function for key/value pairs in the #GHashTable until
1347 * @predicate returns %TRUE. The function is passed the key and value of
1348 * each pair, and the given @user_data parameter. The hash table may not
1349 * be modified while iterating over it (you can't add/remove items).
1351 * Note, that hash tables are really only optimized for forward lookups,
1352 * i.e. g_hash_table_lookup().
1353 * So code that frequently issues g_hash_table_find() or
1354 * g_hash_table_foreach() (e.g. in the order of once per every entry in a
1355 * hash table) should probably be reworked to use additional or different
1356 * data structures for reverse lookups (keep in mind that an O(n) find/foreach
1357 * operation issued for all n values in a hash table ends up needing O(n*n)
1358 * operations).
1360 * Return value: The value of the first key/value pair is returned, for which
1361 * func evaluates to %TRUE. If no pair with the requested property is found,
1362 * %NULL is returned.
1364 * Since: 2.4
1366 gpointer
1367 g_hash_table_find (GHashTable *hash_table,
1368 GHRFunc predicate,
1369 gpointer user_data)
1371 gint i;
1373 g_return_val_if_fail (hash_table != NULL, NULL);
1374 g_return_val_if_fail (predicate != NULL, NULL);
1376 for (i = 0; i < hash_table->size; i++)
1378 GHashNode *node = &hash_table->nodes [i];
1380 if (node->key_hash > 1 && predicate (node->key, node->value, user_data))
1381 return node->value;
1384 return NULL;
1388 * g_hash_table_size:
1389 * @hash_table: a #GHashTable.
1391 * Returns the number of elements contained in the #GHashTable.
1393 * Return value: the number of key/value pairs in the #GHashTable.
1395 guint
1396 g_hash_table_size (GHashTable *hash_table)
1398 g_return_val_if_fail (hash_table != NULL, 0);
1400 return hash_table->nnodes;
1404 * g_hash_table_get_keys:
1405 * @hash_table: a #GHashTable
1407 * Retrieves every key inside @hash_table. The returned data is valid
1408 * until @hash_table is modified.
1410 * Return value: a #GList containing all the keys inside the hash
1411 * table. The content of the list is owned by the hash table and
1412 * should not be modified or freed. Use g_list_free() when done
1413 * using the list.
1415 * Since: 2.14
1417 GList *
1418 g_hash_table_get_keys (GHashTable *hash_table)
1420 gint i;
1421 GList *retval;
1423 g_return_val_if_fail (hash_table != NULL, NULL);
1425 retval = NULL;
1426 for (i = 0; i < hash_table->size; i++)
1428 GHashNode *node = &hash_table->nodes [i];
1430 if (node->key_hash > 1)
1431 retval = g_list_prepend (retval, node->key);
1434 return retval;
1438 * g_hash_table_get_values:
1439 * @hash_table: a #GHashTable
1441 * Retrieves every value inside @hash_table. The returned data is
1442 * valid until @hash_table is modified.
1444 * Return value: a #GList containing all the values inside the hash
1445 * table. The content of the list is owned by the hash table and
1446 * should not be modified or freed. Use g_list_free() when done
1447 * using the list.
1449 * Since: 2.14
1451 GList *
1452 g_hash_table_get_values (GHashTable *hash_table)
1454 gint i;
1455 GList *retval;
1457 g_return_val_if_fail (hash_table != NULL, NULL);
1459 retval = NULL;
1460 for (i = 0; i < hash_table->size; i++)
1462 GHashNode *node = &hash_table->nodes [i];
1464 if (node->key_hash > 1)
1465 retval = g_list_prepend (retval, node->value);
1468 return retval;