gobject: Add prefixes to variables in G_VALUE_COLLECT*() macros
[glib.git] / glib / ghash.c
blob433004cf8ad9b4cd6cde9551d2aefd2ae15e826e
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.1 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, see <http://www.gnu.org/licenses/>.
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/.
26 * MT safe
29 #include "config.h"
31 #include <string.h> /* memset */
33 #include "ghash.h"
35 #include "glib-private.h"
36 #include "gstrfuncs.h"
37 #include "gatomic.h"
38 #include "gtestutils.h"
39 #include "gslice.h"
40 #include "grefcount.h"
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
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.
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.
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.
65 * To create a #GHashTable, use g_hash_table_new().
67 * To insert a key and value into a #GHashTable, use
68 * g_hash_table_insert().
70 * To lookup a value corresponding to a given key, use
71 * g_hash_table_lookup() and g_hash_table_lookup_extended().
73 * g_hash_table_lookup_extended() can also be used to simply
74 * check if a key is present in the hash table.
76 * To remove a key and value, use g_hash_table_remove().
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.
82 * To destroy a #GHashTable use g_hash_table_destroy().
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.
93 * #GHashTable is not designed to be statically initialised with keys and
94 * values known at compile time. To build a static hash table, use a tool such
95 * as [gperf](https://www.gnu.org/software/gperf/).
98 /**
99 * GHashTable:
101 * The #GHashTable struct is an opaque data structure to represent a
102 * [Hash Table][glib-Hash-Tables]. It should only be accessed via the
103 * following functions.
107 * GHashFunc:
108 * @key: a key
110 * Specifies the type of the hash function which is passed to
111 * g_hash_table_new() when a #GHashTable is created.
113 * The function is passed a key and should return a #guint hash value.
114 * The functions g_direct_hash(), g_int_hash() and g_str_hash() provide
115 * hash functions which can be used when the key is a #gpointer, #gint*,
116 * and #gchar* respectively.
118 * g_direct_hash() is also the appropriate hash function for keys
119 * of the form `GINT_TO_POINTER (n)` (or similar macros).
121 * A good hash functions should produce
122 * hash values that are evenly distributed over a fairly large range.
123 * The modulus is taken with the hash table size (a prime number) to
124 * find the 'bucket' to place each key into. The function should also
125 * be very fast, since it is called for each key lookup.
127 * Note that the hash functions provided by GLib have these qualities,
128 * but are not particularly robust against manufactured keys that
129 * cause hash collisions. Therefore, you should consider choosing
130 * a more secure hash function when using a GHashTable with keys
131 * that originate in untrusted data (such as HTTP requests).
132 * Using g_str_hash() in that situation might make your application
133 * vulerable to
134 * [Algorithmic Complexity Attacks](https://lwn.net/Articles/474912/).
136 * The key to choosing a good hash is unpredictability. Even
137 * cryptographic hashes are very easy to find collisions for when the
138 * remainder is taken modulo a somewhat predictable prime number. There
139 * must be an element of randomness that an attacker is unable to guess.
141 * Returns: the hash value corresponding to the key
145 * GHFunc:
146 * @key: a key
147 * @value: the value corresponding to the key
148 * @user_data: user data passed to g_hash_table_foreach()
150 * Specifies the type of the function passed to g_hash_table_foreach().
151 * It is called with each key/value pair, together with the @user_data
152 * parameter which is passed to g_hash_table_foreach().
156 * GHRFunc:
157 * @key: a key
158 * @value: the value associated with the key
159 * @user_data: user data passed to g_hash_table_remove()
161 * Specifies the type of the function passed to
162 * g_hash_table_foreach_remove(). It is called with each key/value
163 * pair, together with the @user_data parameter passed to
164 * g_hash_table_foreach_remove(). It should return %TRUE if the
165 * key/value pair should be removed from the #GHashTable.
167 * Returns: %TRUE if the key/value pair should be removed from the
168 * #GHashTable
172 * GEqualFunc:
173 * @a: a value
174 * @b: a value to compare with
176 * Specifies the type of a function used to test two values for
177 * equality. The function should return %TRUE if both values are equal
178 * and %FALSE otherwise.
180 * Returns: %TRUE if @a = @b; %FALSE otherwise
184 * GHashTableIter:
186 * A GHashTableIter structure represents an iterator that can be used
187 * to iterate over the elements of a #GHashTable. GHashTableIter
188 * structures are typically allocated on the stack and then initialized
189 * with g_hash_table_iter_init().
193 * g_hash_table_freeze:
194 * @hash_table: a #GHashTable
196 * This function is deprecated and will be removed in the next major
197 * release of GLib. It does nothing.
201 * g_hash_table_thaw:
202 * @hash_table: a #GHashTable
204 * This function is deprecated and will be removed in the next major
205 * release of GLib. It does nothing.
208 #define HASH_TABLE_MIN_SHIFT 3 /* 1 << 3 == 8 buckets */
210 #define UNUSED_HASH_VALUE 0
211 #define TOMBSTONE_HASH_VALUE 1
212 #define HASH_IS_UNUSED(h_) ((h_) == UNUSED_HASH_VALUE)
213 #define HASH_IS_TOMBSTONE(h_) ((h_) == TOMBSTONE_HASH_VALUE)
214 #define HASH_IS_REAL(h_) ((h_) >= 2)
216 struct _GHashTable
218 gint size;
219 gint mod;
220 guint mask;
221 gint nnodes;
222 gint noccupied; /* nnodes + tombstones */
224 gpointer *keys;
225 guint *hashes;
226 gpointer *values;
228 GHashFunc hash_func;
229 GEqualFunc key_equal_func;
230 gatomicrefcount ref_count;
231 #ifndef G_DISABLE_ASSERT
233 * Tracks the structure of the hash table, not its contents: is only
234 * incremented when a node is added or removed (is not incremented
235 * when the key or data of a node is modified).
237 int version;
238 #endif
239 GDestroyNotify key_destroy_func;
240 GDestroyNotify value_destroy_func;
243 typedef struct
245 GHashTable *hash_table;
246 gpointer dummy1;
247 gpointer dummy2;
248 int position;
249 gboolean dummy3;
250 int version;
251 } RealIter;
253 G_STATIC_ASSERT (sizeof (GHashTableIter) == sizeof (RealIter));
254 G_STATIC_ASSERT (_g_alignof (GHashTableIter) >= _g_alignof (RealIter));
256 /* Each table size has an associated prime modulo (the first prime
257 * lower than the table size) used to find the initial bucket. Probing
258 * then works modulo 2^n. The prime modulo is necessary to get a
259 * good distribution with poor hash functions.
261 static const gint prime_mod [] =
263 1, /* For 1 << 0 */
270 127,
271 251,
272 509,
273 1021,
274 2039,
275 4093,
276 8191,
277 16381,
278 32749,
279 65521, /* For 1 << 16 */
280 131071,
281 262139,
282 524287,
283 1048573,
284 2097143,
285 4194301,
286 8388593,
287 16777213,
288 33554393,
289 67108859,
290 134217689,
291 268435399,
292 536870909,
293 1073741789,
294 2147483647 /* For 1 << 31 */
297 static void
298 g_hash_table_set_shift (GHashTable *hash_table, gint shift)
300 gint i;
301 guint mask = 0;
303 hash_table->size = 1 << shift;
304 hash_table->mod = prime_mod [shift];
306 for (i = 0; i < shift; i++)
308 mask <<= 1;
309 mask |= 1;
312 hash_table->mask = mask;
315 static gint
316 g_hash_table_find_closest_shift (gint n)
318 gint i;
320 for (i = 0; n; i++)
321 n >>= 1;
323 return i;
326 static void
327 g_hash_table_set_shift_from_size (GHashTable *hash_table, gint size)
329 gint shift;
331 shift = g_hash_table_find_closest_shift (size);
332 shift = MAX (shift, HASH_TABLE_MIN_SHIFT);
334 g_hash_table_set_shift (hash_table, shift);
338 * g_hash_table_lookup_node:
339 * @hash_table: our #GHashTable
340 * @key: the key to lookup against
341 * @hash_return: key hash return location
343 * Performs a lookup in the hash table, preserving extra information
344 * usually needed for insertion.
346 * This function first computes the hash value of the key using the
347 * user's hash function.
349 * If an entry in the table matching @key is found then this function
350 * returns the index of that entry in the table, and if not, the
351 * index of an unused node (empty or tombstone) where the key can be
352 * inserted.
354 * The computed hash value is returned in the variable pointed to
355 * by @hash_return. This is to save insertions from having to compute
356 * the hash record again for the new record.
358 * Returns: index of the described node
360 static inline guint
361 g_hash_table_lookup_node (GHashTable *hash_table,
362 gconstpointer key,
363 guint *hash_return)
365 guint node_index;
366 guint node_hash;
367 guint hash_value;
368 guint first_tombstone = 0;
369 gboolean have_tombstone = FALSE;
370 guint step = 0;
372 /* If this happens, then the application is probably doing too much work
373 * from a destroy notifier. The alternative would be to crash any second
374 * (as keys, etc. will be NULL).
375 * Applications need to either use g_hash_table_destroy, or ensure the hash
376 * table is empty prior to removing the last reference using g_hash_table_unref(). */
377 g_assert (!g_atomic_ref_count_compare (&hash_table->ref_count, 0));
379 hash_value = hash_table->hash_func (key);
380 if (G_UNLIKELY (!HASH_IS_REAL (hash_value)))
381 hash_value = 2;
383 *hash_return = hash_value;
385 node_index = hash_value % hash_table->mod;
386 node_hash = hash_table->hashes[node_index];
388 while (!HASH_IS_UNUSED (node_hash))
390 /* We first check if our full hash values
391 * are equal so we can avoid calling the full-blown
392 * key equality function in most cases.
394 if (node_hash == hash_value)
396 gpointer node_key = hash_table->keys[node_index];
398 if (hash_table->key_equal_func)
400 if (hash_table->key_equal_func (node_key, key))
401 return node_index;
403 else if (node_key == key)
405 return node_index;
408 else if (HASH_IS_TOMBSTONE (node_hash) && !have_tombstone)
410 first_tombstone = node_index;
411 have_tombstone = TRUE;
414 step++;
415 node_index += step;
416 node_index &= hash_table->mask;
417 node_hash = hash_table->hashes[node_index];
420 if (have_tombstone)
421 return first_tombstone;
423 return node_index;
427 * g_hash_table_remove_node:
428 * @hash_table: our #GHashTable
429 * @node: pointer to node to remove
430 * @notify: %TRUE if the destroy notify handlers are to be called
432 * Removes a node from the hash table and updates the node count.
433 * The node is replaced by a tombstone. No table resize is performed.
435 * If @notify is %TRUE then the destroy notify functions are called
436 * for the key and value of the hash node.
438 static void
439 g_hash_table_remove_node (GHashTable *hash_table,
440 gint i,
441 gboolean notify)
443 gpointer key;
444 gpointer value;
446 key = hash_table->keys[i];
447 value = hash_table->values[i];
449 /* Erect tombstone */
450 hash_table->hashes[i] = TOMBSTONE_HASH_VALUE;
452 /* Be GC friendly */
453 hash_table->keys[i] = NULL;
454 hash_table->values[i] = NULL;
456 hash_table->nnodes--;
458 if (notify && hash_table->key_destroy_func)
459 hash_table->key_destroy_func (key);
461 if (notify && hash_table->value_destroy_func)
462 hash_table->value_destroy_func (value);
467 * g_hash_table_remove_all_nodes:
468 * @hash_table: our #GHashTable
469 * @notify: %TRUE if the destroy notify handlers are to be called
471 * Removes all nodes from the table. Since this may be a precursor to
472 * freeing the table entirely, no resize is performed.
474 * If @notify is %TRUE then the destroy notify functions are called
475 * for the key and value of the hash node.
477 static void
478 g_hash_table_remove_all_nodes (GHashTable *hash_table,
479 gboolean notify,
480 gboolean destruction)
482 int i;
483 gpointer key;
484 gpointer value;
485 gint old_size;
486 gpointer *old_keys;
487 gpointer *old_values;
488 guint *old_hashes;
490 /* If the hash table is already empty, there is nothing to be done. */
491 if (hash_table->nnodes == 0)
492 return;
494 hash_table->nnodes = 0;
495 hash_table->noccupied = 0;
497 if (!notify ||
498 (hash_table->key_destroy_func == NULL &&
499 hash_table->value_destroy_func == NULL))
501 if (!destruction)
503 memset (hash_table->hashes, 0, hash_table->size * sizeof (guint));
504 memset (hash_table->keys, 0, hash_table->size * sizeof (gpointer));
505 memset (hash_table->values, 0, hash_table->size * sizeof (gpointer));
508 return;
511 /* Keep the old storage space around to iterate over it. */
512 old_size = hash_table->size;
513 old_keys = hash_table->keys;
514 old_values = hash_table->values;
515 old_hashes = hash_table->hashes;
517 /* Now create a new storage space; If the table is destroyed we can use the
518 * shortcut of not creating a new storage. This saves the allocation at the
519 * cost of not allowing any recursive access.
520 * However, the application doesn't own any reference anymore, so access
521 * is not allowed. If accesses are done, then either an assert or crash
522 * *will* happen. */
523 g_hash_table_set_shift (hash_table, HASH_TABLE_MIN_SHIFT);
524 if (!destruction)
526 hash_table->keys = g_new0 (gpointer, hash_table->size);
527 hash_table->values = hash_table->keys;
528 hash_table->hashes = g_new0 (guint, hash_table->size);
530 else
532 hash_table->keys = NULL;
533 hash_table->values = NULL;
534 hash_table->hashes = NULL;
537 for (i = 0; i < old_size; i++)
539 if (HASH_IS_REAL (old_hashes[i]))
541 key = old_keys[i];
542 value = old_values[i];
544 old_hashes[i] = UNUSED_HASH_VALUE;
545 old_keys[i] = NULL;
546 old_values[i] = NULL;
548 if (hash_table->key_destroy_func != NULL)
549 hash_table->key_destroy_func (key);
551 if (hash_table->value_destroy_func != NULL)
552 hash_table->value_destroy_func (value);
556 /* Destroy old storage space. */
557 if (old_keys != old_values)
558 g_free (old_values);
560 g_free (old_keys);
561 g_free (old_hashes);
565 * g_hash_table_resize:
566 * @hash_table: our #GHashTable
568 * Resizes the hash table to the optimal size based on the number of
569 * nodes currently held. If you call this function then a resize will
570 * occur, even if one does not need to occur.
571 * Use g_hash_table_maybe_resize() instead.
573 * This function may "resize" the hash table to its current size, with
574 * the side effect of cleaning up tombstones and otherwise optimizing
575 * the probe sequences.
577 static void
578 g_hash_table_resize (GHashTable *hash_table)
580 gpointer *new_keys;
581 gpointer *new_values;
582 guint *new_hashes;
583 gint old_size;
584 gint i;
586 old_size = hash_table->size;
587 g_hash_table_set_shift_from_size (hash_table, hash_table->nnodes * 2);
589 new_keys = g_new0 (gpointer, hash_table->size);
590 if (hash_table->keys == hash_table->values)
591 new_values = new_keys;
592 else
593 new_values = g_new0 (gpointer, hash_table->size);
594 new_hashes = g_new0 (guint, hash_table->size);
596 for (i = 0; i < old_size; i++)
598 guint node_hash = hash_table->hashes[i];
599 guint hash_val;
600 guint step = 0;
602 if (!HASH_IS_REAL (node_hash))
603 continue;
605 hash_val = node_hash % hash_table->mod;
607 while (!HASH_IS_UNUSED (new_hashes[hash_val]))
609 step++;
610 hash_val += step;
611 hash_val &= hash_table->mask;
614 new_hashes[hash_val] = hash_table->hashes[i];
615 new_keys[hash_val] = hash_table->keys[i];
616 new_values[hash_val] = hash_table->values[i];
619 if (hash_table->keys != hash_table->values)
620 g_free (hash_table->values);
622 g_free (hash_table->keys);
623 g_free (hash_table->hashes);
625 hash_table->keys = new_keys;
626 hash_table->values = new_values;
627 hash_table->hashes = new_hashes;
629 hash_table->noccupied = hash_table->nnodes;
633 * g_hash_table_maybe_resize:
634 * @hash_table: our #GHashTable
636 * Resizes the hash table, if needed.
638 * Essentially, calls g_hash_table_resize() if the table has strayed
639 * too far from its ideal size for its number of nodes.
641 static inline void
642 g_hash_table_maybe_resize (GHashTable *hash_table)
644 gint noccupied = hash_table->noccupied;
645 gint size = hash_table->size;
647 if ((size > hash_table->nnodes * 4 && size > 1 << HASH_TABLE_MIN_SHIFT) ||
648 (size <= noccupied + (noccupied / 16)))
649 g_hash_table_resize (hash_table);
653 * g_hash_table_new:
654 * @hash_func: a function to create a hash value from a key
655 * @key_equal_func: a function to check two keys for equality
657 * Creates a new #GHashTable with a reference count of 1.
659 * Hash values returned by @hash_func are used to determine where keys
660 * are stored within the #GHashTable data structure. The g_direct_hash(),
661 * g_int_hash(), g_int64_hash(), g_double_hash() and g_str_hash()
662 * functions are provided for some common types of keys.
663 * If @hash_func is %NULL, g_direct_hash() is used.
665 * @key_equal_func is used when looking up keys in the #GHashTable.
666 * The g_direct_equal(), g_int_equal(), g_int64_equal(), g_double_equal()
667 * and g_str_equal() functions are provided for the most common types
668 * of keys. If @key_equal_func is %NULL, keys are compared directly in
669 * a similar fashion to g_direct_equal(), but without the overhead of
670 * a function call. @key_equal_func is called with the key from the hash table
671 * as its first parameter, and the user-provided key to check against as
672 * its second.
674 * Returns: a new #GHashTable
676 GHashTable *
677 g_hash_table_new (GHashFunc hash_func,
678 GEqualFunc key_equal_func)
680 return g_hash_table_new_full (hash_func, key_equal_func, NULL, NULL);
685 * g_hash_table_new_full:
686 * @hash_func: a function to create a hash value from a key
687 * @key_equal_func: a function to check two keys for equality
688 * @key_destroy_func: (nullable): a function to free the memory allocated for the key
689 * used when removing the entry from the #GHashTable, or %NULL
690 * if you don't want to supply such a function.
691 * @value_destroy_func: (nullable): a function to free the memory allocated for the
692 * value used when removing the entry from the #GHashTable, or %NULL
693 * if you don't want to supply such a function.
695 * Creates a new #GHashTable like g_hash_table_new() with a reference
696 * count of 1 and allows to specify functions to free the memory
697 * allocated for the key and value that get called when removing the
698 * entry from the #GHashTable.
700 * Since version 2.42 it is permissible for destroy notify functions to
701 * recursively remove further items from the hash table. This is only
702 * permissible if the application still holds a reference to the hash table.
703 * This means that you may need to ensure that the hash table is empty by
704 * calling g_hash_table_remove_all() before releasing the last reference using
705 * g_hash_table_unref().
707 * Returns: a new #GHashTable
709 GHashTable *
710 g_hash_table_new_full (GHashFunc hash_func,
711 GEqualFunc key_equal_func,
712 GDestroyNotify key_destroy_func,
713 GDestroyNotify value_destroy_func)
715 GHashTable *hash_table;
717 hash_table = g_slice_new (GHashTable);
718 g_hash_table_set_shift (hash_table, HASH_TABLE_MIN_SHIFT);
719 g_atomic_ref_count_init (&hash_table->ref_count);
720 hash_table->nnodes = 0;
721 hash_table->noccupied = 0;
722 hash_table->hash_func = hash_func ? hash_func : g_direct_hash;
723 hash_table->key_equal_func = key_equal_func;
724 #ifndef G_DISABLE_ASSERT
725 hash_table->version = 0;
726 #endif
727 hash_table->key_destroy_func = key_destroy_func;
728 hash_table->value_destroy_func = value_destroy_func;
729 hash_table->keys = g_new0 (gpointer, hash_table->size);
730 hash_table->values = hash_table->keys;
731 hash_table->hashes = g_new0 (guint, hash_table->size);
733 return hash_table;
737 * g_hash_table_iter_init:
738 * @iter: an uninitialized #GHashTableIter
739 * @hash_table: a #GHashTable
741 * Initializes a key/value pair iterator and associates it with
742 * @hash_table. Modifying the hash table after calling this function
743 * invalidates the returned iterator.
744 * |[<!-- language="C" -->
745 * GHashTableIter iter;
746 * gpointer key, value;
748 * g_hash_table_iter_init (&iter, hash_table);
749 * while (g_hash_table_iter_next (&iter, &key, &value))
751 * // do something with key and value
753 * ]|
755 * Since: 2.16
757 void
758 g_hash_table_iter_init (GHashTableIter *iter,
759 GHashTable *hash_table)
761 RealIter *ri = (RealIter *) iter;
763 g_return_if_fail (iter != NULL);
764 g_return_if_fail (hash_table != NULL);
766 ri->hash_table = hash_table;
767 ri->position = -1;
768 #ifndef G_DISABLE_ASSERT
769 ri->version = hash_table->version;
770 #endif
774 * g_hash_table_iter_next:
775 * @iter: an initialized #GHashTableIter
776 * @key: (out) (optional): a location to store the key
777 * @value: (out) (optional) (nullable): a location to store the value
779 * Advances @iter and retrieves the key and/or value that are now
780 * pointed to as a result of this advancement. If %FALSE is returned,
781 * @key and @value are not set, and the iterator becomes invalid.
783 * Returns: %FALSE if the end of the #GHashTable has been reached.
785 * Since: 2.16
787 gboolean
788 g_hash_table_iter_next (GHashTableIter *iter,
789 gpointer *key,
790 gpointer *value)
792 RealIter *ri = (RealIter *) iter;
793 gint position;
795 g_return_val_if_fail (iter != NULL, FALSE);
796 #ifndef G_DISABLE_ASSERT
797 g_return_val_if_fail (ri->version == ri->hash_table->version, FALSE);
798 #endif
799 g_return_val_if_fail (ri->position < ri->hash_table->size, FALSE);
801 position = ri->position;
805 position++;
806 if (position >= ri->hash_table->size)
808 ri->position = position;
809 return FALSE;
812 while (!HASH_IS_REAL (ri->hash_table->hashes[position]));
814 if (key != NULL)
815 *key = ri->hash_table->keys[position];
816 if (value != NULL)
817 *value = ri->hash_table->values[position];
819 ri->position = position;
820 return TRUE;
824 * g_hash_table_iter_get_hash_table:
825 * @iter: an initialized #GHashTableIter
827 * Returns the #GHashTable associated with @iter.
829 * Returns: the #GHashTable associated with @iter.
831 * Since: 2.16
833 GHashTable *
834 g_hash_table_iter_get_hash_table (GHashTableIter *iter)
836 g_return_val_if_fail (iter != NULL, NULL);
838 return ((RealIter *) iter)->hash_table;
841 static void
842 iter_remove_or_steal (RealIter *ri, gboolean notify)
844 g_return_if_fail (ri != NULL);
845 #ifndef G_DISABLE_ASSERT
846 g_return_if_fail (ri->version == ri->hash_table->version);
847 #endif
848 g_return_if_fail (ri->position >= 0);
849 g_return_if_fail (ri->position < ri->hash_table->size);
851 g_hash_table_remove_node (ri->hash_table, ri->position, notify);
853 #ifndef G_DISABLE_ASSERT
854 ri->version++;
855 ri->hash_table->version++;
856 #endif
860 * g_hash_table_iter_remove:
861 * @iter: an initialized #GHashTableIter
863 * Removes the key/value pair currently pointed to by the iterator
864 * from its associated #GHashTable. Can only be called after
865 * g_hash_table_iter_next() returned %TRUE, and cannot be called
866 * more than once for the same key/value pair.
868 * If the #GHashTable was created using g_hash_table_new_full(),
869 * the key and value are freed using the supplied destroy functions,
870 * otherwise you have to make sure that any dynamically allocated
871 * values are freed yourself.
873 * It is safe to continue iterating the #GHashTable afterward:
874 * |[<!-- language="C" -->
875 * while (g_hash_table_iter_next (&iter, &key, &value))
877 * if (condition)
878 * g_hash_table_iter_remove (&iter);
880 * ]|
882 * Since: 2.16
884 void
885 g_hash_table_iter_remove (GHashTableIter *iter)
887 iter_remove_or_steal ((RealIter *) iter, TRUE);
891 * g_hash_table_insert_node:
892 * @hash_table: our #GHashTable
893 * @node_index: pointer to node to insert/replace
894 * @key_hash: key hash
895 * @key: (nullable): key to replace with, or %NULL
896 * @value: value to replace with
897 * @keep_new_key: whether to replace the key in the node with @key
898 * @reusing_key: whether @key was taken out of the existing node
900 * Inserts a value at @node_index in the hash table and updates it.
902 * If @key has been taken out of the existing node (ie it is not
903 * passed in via a g_hash_table_insert/replace) call, then @reusing_key
904 * should be %TRUE.
906 * Returns: %TRUE if the key did not exist yet
908 static gboolean
909 g_hash_table_insert_node (GHashTable *hash_table,
910 guint node_index,
911 guint key_hash,
912 gpointer new_key,
913 gpointer new_value,
914 gboolean keep_new_key,
915 gboolean reusing_key)
917 gboolean already_exists;
918 guint old_hash;
919 gpointer key_to_free = NULL;
920 gpointer value_to_free = NULL;
922 old_hash = hash_table->hashes[node_index];
923 already_exists = HASH_IS_REAL (old_hash);
925 /* Proceed in three steps. First, deal with the key because it is the
926 * most complicated. Then consider if we need to split the table in
927 * two (because writing the value will result in the set invariant
928 * becoming broken). Then deal with the value.
930 * There are three cases for the key:
932 * - entry already exists in table, reusing key:
933 * free the just-passed-in new_key and use the existing value
935 * - entry already exists in table, not reusing key:
936 * free the entry in the table, use the new key
938 * - entry not already in table:
939 * use the new key, free nothing
941 * We update the hash at the same time...
943 if (already_exists)
945 /* Note: we must record the old value before writing the new key
946 * because we might change the value in the event that the two
947 * arrays are shared.
949 value_to_free = hash_table->values[node_index];
951 if (keep_new_key)
953 key_to_free = hash_table->keys[node_index];
954 hash_table->keys[node_index] = new_key;
956 else
957 key_to_free = new_key;
959 else
961 hash_table->hashes[node_index] = key_hash;
962 hash_table->keys[node_index] = new_key;
965 /* Step two: check if the value that we are about to write to the
966 * table is the same as the key in the same position. If it's not,
967 * split the table.
969 if (G_UNLIKELY (hash_table->keys == hash_table->values && hash_table->keys[node_index] != new_value))
970 hash_table->values = g_memdup (hash_table->keys, sizeof (gpointer) * hash_table->size);
972 /* Step 3: Actually do the write */
973 hash_table->values[node_index] = new_value;
975 /* Now, the bookkeeping... */
976 if (!already_exists)
978 hash_table->nnodes++;
980 if (HASH_IS_UNUSED (old_hash))
982 /* We replaced an empty node, and not a tombstone */
983 hash_table->noccupied++;
984 g_hash_table_maybe_resize (hash_table);
987 #ifndef G_DISABLE_ASSERT
988 hash_table->version++;
989 #endif
992 if (already_exists)
994 if (hash_table->key_destroy_func && !reusing_key)
995 (* hash_table->key_destroy_func) (key_to_free);
996 if (hash_table->value_destroy_func)
997 (* hash_table->value_destroy_func) (value_to_free);
1000 return !already_exists;
1004 * g_hash_table_iter_replace:
1005 * @iter: an initialized #GHashTableIter
1006 * @value: the value to replace with
1008 * Replaces the value currently pointed to by the iterator
1009 * from its associated #GHashTable. Can only be called after
1010 * g_hash_table_iter_next() returned %TRUE.
1012 * If you supplied a @value_destroy_func when creating the
1013 * #GHashTable, the old value is freed using that function.
1015 * Since: 2.30
1017 void
1018 g_hash_table_iter_replace (GHashTableIter *iter,
1019 gpointer value)
1021 RealIter *ri;
1022 guint node_hash;
1023 gpointer key;
1025 ri = (RealIter *) iter;
1027 g_return_if_fail (ri != NULL);
1028 #ifndef G_DISABLE_ASSERT
1029 g_return_if_fail (ri->version == ri->hash_table->version);
1030 #endif
1031 g_return_if_fail (ri->position >= 0);
1032 g_return_if_fail (ri->position < ri->hash_table->size);
1034 node_hash = ri->hash_table->hashes[ri->position];
1035 key = ri->hash_table->keys[ri->position];
1037 g_hash_table_insert_node (ri->hash_table, ri->position, node_hash, key, value, TRUE, TRUE);
1039 #ifndef G_DISABLE_ASSERT
1040 ri->version++;
1041 ri->hash_table->version++;
1042 #endif
1046 * g_hash_table_iter_steal:
1047 * @iter: an initialized #GHashTableIter
1049 * Removes the key/value pair currently pointed to by the
1050 * iterator from its associated #GHashTable, without calling
1051 * the key and value destroy functions. Can only be called
1052 * after g_hash_table_iter_next() returned %TRUE, and cannot
1053 * be called more than once for the same key/value pair.
1055 * Since: 2.16
1057 void
1058 g_hash_table_iter_steal (GHashTableIter *iter)
1060 iter_remove_or_steal ((RealIter *) iter, FALSE);
1065 * g_hash_table_ref:
1066 * @hash_table: a valid #GHashTable
1068 * Atomically increments the reference count of @hash_table by one.
1069 * This function is MT-safe and may be called from any thread.
1071 * Returns: the passed in #GHashTable
1073 * Since: 2.10
1075 GHashTable *
1076 g_hash_table_ref (GHashTable *hash_table)
1078 g_return_val_if_fail (hash_table != NULL, NULL);
1080 g_atomic_ref_count_inc (&hash_table->ref_count);
1082 return hash_table;
1086 * g_hash_table_unref:
1087 * @hash_table: a valid #GHashTable
1089 * Atomically decrements the reference count of @hash_table by one.
1090 * If the reference count drops to 0, all keys and values will be
1091 * destroyed, and all memory allocated by the hash table is released.
1092 * This function is MT-safe and may be called from any thread.
1094 * Since: 2.10
1096 void
1097 g_hash_table_unref (GHashTable *hash_table)
1099 g_return_if_fail (hash_table != NULL);
1101 if (g_atomic_ref_count_dec (&hash_table->ref_count))
1103 g_hash_table_remove_all_nodes (hash_table, TRUE, TRUE);
1104 if (hash_table->keys != hash_table->values)
1105 g_free (hash_table->values);
1106 g_free (hash_table->keys);
1107 g_free (hash_table->hashes);
1108 g_slice_free (GHashTable, hash_table);
1113 * g_hash_table_destroy:
1114 * @hash_table: a #GHashTable
1116 * Destroys all keys and values in the #GHashTable and decrements its
1117 * reference count by 1. If keys and/or values are dynamically allocated,
1118 * you should either free them first or create the #GHashTable with destroy
1119 * notifiers using g_hash_table_new_full(). In the latter case the destroy
1120 * functions you supplied will be called on all keys and values during the
1121 * destruction phase.
1123 void
1124 g_hash_table_destroy (GHashTable *hash_table)
1126 g_return_if_fail (hash_table != NULL);
1128 g_hash_table_remove_all (hash_table);
1129 g_hash_table_unref (hash_table);
1133 * g_hash_table_lookup:
1134 * @hash_table: a #GHashTable
1135 * @key: the key to look up
1137 * Looks up a key in a #GHashTable. Note that this function cannot
1138 * distinguish between a key that is not present and one which is present
1139 * and has the value %NULL. If you need this distinction, use
1140 * g_hash_table_lookup_extended().
1142 * Returns: (nullable): the associated value, or %NULL if the key is not found
1144 gpointer
1145 g_hash_table_lookup (GHashTable *hash_table,
1146 gconstpointer key)
1148 guint node_index;
1149 guint node_hash;
1151 g_return_val_if_fail (hash_table != NULL, NULL);
1153 node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1155 return HASH_IS_REAL (hash_table->hashes[node_index])
1156 ? hash_table->values[node_index]
1157 : NULL;
1161 * g_hash_table_lookup_extended:
1162 * @hash_table: a #GHashTable
1163 * @lookup_key: the key to look up
1164 * @orig_key: (out) (optional): return location for the original key
1165 * @value: (out) (optional) (nullable): return location for the value associated
1166 * with the key
1168 * Looks up a key in the #GHashTable, returning the original key and the
1169 * associated value and a #gboolean which is %TRUE if the key was found. This
1170 * is useful if you need to free the memory allocated for the original key,
1171 * for example before calling g_hash_table_remove().
1173 * You can actually pass %NULL for @lookup_key to test
1174 * whether the %NULL key exists, provided the hash and equal functions
1175 * of @hash_table are %NULL-safe.
1177 * Returns: %TRUE if the key was found in the #GHashTable
1179 gboolean
1180 g_hash_table_lookup_extended (GHashTable *hash_table,
1181 gconstpointer lookup_key,
1182 gpointer *orig_key,
1183 gpointer *value)
1185 guint node_index;
1186 guint node_hash;
1188 g_return_val_if_fail (hash_table != NULL, FALSE);
1190 node_index = g_hash_table_lookup_node (hash_table, lookup_key, &node_hash);
1192 if (!HASH_IS_REAL (hash_table->hashes[node_index]))
1193 return FALSE;
1195 if (orig_key)
1196 *orig_key = hash_table->keys[node_index];
1198 if (value)
1199 *value = hash_table->values[node_index];
1201 return TRUE;
1205 * g_hash_table_insert_internal:
1206 * @hash_table: our #GHashTable
1207 * @key: the key to insert
1208 * @value: the value to insert
1209 * @keep_new_key: if %TRUE and this key already exists in the table
1210 * then call the destroy notify function on the old key. If %FALSE
1211 * then call the destroy notify function on the new key.
1213 * Implements the common logic for the g_hash_table_insert() and
1214 * g_hash_table_replace() functions.
1216 * Do a lookup of @key. If it is found, replace it with the new
1217 * @value (and perhaps the new @key). If it is not found, create
1218 * a new node.
1220 * Returns: %TRUE if the key did not exist yet
1222 static gboolean
1223 g_hash_table_insert_internal (GHashTable *hash_table,
1224 gpointer key,
1225 gpointer value,
1226 gboolean keep_new_key)
1228 guint key_hash;
1229 guint node_index;
1231 g_return_val_if_fail (hash_table != NULL, FALSE);
1233 node_index = g_hash_table_lookup_node (hash_table, key, &key_hash);
1235 return g_hash_table_insert_node (hash_table, node_index, key_hash, key, value, keep_new_key, FALSE);
1239 * g_hash_table_insert:
1240 * @hash_table: a #GHashTable
1241 * @key: a key to insert
1242 * @value: the value to associate with the key
1244 * Inserts a new key and value into a #GHashTable.
1246 * If the key already exists in the #GHashTable its current
1247 * value is replaced with the new value. If you supplied a
1248 * @value_destroy_func when creating the #GHashTable, the old
1249 * value is freed using that function. If you supplied a
1250 * @key_destroy_func when creating the #GHashTable, the passed
1251 * key is freed using that function.
1253 * Starting from GLib 2.40, this function returns a boolean value to
1254 * indicate whether the newly added value was already in the hash table
1255 * or not.
1257 * Returns: %TRUE if the key did not exist yet
1259 gboolean
1260 g_hash_table_insert (GHashTable *hash_table,
1261 gpointer key,
1262 gpointer value)
1264 return g_hash_table_insert_internal (hash_table, key, value, FALSE);
1268 * g_hash_table_replace:
1269 * @hash_table: a #GHashTable
1270 * @key: a key to insert
1271 * @value: the value to associate with the key
1273 * Inserts a new key and value into a #GHashTable similar to
1274 * g_hash_table_insert(). The difference is that if the key
1275 * already exists in the #GHashTable, it gets replaced by the
1276 * new key. If you supplied a @value_destroy_func when creating
1277 * the #GHashTable, the old value is freed using that function.
1278 * If you supplied a @key_destroy_func when creating the
1279 * #GHashTable, the old key is freed using that function.
1281 * Starting from GLib 2.40, this function returns a boolean value to
1282 * indicate whether the newly added value was already in the hash table
1283 * or not.
1285 * Returns: %TRUE if the key did not exist yet
1287 gboolean
1288 g_hash_table_replace (GHashTable *hash_table,
1289 gpointer key,
1290 gpointer value)
1292 return g_hash_table_insert_internal (hash_table, key, value, TRUE);
1296 * g_hash_table_add:
1297 * @hash_table: a #GHashTable
1298 * @key: a key to insert
1300 * This is a convenience function for using a #GHashTable as a set. It
1301 * is equivalent to calling g_hash_table_replace() with @key as both the
1302 * key and the value.
1304 * When a hash table only ever contains keys that have themselves as the
1305 * corresponding value it is able to be stored more efficiently. See
1306 * the discussion in the section description.
1308 * Starting from GLib 2.40, this function returns a boolean value to
1309 * indicate whether the newly added value was already in the hash table
1310 * or not.
1312 * Returns: %TRUE if the key did not exist yet
1314 * Since: 2.32
1316 gboolean
1317 g_hash_table_add (GHashTable *hash_table,
1318 gpointer key)
1320 return g_hash_table_insert_internal (hash_table, key, key, TRUE);
1324 * g_hash_table_contains:
1325 * @hash_table: a #GHashTable
1326 * @key: a key to check
1328 * Checks if @key is in @hash_table.
1330 * Returns: %TRUE if @key is in @hash_table, %FALSE otherwise.
1332 * Since: 2.32
1334 gboolean
1335 g_hash_table_contains (GHashTable *hash_table,
1336 gconstpointer key)
1338 guint node_index;
1339 guint node_hash;
1341 g_return_val_if_fail (hash_table != NULL, FALSE);
1343 node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1345 return HASH_IS_REAL (hash_table->hashes[node_index]);
1349 * g_hash_table_remove_internal:
1350 * @hash_table: our #GHashTable
1351 * @key: the key to remove
1352 * @notify: %TRUE if the destroy notify handlers are to be called
1353 * Returns: %TRUE if a node was found and removed, else %FALSE
1355 * Implements the common logic for the g_hash_table_remove() and
1356 * g_hash_table_steal() functions.
1358 * Do a lookup of @key and remove it if it is found, calling the
1359 * destroy notify handlers only if @notify is %TRUE.
1361 static gboolean
1362 g_hash_table_remove_internal (GHashTable *hash_table,
1363 gconstpointer key,
1364 gboolean notify)
1366 guint node_index;
1367 guint node_hash;
1369 g_return_val_if_fail (hash_table != NULL, FALSE);
1371 node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1373 if (!HASH_IS_REAL (hash_table->hashes[node_index]))
1374 return FALSE;
1376 g_hash_table_remove_node (hash_table, node_index, notify);
1377 g_hash_table_maybe_resize (hash_table);
1379 #ifndef G_DISABLE_ASSERT
1380 hash_table->version++;
1381 #endif
1383 return TRUE;
1387 * g_hash_table_remove:
1388 * @hash_table: a #GHashTable
1389 * @key: the key to remove
1391 * Removes a key and its associated value from a #GHashTable.
1393 * If the #GHashTable was created using g_hash_table_new_full(), the
1394 * key and value are freed using the supplied destroy functions, otherwise
1395 * you have to make sure that any dynamically allocated values are freed
1396 * yourself.
1398 * Returns: %TRUE if the key was found and removed from the #GHashTable
1400 gboolean
1401 g_hash_table_remove (GHashTable *hash_table,
1402 gconstpointer key)
1404 return g_hash_table_remove_internal (hash_table, key, TRUE);
1408 * g_hash_table_steal:
1409 * @hash_table: a #GHashTable
1410 * @key: the key to remove
1412 * Removes a key and its associated value from a #GHashTable without
1413 * calling the key and value destroy functions.
1415 * Returns: %TRUE if the key was found and removed from the #GHashTable
1417 gboolean
1418 g_hash_table_steal (GHashTable *hash_table,
1419 gconstpointer key)
1421 return g_hash_table_remove_internal (hash_table, key, FALSE);
1425 * g_hash_table_steal_extended:
1426 * @hash_table: a #GHashTable
1427 * @lookup_key: the key to look up
1428 * @stolen_key: (out) (optional) (transfer full): return location for the
1429 * original key
1430 * @stolen_value: (out) (optional) (nullable) (transfer full): return location
1431 * for the value associated with the key
1433 * Looks up a key in the #GHashTable, stealing the original key and the
1434 * associated value and returning %TRUE if the key was found. If the key was
1435 * not found, %FALSE is returned.
1437 * If found, the stolen key and value are removed from the hash table without
1438 * calling the key and value destroy functions, and ownership is transferred to
1439 * the caller of this method; as with g_hash_table_steal().
1441 * You can pass %NULL for @lookup_key, provided the hash and equal functions
1442 * of @hash_table are %NULL-safe.
1444 * Returns: %TRUE if the key was found in the #GHashTable
1445 * Since: 2.58
1447 gboolean
1448 g_hash_table_steal_extended (GHashTable *hash_table,
1449 gconstpointer lookup_key,
1450 gpointer *stolen_key,
1451 gpointer *stolen_value)
1453 guint node_index;
1454 guint node_hash;
1456 g_return_val_if_fail (hash_table != NULL, FALSE);
1458 node_index = g_hash_table_lookup_node (hash_table, lookup_key, &node_hash);
1460 if (!HASH_IS_REAL (hash_table->hashes[node_index]))
1462 if (stolen_key != NULL)
1463 *stolen_key = NULL;
1464 if (stolen_value != NULL)
1465 *stolen_value = NULL;
1466 return FALSE;
1469 if (stolen_key != NULL)
1470 *stolen_key = g_steal_pointer (&hash_table->keys[node_index]);
1472 if (stolen_value != NULL)
1473 *stolen_value = g_steal_pointer (&hash_table->values[node_index]);
1475 g_hash_table_remove_node (hash_table, node_index, FALSE);
1476 g_hash_table_maybe_resize (hash_table);
1478 #ifndef G_DISABLE_ASSERT
1479 hash_table->version++;
1480 #endif
1482 return TRUE;
1486 * g_hash_table_remove_all:
1487 * @hash_table: a #GHashTable
1489 * Removes all keys and their associated values from a #GHashTable.
1491 * If the #GHashTable was created using g_hash_table_new_full(),
1492 * the keys and values are freed using the supplied destroy functions,
1493 * otherwise you have to make sure that any dynamically allocated
1494 * values are freed yourself.
1496 * Since: 2.12
1498 void
1499 g_hash_table_remove_all (GHashTable *hash_table)
1501 g_return_if_fail (hash_table != NULL);
1503 #ifndef G_DISABLE_ASSERT
1504 if (hash_table->nnodes != 0)
1505 hash_table->version++;
1506 #endif
1508 g_hash_table_remove_all_nodes (hash_table, TRUE, FALSE);
1509 g_hash_table_maybe_resize (hash_table);
1513 * g_hash_table_steal_all:
1514 * @hash_table: a #GHashTable
1516 * Removes all keys and their associated values from a #GHashTable
1517 * without calling the key and value destroy functions.
1519 * Since: 2.12
1521 void
1522 g_hash_table_steal_all (GHashTable *hash_table)
1524 g_return_if_fail (hash_table != NULL);
1526 #ifndef G_DISABLE_ASSERT
1527 if (hash_table->nnodes != 0)
1528 hash_table->version++;
1529 #endif
1531 g_hash_table_remove_all_nodes (hash_table, FALSE, FALSE);
1532 g_hash_table_maybe_resize (hash_table);
1536 * g_hash_table_foreach_remove_or_steal:
1537 * @hash_table: a #GHashTable
1538 * @func: the user's callback function
1539 * @user_data: data for @func
1540 * @notify: %TRUE if the destroy notify handlers are to be called
1542 * Implements the common logic for g_hash_table_foreach_remove()
1543 * and g_hash_table_foreach_steal().
1545 * Iterates over every node in the table, calling @func with the key
1546 * and value of the node (and @user_data). If @func returns %TRUE the
1547 * node is removed from the table.
1549 * If @notify is true then the destroy notify handlers will be called
1550 * for each removed node.
1552 static guint
1553 g_hash_table_foreach_remove_or_steal (GHashTable *hash_table,
1554 GHRFunc func,
1555 gpointer user_data,
1556 gboolean notify)
1558 guint deleted = 0;
1559 gint i;
1560 #ifndef G_DISABLE_ASSERT
1561 gint version = hash_table->version;
1562 #endif
1564 for (i = 0; i < hash_table->size; i++)
1566 guint node_hash = hash_table->hashes[i];
1567 gpointer node_key = hash_table->keys[i];
1568 gpointer node_value = hash_table->values[i];
1570 if (HASH_IS_REAL (node_hash) &&
1571 (* func) (node_key, node_value, user_data))
1573 g_hash_table_remove_node (hash_table, i, notify);
1574 deleted++;
1577 #ifndef G_DISABLE_ASSERT
1578 g_return_val_if_fail (version == hash_table->version, 0);
1579 #endif
1582 g_hash_table_maybe_resize (hash_table);
1584 #ifndef G_DISABLE_ASSERT
1585 if (deleted > 0)
1586 hash_table->version++;
1587 #endif
1589 return deleted;
1593 * g_hash_table_foreach_remove:
1594 * @hash_table: a #GHashTable
1595 * @func: the function to call for each key/value pair
1596 * @user_data: user data to pass to the function
1598 * Calls the given function for each key/value pair in the
1599 * #GHashTable. If the function returns %TRUE, then the key/value
1600 * pair is removed from the #GHashTable. If you supplied key or
1601 * value destroy functions when creating the #GHashTable, they are
1602 * used to free the memory allocated for the removed keys and values.
1604 * See #GHashTableIter for an alternative way to loop over the
1605 * key/value pairs in the hash table.
1607 * Returns: the number of key/value pairs removed
1609 guint
1610 g_hash_table_foreach_remove (GHashTable *hash_table,
1611 GHRFunc func,
1612 gpointer user_data)
1614 g_return_val_if_fail (hash_table != NULL, 0);
1615 g_return_val_if_fail (func != NULL, 0);
1617 return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, TRUE);
1621 * g_hash_table_foreach_steal:
1622 * @hash_table: a #GHashTable
1623 * @func: the function to call for each key/value pair
1624 * @user_data: user data to pass to the function
1626 * Calls the given function for each key/value pair in the
1627 * #GHashTable. If the function returns %TRUE, then the key/value
1628 * pair is removed from the #GHashTable, but no key or value
1629 * destroy functions are called.
1631 * See #GHashTableIter for an alternative way to loop over the
1632 * key/value pairs in the hash table.
1634 * Returns: the number of key/value pairs removed.
1636 guint
1637 g_hash_table_foreach_steal (GHashTable *hash_table,
1638 GHRFunc func,
1639 gpointer user_data)
1641 g_return_val_if_fail (hash_table != NULL, 0);
1642 g_return_val_if_fail (func != NULL, 0);
1644 return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, FALSE);
1648 * g_hash_table_foreach:
1649 * @hash_table: a #GHashTable
1650 * @func: the function to call for each key/value pair
1651 * @user_data: user data to pass to the function
1653 * Calls the given function for each of the key/value pairs in the
1654 * #GHashTable. The function is passed the key and value of each
1655 * pair, and the given @user_data parameter. The hash table may not
1656 * be modified while iterating over it (you can't add/remove
1657 * items). To remove all items matching a predicate, use
1658 * g_hash_table_foreach_remove().
1660 * See g_hash_table_find() for performance caveats for linear
1661 * order searches in contrast to g_hash_table_lookup().
1663 void
1664 g_hash_table_foreach (GHashTable *hash_table,
1665 GHFunc func,
1666 gpointer user_data)
1668 gint i;
1669 #ifndef G_DISABLE_ASSERT
1670 gint version;
1671 #endif
1673 g_return_if_fail (hash_table != NULL);
1674 g_return_if_fail (func != NULL);
1676 #ifndef G_DISABLE_ASSERT
1677 version = hash_table->version;
1678 #endif
1680 for (i = 0; i < hash_table->size; i++)
1682 guint node_hash = hash_table->hashes[i];
1683 gpointer node_key = hash_table->keys[i];
1684 gpointer node_value = hash_table->values[i];
1686 if (HASH_IS_REAL (node_hash))
1687 (* func) (node_key, node_value, user_data);
1689 #ifndef G_DISABLE_ASSERT
1690 g_return_if_fail (version == hash_table->version);
1691 #endif
1696 * g_hash_table_find:
1697 * @hash_table: a #GHashTable
1698 * @predicate: function to test the key/value pairs for a certain property
1699 * @user_data: user data to pass to the function
1701 * Calls the given function for key/value pairs in the #GHashTable
1702 * until @predicate returns %TRUE. The function is passed the key
1703 * and value of each pair, and the given @user_data parameter. The
1704 * hash table may not be modified while iterating over it (you can't
1705 * add/remove items).
1707 * Note, that hash tables are really only optimized for forward
1708 * lookups, i.e. g_hash_table_lookup(). So code that frequently issues
1709 * g_hash_table_find() or g_hash_table_foreach() (e.g. in the order of
1710 * once per every entry in a hash table) should probably be reworked
1711 * to use additional or different data structures for reverse lookups
1712 * (keep in mind that an O(n) find/foreach operation issued for all n
1713 * values in a hash table ends up needing O(n*n) operations).
1715 * Returns: (nullable): The value of the first key/value pair is returned,
1716 * for which @predicate evaluates to %TRUE. If no pair with the
1717 * requested property is found, %NULL is returned.
1719 * Since: 2.4
1721 gpointer
1722 g_hash_table_find (GHashTable *hash_table,
1723 GHRFunc predicate,
1724 gpointer user_data)
1726 gint i;
1727 #ifndef G_DISABLE_ASSERT
1728 gint version;
1729 #endif
1730 gboolean match;
1732 g_return_val_if_fail (hash_table != NULL, NULL);
1733 g_return_val_if_fail (predicate != NULL, NULL);
1735 #ifndef G_DISABLE_ASSERT
1736 version = hash_table->version;
1737 #endif
1739 match = FALSE;
1741 for (i = 0; i < hash_table->size; i++)
1743 guint node_hash = hash_table->hashes[i];
1744 gpointer node_key = hash_table->keys[i];
1745 gpointer node_value = hash_table->values[i];
1747 if (HASH_IS_REAL (node_hash))
1748 match = predicate (node_key, node_value, user_data);
1750 #ifndef G_DISABLE_ASSERT
1751 g_return_val_if_fail (version == hash_table->version, NULL);
1752 #endif
1754 if (match)
1755 return node_value;
1758 return NULL;
1762 * g_hash_table_size:
1763 * @hash_table: a #GHashTable
1765 * Returns the number of elements contained in the #GHashTable.
1767 * Returns: the number of key/value pairs in the #GHashTable.
1769 guint
1770 g_hash_table_size (GHashTable *hash_table)
1772 g_return_val_if_fail (hash_table != NULL, 0);
1774 return hash_table->nnodes;
1778 * g_hash_table_get_keys:
1779 * @hash_table: a #GHashTable
1781 * Retrieves every key inside @hash_table. The returned data is valid
1782 * until changes to the hash release those keys.
1784 * This iterates over every entry in the hash table to build its return value.
1785 * To iterate over the entries in a #GHashTable more efficiently, use a
1786 * #GHashTableIter.
1788 * Returns: (transfer container): a #GList containing all the keys
1789 * inside the hash table. The content of the list is owned by the
1790 * hash table and should not be modified or freed. Use g_list_free()
1791 * when done using the list.
1793 * Since: 2.14
1795 GList *
1796 g_hash_table_get_keys (GHashTable *hash_table)
1798 gint i;
1799 GList *retval;
1801 g_return_val_if_fail (hash_table != NULL, NULL);
1803 retval = NULL;
1804 for (i = 0; i < hash_table->size; i++)
1806 if (HASH_IS_REAL (hash_table->hashes[i]))
1807 retval = g_list_prepend (retval, hash_table->keys[i]);
1810 return retval;
1814 * g_hash_table_get_keys_as_array:
1815 * @hash_table: a #GHashTable
1816 * @length: (out): the length of the returned array
1818 * Retrieves every key inside @hash_table, as an array.
1820 * The returned array is %NULL-terminated but may contain %NULL as a
1821 * key. Use @length to determine the true length if it's possible that
1822 * %NULL was used as the value for a key.
1824 * Note: in the common case of a string-keyed #GHashTable, the return
1825 * value of this function can be conveniently cast to (const gchar **).
1827 * This iterates over every entry in the hash table to build its return value.
1828 * To iterate over the entries in a #GHashTable more efficiently, use a
1829 * #GHashTableIter.
1831 * You should always free the return result with g_free(). In the
1832 * above-mentioned case of a string-keyed hash table, it may be
1833 * appropriate to use g_strfreev() if you call g_hash_table_steal_all()
1834 * first to transfer ownership of the keys.
1836 * Returns: (array length=length) (transfer container): a
1837 * %NULL-terminated array containing each key from the table.
1839 * Since: 2.40
1841 gpointer *
1842 g_hash_table_get_keys_as_array (GHashTable *hash_table,
1843 guint *length)
1845 gpointer *result;
1846 guint i, j = 0;
1848 result = g_new (gpointer, hash_table->nnodes + 1);
1849 for (i = 0; i < hash_table->size; i++)
1851 if (HASH_IS_REAL (hash_table->hashes[i]))
1852 result[j++] = hash_table->keys[i];
1854 g_assert_cmpint (j, ==, hash_table->nnodes);
1855 result[j] = NULL;
1857 if (length)
1858 *length = j;
1860 return result;
1864 * g_hash_table_get_values:
1865 * @hash_table: a #GHashTable
1867 * Retrieves every value inside @hash_table. The returned data
1868 * is valid until @hash_table is modified.
1870 * This iterates over every entry in the hash table to build its return value.
1871 * To iterate over the entries in a #GHashTable more efficiently, use a
1872 * #GHashTableIter.
1874 * Returns: (transfer container): a #GList containing all the values
1875 * inside the hash table. The content of the list is owned by the
1876 * hash table and should not be modified or freed. Use g_list_free()
1877 * when done using the list.
1879 * Since: 2.14
1881 GList *
1882 g_hash_table_get_values (GHashTable *hash_table)
1884 gint i;
1885 GList *retval;
1887 g_return_val_if_fail (hash_table != NULL, NULL);
1889 retval = NULL;
1890 for (i = 0; i < hash_table->size; i++)
1892 if (HASH_IS_REAL (hash_table->hashes[i]))
1893 retval = g_list_prepend (retval, hash_table->values[i]);
1896 return retval;
1899 /* Hash functions.
1903 * g_str_equal:
1904 * @v1: (not nullable): a key
1905 * @v2: (not nullable): a key to compare with @v1
1907 * Compares two strings for byte-by-byte equality and returns %TRUE
1908 * if they are equal. It can be passed to g_hash_table_new() as the
1909 * @key_equal_func parameter, when using non-%NULL strings as keys in a
1910 * #GHashTable.
1912 * This function is typically used for hash table comparisons, but can be used
1913 * for general purpose comparisons of non-%NULL strings. For a %NULL-safe string
1914 * comparison function, see g_strcmp0().
1916 * Returns: %TRUE if the two keys match
1918 gboolean
1919 g_str_equal (gconstpointer v1,
1920 gconstpointer v2)
1922 const gchar *string1 = v1;
1923 const gchar *string2 = v2;
1925 return strcmp (string1, string2) == 0;
1929 * g_str_hash:
1930 * @v: (not nullable): a string key
1932 * Converts a string to a hash value.
1934 * This function implements the widely used "djb" hash apparently
1935 * posted by Daniel Bernstein to comp.lang.c some time ago. The 32
1936 * bit unsigned hash value starts at 5381 and for each byte 'c' in
1937 * the string, is updated: `hash = hash * 33 + c`. This function
1938 * uses the signed value of each byte.
1940 * It can be passed to g_hash_table_new() as the @hash_func parameter,
1941 * when using non-%NULL strings as keys in a #GHashTable.
1943 * Note that this function may not be a perfect fit for all use cases.
1944 * For example, it produces some hash collisions with strings as short
1945 * as 2.
1947 * Returns: a hash value corresponding to the key
1949 guint
1950 g_str_hash (gconstpointer v)
1952 const signed char *p;
1953 guint32 h = 5381;
1955 for (p = v; *p != '\0'; p++)
1956 h = (h << 5) + h + *p;
1958 return h;
1962 * g_direct_hash:
1963 * @v: (nullable): a #gpointer key
1965 * Converts a gpointer to a hash value.
1966 * It can be passed to g_hash_table_new() as the @hash_func parameter,
1967 * when using opaque pointers compared by pointer value as keys in a
1968 * #GHashTable.
1970 * This hash function is also appropriate for keys that are integers
1971 * stored in pointers, such as `GINT_TO_POINTER (n)`.
1973 * Returns: a hash value corresponding to the key.
1975 guint
1976 g_direct_hash (gconstpointer v)
1978 return GPOINTER_TO_UINT (v);
1982 * g_direct_equal:
1983 * @v1: (nullable): a key
1984 * @v2: (nullable): a key to compare with @v1
1986 * Compares two #gpointer arguments and returns %TRUE if they are equal.
1987 * It can be passed to g_hash_table_new() as the @key_equal_func
1988 * parameter, when using opaque pointers compared by pointer value as
1989 * keys in a #GHashTable.
1991 * This equality function is also appropriate for keys that are integers
1992 * stored in pointers, such as `GINT_TO_POINTER (n)`.
1994 * Returns: %TRUE if the two keys match.
1996 gboolean
1997 g_direct_equal (gconstpointer v1,
1998 gconstpointer v2)
2000 return v1 == v2;
2004 * g_int_equal:
2005 * @v1: (not nullable): a pointer to a #gint key
2006 * @v2: (not nullable): a pointer to a #gint key to compare with @v1
2008 * Compares the two #gint values being pointed to and returns
2009 * %TRUE if they are equal.
2010 * It can be passed to g_hash_table_new() as the @key_equal_func
2011 * parameter, when using non-%NULL pointers to integers as keys in a
2012 * #GHashTable.
2014 * Note that this function acts on pointers to #gint, not on #gint
2015 * directly: if your hash table's keys are of the form
2016 * `GINT_TO_POINTER (n)`, use g_direct_equal() instead.
2018 * Returns: %TRUE if the two keys match.
2020 gboolean
2021 g_int_equal (gconstpointer v1,
2022 gconstpointer v2)
2024 return *((const gint*) v1) == *((const gint*) v2);
2028 * g_int_hash:
2029 * @v: (not nullable): a pointer to a #gint key
2031 * Converts a pointer to a #gint to a hash value.
2032 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2033 * when using non-%NULL pointers to integer values as keys in a #GHashTable.
2035 * Note that this function acts on pointers to #gint, not on #gint
2036 * directly: if your hash table's keys are of the form
2037 * `GINT_TO_POINTER (n)`, use g_direct_hash() instead.
2039 * Returns: a hash value corresponding to the key.
2041 guint
2042 g_int_hash (gconstpointer v)
2044 return *(const gint*) v;
2048 * g_int64_equal:
2049 * @v1: (not nullable): a pointer to a #gint64 key
2050 * @v2: (not nullable): a pointer to a #gint64 key to compare with @v1
2052 * Compares the two #gint64 values being pointed to and returns
2053 * %TRUE if they are equal.
2054 * It can be passed to g_hash_table_new() as the @key_equal_func
2055 * parameter, when using non-%NULL pointers to 64-bit integers as keys in a
2056 * #GHashTable.
2058 * Returns: %TRUE if the two keys match.
2060 * Since: 2.22
2062 gboolean
2063 g_int64_equal (gconstpointer v1,
2064 gconstpointer v2)
2066 return *((const gint64*) v1) == *((const gint64*) v2);
2070 * g_int64_hash:
2071 * @v: (not nullable): a pointer to a #gint64 key
2073 * Converts a pointer to a #gint64 to a hash value.
2075 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2076 * when using non-%NULL pointers to 64-bit integer values as keys in a
2077 * #GHashTable.
2079 * Returns: a hash value corresponding to the key.
2081 * Since: 2.22
2083 guint
2084 g_int64_hash (gconstpointer v)
2086 return (guint) *(const gint64*) v;
2090 * g_double_equal:
2091 * @v1: (not nullable): a pointer to a #gdouble key
2092 * @v2: (not nullable): a pointer to a #gdouble key to compare with @v1
2094 * Compares the two #gdouble values being pointed to and returns
2095 * %TRUE if they are equal.
2096 * It can be passed to g_hash_table_new() as the @key_equal_func
2097 * parameter, when using non-%NULL pointers to doubles as keys in a
2098 * #GHashTable.
2100 * Returns: %TRUE if the two keys match.
2102 * Since: 2.22
2104 gboolean
2105 g_double_equal (gconstpointer v1,
2106 gconstpointer v2)
2108 return *((const gdouble*) v1) == *((const gdouble*) v2);
2112 * g_double_hash:
2113 * @v: (not nullable): a pointer to a #gdouble key
2115 * Converts a pointer to a #gdouble to a hash value.
2116 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2117 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2118 * when using non-%NULL pointers to doubles as keys in a #GHashTable.
2120 * Returns: a hash value corresponding to the key.
2122 * Since: 2.22
2124 guint
2125 g_double_hash (gconstpointer v)
2127 return (guint) *(const gdouble*) v;