Coverage Report

Created: 2025-12-23 06:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/glib/glib/ghash.c
Line
Count
Source
1
/* GLIB - Library of useful routines for C programming
2
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3
 *
4
 * SPDX-License-Identifier: LGPL-2.1-or-later
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
/*
21
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22
 * file for a list of people on the GLib Team.  See the ChangeLog
23
 * files for a list of changes.  These files are distributed with
24
 * GLib at ftp://ftp.gtk.org/pub/gtk/.
25
 */
26
27
/*
28
 * MT safe
29
 */
30
31
#include "config.h"
32
33
#include <string.h>  /* memset */
34
35
#include "ghash.h"
36
#include "gmacros.h"
37
#include "glib-private.h"
38
#include "gstrfuncs.h"
39
#include "gatomic.h"
40
#include "gtestutils.h"
41
#include "gslice.h"
42
#include "grefcount.h"
43
#include "gvalgrind.h"
44
45
/* The following #pragma is here so we can do this...
46
 *
47
 *   #ifndef USE_SMALL_ARRAYS
48
 *     is_big = TRUE;
49
 *   #endif
50
 *     return is_big ? *(((gpointer *) a) + index) : GUINT_TO_POINTER (*(((guint *) a) + index));
51
 *
52
 * ...instead of this...
53
 *
54
 *   #ifndef USE_SMALL_ARRAYS
55
 *     return *(((gpointer *) a) + index);
56
 *   #else
57
 *     return is_big ? *(((gpointer *) a) + index) : GUINT_TO_POINTER (*(((guint *) a) + index));
58
 *   #endif
59
 *
60
 * ...and still compile successfully when -Werror=duplicated-branches is passed. */
61
62
#if defined(__GNUC__) && __GNUC__ > 6
63
#pragma GCC diagnostic ignored "-Wduplicated-branches"
64
#endif
65
66
/**
67
 * SECTION:hash_tables
68
 * @title: Hash Tables
69
 * @short_description: associations between keys and values so that
70
 *     given a key the value can be found quickly
71
 *
72
 * A #GHashTable provides associations between keys and values which is
73
 * optimized so that given a key, the associated value can be found,
74
 * inserted or removed in amortized O(1). All operations going through
75
 * each element take O(n) time (list all keys/values, table resize, etc.).
76
 *
77
 * Note that neither keys nor values are copied when inserted into the
78
 * #GHashTable, so they must exist for the lifetime of the #GHashTable.
79
 * This means that the use of static strings is OK, but temporary
80
 * strings (i.e. those created in buffers and those returned by GTK
81
 * widgets) should be copied with g_strdup() before being inserted.
82
 *
83
 * If keys or values are dynamically allocated, you must be careful to
84
 * ensure that they are freed when they are removed from the
85
 * #GHashTable, and also when they are overwritten by new insertions
86
 * into the #GHashTable. It is also not advisable to mix static strings
87
 * and dynamically-allocated strings in a #GHashTable, because it then
88
 * becomes difficult to determine whether the string should be freed.
89
 *
90
 * To create a #GHashTable, use g_hash_table_new().
91
 *
92
 * To insert a key and value into a #GHashTable, use
93
 * g_hash_table_insert().
94
 *
95
 * To look up a value corresponding to a given key, use
96
 * g_hash_table_lookup() and g_hash_table_lookup_extended().
97
 *
98
 * g_hash_table_lookup_extended() can also be used to simply
99
 * check if a key is present in the hash table.
100
 *
101
 * To remove a key and value, use g_hash_table_remove().
102
 *
103
 * To call a function for each key and value pair use
104
 * g_hash_table_foreach() or use an iterator to iterate over the
105
 * key/value pairs in the hash table, see #GHashTableIter. The iteration order
106
 * of a hash table is not defined, and you must not rely on iterating over
107
 * keys/values in the same order as they were inserted.
108
 *
109
 * To destroy a #GHashTable use g_hash_table_destroy().
110
 *
111
 * A common use-case for hash tables is to store information about a
112
 * set of keys, without associating any particular value with each
113
 * key. GHashTable optimizes one way of doing so: If you store only
114
 * key-value pairs where key == value, then GHashTable does not
115
 * allocate memory to store the values, which can be a considerable
116
 * space saving, if your set is large. The functions
117
 * g_hash_table_add() and g_hash_table_contains() are designed to be
118
 * used when using #GHashTable this way.
119
 *
120
 * #GHashTable is not designed to be statically initialised with keys and
121
 * values known at compile time. To build a static hash table, use a tool such
122
 * as [gperf](https://www.gnu.org/software/gperf/).
123
 */
124
125
/**
126
 * GHashTable:
127
 *
128
 * The #GHashTable struct is an opaque data structure to represent a
129
 * [Hash Table][glib-Hash-Tables]. It should only be accessed via the
130
 * following functions.
131
 */
132
133
/**
134
 * GHashFunc:
135
 * @key: a key
136
 *
137
 * Specifies the type of the hash function which is passed to
138
 * g_hash_table_new() when a #GHashTable is created.
139
 *
140
 * The function is passed a key and should return a #guint hash value.
141
 * The functions g_direct_hash(), g_int_hash() and g_str_hash() provide
142
 * hash functions which can be used when the key is a #gpointer, #gint*,
143
 * and #gchar* respectively.
144
 *
145
 * g_direct_hash() is also the appropriate hash function for keys
146
 * of the form `GINT_TO_POINTER (n)` (or similar macros).
147
 *
148
 * A good hash functions should produce
149
 * hash values that are evenly distributed over a fairly large range.
150
 * The modulus is taken with the hash table size (a prime number) to
151
 * find the 'bucket' to place each key into. The function should also
152
 * be very fast, since it is called for each key lookup.
153
 *
154
 * Note that the hash functions provided by GLib have these qualities,
155
 * but are not particularly robust against manufactured keys that
156
 * cause hash collisions. Therefore, you should consider choosing
157
 * a more secure hash function when using a GHashTable with keys
158
 * that originate in untrusted data (such as HTTP requests).
159
 * Using g_str_hash() in that situation might make your application
160
 * vulnerable to
161
 * [Algorithmic Complexity Attacks](https://lwn.net/Articles/474912/).
162
 *
163
 * The key to choosing a good hash is unpredictability.  Even
164
 * cryptographic hashes are very easy to find collisions for when the
165
 * remainder is taken modulo a somewhat predictable prime number.  There
166
 * must be an element of randomness that an attacker is unable to guess.
167
 *
168
 * Returns: the hash value corresponding to the key
169
 */
170
171
/**
172
 * GHFunc:
173
 * @key: a key
174
 * @value: the value corresponding to the key
175
 * @user_data: user data passed to g_hash_table_foreach()
176
 *
177
 * Specifies the type of the function passed to g_hash_table_foreach().
178
 * It is called with each key/value pair, together with the @user_data
179
 * parameter which is passed to g_hash_table_foreach().
180
 */
181
182
/**
183
 * GHRFunc:
184
 * @key: a key
185
 * @value: the value associated with the key
186
 * @user_data: user data passed to g_hash_table_remove()
187
 *
188
 * Specifies the type of the function passed to
189
 * g_hash_table_foreach_remove(). It is called with each key/value
190
 * pair, together with the @user_data parameter passed to
191
 * g_hash_table_foreach_remove(). It should return %TRUE if the
192
 * key/value pair should be removed from the #GHashTable.
193
 *
194
 * Returns: %TRUE if the key/value pair should be removed from the
195
 *     #GHashTable
196
 */
197
198
/**
199
 * GEqualFunc:
200
 * @a: a value
201
 * @b: a value to compare with
202
 *
203
 * Specifies the type of a function used to test two values for
204
 * equality. The function should return %TRUE if both values are equal
205
 * and %FALSE otherwise.
206
 *
207
 * Returns: %TRUE if @a = @b; %FALSE otherwise
208
 */
209
210
/**
211
 * GHashTableIter:
212
 *
213
 * A GHashTableIter structure represents an iterator that can be used
214
 * to iterate over the elements of a #GHashTable. GHashTableIter
215
 * structures are typically allocated on the stack and then initialized
216
 * with g_hash_table_iter_init().
217
 *
218
 * The iteration order of a #GHashTableIter over the keys/values in a hash
219
 * table is not defined.
220
 */
221
222
/**
223
 * g_hash_table_freeze:
224
 * @hash_table: a #GHashTable
225
 *
226
 * This function is deprecated and will be removed in the next major
227
 * release of GLib. It does nothing.
228
 */
229
230
/**
231
 * g_hash_table_thaw:
232
 * @hash_table: a #GHashTable
233
 *
234
 * This function is deprecated and will be removed in the next major
235
 * release of GLib. It does nothing.
236
 */
237
238
36.1k
#define HASH_TABLE_MIN_SHIFT 3  /* 1 << 3 == 8 buckets */
239
240
194k
#define UNUSED_HASH_VALUE 0
241
22.8k
#define TOMBSTONE_HASH_VALUE 1
242
194k
#define HASH_IS_UNUSED(h_) ((h_) == UNUSED_HASH_VALUE)
243
35.1k
#define HASH_IS_TOMBSTONE(h_) ((h_) == TOMBSTONE_HASH_VALUE)
244
164k
#define HASH_IS_REAL(h_) ((h_) >= 2)
245
246
/* If int is smaller than void * on our arch, we start out with
247
 * int-sized keys and values and resize to pointer-sized entries as
248
 * needed. This saves a good amount of memory when the HT is being
249
 * used with e.g. GUINT_TO_POINTER(). */
250
251
27.9k
#define BIG_ENTRY_SIZE (SIZEOF_VOID_P)
252
27.7k
#define SMALL_ENTRY_SIZE (SIZEOF_INT)
253
254
/* NB: The USE_SMALL_ARRAYS code assumes pointers are at most 8 bytes. */
255
#if SMALL_ENTRY_SIZE < BIG_ENTRY_SIZE && BIG_ENTRY_SIZE <= 8
256
# define USE_SMALL_ARRAYS
257
#endif
258
259
struct _GHashTable
260
{
261
  gsize            size;
262
  gint             mod;
263
  guint            mask;
264
  guint            nnodes;
265
  guint            noccupied;  /* nnodes + tombstones */
266
267
  guint            have_big_keys : 1;
268
  guint            have_big_values : 1;
269
270
  gpointer         keys;
271
  guint           *hashes;
272
  gpointer         values;
273
274
  GHashFunc        hash_func;
275
  GEqualFunc       key_equal_func;
276
  gatomicrefcount  ref_count;
277
#ifndef G_DISABLE_ASSERT
278
  /*
279
   * Tracks the structure of the hash table, not its contents: is only
280
   * incremented when a node is added or removed (is not incremented
281
   * when the key or data of a node is modified).
282
   */
283
  int              version;
284
#endif
285
  GDestroyNotify   key_destroy_func;
286
  GDestroyNotify   value_destroy_func;
287
};
288
289
typedef struct
290
{
291
  GHashTable  *hash_table;
292
  gpointer     dummy1;
293
  gpointer     dummy2;
294
  gint         position;
295
  gboolean     dummy3;
296
  gintptr      version;
297
} RealIter;
298
299
G_STATIC_ASSERT (sizeof (GHashTableIter) == sizeof (RealIter));
300
G_STATIC_ASSERT (G_ALIGNOF (GHashTableIter) >= G_ALIGNOF (RealIter));
301
302
/* Each table size has an associated prime modulo (the first prime
303
 * lower than the table size) used to find the initial bucket. Probing
304
 * then works modulo 2^n. The prime modulo is necessary to get a
305
 * good distribution with poor hash functions.
306
 */
307
static const gint prime_mod [] =
308
{
309
  1,          /* For 1 << 0 */
310
  2,
311
  3,
312
  7,
313
  13,
314
  31,
315
  61,
316
  127,
317
  251,
318
  509,
319
  1021,
320
  2039,
321
  4093,
322
  8191,
323
  16381,
324
  32749,
325
  65521,      /* For 1 << 16 */
326
  131071,
327
  262139,
328
  524287,
329
  1048573,
330
  2097143,
331
  4194301,
332
  8388593,
333
  16777213,
334
  33554393,
335
  67108859,
336
  134217689,
337
  268435399,
338
  536870909,
339
  1073741789,
340
  2147483647  /* For 1 << 31 */
341
};
342
343
static void
344
g_hash_table_set_shift (GHashTable *hash_table, gint shift)
345
10.3k
{
346
10.3k
  hash_table->size = 1 << shift;
347
10.3k
  hash_table->mod  = prime_mod [shift];
348
349
  /* hash_table->size is always a power of two, so we can calculate the mask
350
   * by simply subtracting 1 from it. The leading assertion ensures that
351
   * we're really dealing with a power of two. */
352
353
10.3k
  g_assert ((hash_table->size & (hash_table->size - 1)) == 0);
354
10.3k
  hash_table->mask = hash_table->size - 1;
355
10.3k
}
356
357
static gint
358
g_hash_table_find_closest_shift (gint n)
359
26
{
360
26
  gint i;
361
362
160
  for (i = 0; n; i++)
363
134
    n >>= 1;
364
365
26
  return i;
366
26
}
367
368
static void
369
g_hash_table_set_shift_from_size (GHashTable *hash_table, gint size)
370
26
{
371
26
  gint shift;
372
373
26
  shift = g_hash_table_find_closest_shift (size);
374
26
  shift = MAX (shift, HASH_TABLE_MIN_SHIFT);
375
376
26
  g_hash_table_set_shift (hash_table, shift);
377
26
}
378
379
static inline gpointer
380
g_hash_table_realloc_key_or_value_array (gpointer a, guint size, G_GNUC_UNUSED gboolean is_big)
381
10.3k
{
382
10.3k
#ifdef USE_SMALL_ARRAYS
383
10.3k
  return g_realloc (a, size * (is_big ? BIG_ENTRY_SIZE : SMALL_ENTRY_SIZE));
384
#else
385
  return g_renew (gpointer, a, size);
386
#endif
387
10.3k
}
388
389
static inline gpointer
390
g_hash_table_fetch_key_or_value (gpointer a, guint index, gboolean is_big)
391
89.6k
{
392
#ifndef USE_SMALL_ARRAYS
393
  is_big = TRUE;
394
#endif
395
89.6k
  return is_big ? *(((gpointer *) a) + index) : GUINT_TO_POINTER (*(((guint *) a) + index));
396
89.6k
}
397
398
static inline void
399
g_hash_table_assign_key_or_value (gpointer a, guint index, gboolean is_big, gpointer v)
400
39.6k
{
401
#ifndef USE_SMALL_ARRAYS
402
  is_big = TRUE;
403
#endif
404
39.6k
  if (is_big)
405
39.1k
    *(((gpointer *) a) + index) = v;
406
485
  else
407
485
    *(((guint *) a) + index) = GPOINTER_TO_UINT (v);
408
39.6k
}
409
410
static inline gpointer
411
g_hash_table_evict_key_or_value (gpointer a, guint index, gboolean is_big, gpointer v)
412
1.12k
{
413
#ifndef USE_SMALL_ARRAYS
414
  is_big = TRUE;
415
#endif
416
1.12k
  if (is_big)
417
782
    {
418
782
      gpointer r = *(((gpointer *) a) + index);
419
782
      *(((gpointer *) a) + index) = v;
420
782
      return r;
421
782
    }
422
342
  else
423
342
    {
424
342
      gpointer r = GUINT_TO_POINTER (*(((guint *) a) + index));
425
342
      *(((guint *) a) + index) = GPOINTER_TO_UINT (v);
426
342
      return r;
427
342
    }
428
1.12k
}
429
430
static inline guint
431
g_hash_table_hash_to_index (GHashTable *hash_table, guint hash)
432
162k
{
433
  /* Multiply the hash by a small prime before applying the modulo. This
434
   * prevents the table from becoming densely packed, even with a poor hash
435
   * function. A densely packed table would have poor performance on
436
   * workloads with many failed lookups or a high degree of churn. */
437
162k
  return (hash * 11) % hash_table->mod;
438
162k
}
439
440
/*
441
 * g_hash_table_lookup_node:
442
 * @hash_table: our #GHashTable
443
 * @key: the key to look up against
444
 * @hash_return: key hash return location
445
 *
446
 * Performs a lookup in the hash table, preserving extra information
447
 * usually needed for insertion.
448
 *
449
 * This function first computes the hash value of the key using the
450
 * user's hash function.
451
 *
452
 * If an entry in the table matching @key is found then this function
453
 * returns the index of that entry in the table, and if not, the
454
 * index of an unused node (empty or tombstone) where the key can be
455
 * inserted.
456
 *
457
 * The computed hash value is returned in the variable pointed to
458
 * by @hash_return. This is to save insertions from having to compute
459
 * the hash record again for the new record.
460
 *
461
 * Returns: index of the described node
462
 */
463
static inline guint
464
g_hash_table_lookup_node (GHashTable    *hash_table,
465
                          gconstpointer  key,
466
                          guint         *hash_return)
467
162k
{
468
162k
  guint node_index;
469
162k
  guint node_hash;
470
162k
  guint hash_value;
471
162k
  guint first_tombstone = 0;
472
162k
  gboolean have_tombstone = FALSE;
473
162k
  guint step = 0;
474
475
162k
  hash_value = hash_table->hash_func (key);
476
162k
  if (G_UNLIKELY (!HASH_IS_REAL (hash_value)))
477
41
    hash_value = 2;
478
479
162k
  *hash_return = hash_value;
480
481
162k
  node_index = g_hash_table_hash_to_index (hash_table, hash_value);
482
162k
  node_hash = hash_table->hashes[node_index];
483
484
180k
  while (!HASH_IS_UNUSED (node_hash))
485
59.7k
    {
486
      /* We first check if our full hash values
487
       * are equal so we can avoid calling the full-blown
488
       * key equality function in most cases.
489
       */
490
59.7k
      if (node_hash == hash_value)
491
42.1k
        {
492
42.1k
          gpointer node_key = g_hash_table_fetch_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys);
493
494
42.1k
          if (hash_table->key_equal_func)
495
42.1k
            {
496
42.1k
              if (hash_table->key_equal_func (node_key, key))
497
42.0k
                return node_index;
498
42.1k
            }
499
0
          else if (node_key == key)
500
0
            {
501
0
              return node_index;
502
0
            }
503
42.1k
        }
504
17.5k
      else if (HASH_IS_TOMBSTONE (node_hash) && !have_tombstone)
505
0
        {
506
0
          first_tombstone = node_index;
507
0
          have_tombstone = TRUE;
508
0
        }
509
510
17.7k
      step++;
511
17.7k
      node_index += step;
512
17.7k
      node_index &= hash_table->mask;
513
17.7k
      node_hash = hash_table->hashes[node_index];
514
17.7k
    }
515
516
120k
  if (have_tombstone)
517
0
    return first_tombstone;
518
519
120k
  return node_index;
520
120k
}
521
522
/*
523
 * g_hash_table_remove_node:
524
 * @hash_table: our #GHashTable
525
 * @node: pointer to node to remove
526
 * @notify: %TRUE if the destroy notify handlers are to be called
527
 *
528
 * Removes a node from the hash table and updates the node count.
529
 * The node is replaced by a tombstone. No table resize is performed.
530
 *
531
 * If @notify is %TRUE then the destroy notify functions are called
532
 * for the key and value of the hash node.
533
 */
534
static void
535
g_hash_table_remove_node (GHashTable   *hash_table,
536
                          gint          i,
537
                          gboolean      notify)
538
5.25k
{
539
5.25k
  gpointer key;
540
5.25k
  gpointer value;
541
542
5.25k
  key = g_hash_table_fetch_key_or_value (hash_table->keys, i, hash_table->have_big_keys);
543
5.25k
  value = g_hash_table_fetch_key_or_value (hash_table->values, i, hash_table->have_big_values);
544
545
  /* Erect tombstone */
546
5.25k
  hash_table->hashes[i] = TOMBSTONE_HASH_VALUE;
547
548
  /* Be GC friendly */
549
5.25k
  g_hash_table_assign_key_or_value (hash_table->keys, i, hash_table->have_big_keys, NULL);
550
5.25k
  g_hash_table_assign_key_or_value (hash_table->values, i, hash_table->have_big_values, NULL);
551
552
5.25k
  g_assert (hash_table->nnodes > 0);
553
5.25k
  hash_table->nnodes--;
554
555
5.25k
  if (notify && hash_table->key_destroy_func)
556
0
    hash_table->key_destroy_func (key);
557
558
5.25k
  if (notify && hash_table->value_destroy_func)
559
0
    hash_table->value_destroy_func (value);
560
561
5.25k
}
562
563
/*
564
 * g_hash_table_setup_storage:
565
 * @hash_table: our #GHashTable
566
 *
567
 * Initialise the hash table size, mask, mod, and arrays.
568
 */
569
static void
570
g_hash_table_setup_storage (GHashTable *hash_table)
571
10.3k
{
572
10.3k
  gboolean small = FALSE;
573
574
  /* We want to use small arrays only if:
575
   *   - we are running on a system where that makes sense (64 bit); and
576
   *   - we are not running under valgrind.
577
   */
578
579
10.3k
#ifdef USE_SMALL_ARRAYS
580
10.3k
  small = TRUE;
581
582
10.3k
# ifdef ENABLE_VALGRIND
583
10.3k
  if (RUNNING_ON_VALGRIND)
584
0
    small = FALSE;
585
10.3k
# endif
586
10.3k
#endif
587
588
10.3k
  g_hash_table_set_shift (hash_table, HASH_TABLE_MIN_SHIFT);
589
590
10.3k
  hash_table->have_big_keys = !small;
591
10.3k
  hash_table->have_big_values = !small;
592
593
10.3k
  hash_table->keys   = g_hash_table_realloc_key_or_value_array (NULL, hash_table->size, hash_table->have_big_keys);
594
10.3k
  hash_table->values = hash_table->keys;
595
10.3k
  hash_table->hashes = g_new0 (guint, hash_table->size);
596
10.3k
}
597
598
/*
599
 * g_hash_table_remove_all_nodes:
600
 * @hash_table: our #GHashTable
601
 * @notify: %TRUE if the destroy notify handlers are to be called
602
 *
603
 * Removes all nodes from the table.
604
 *
605
 * If @notify is %TRUE then the destroy notify functions are called
606
 * for the key and value of the hash node.
607
 *
608
 * Since this may be a precursor to freeing the table entirely, we'd
609
 * ideally perform no resize, and we can indeed avoid that in some
610
 * cases.  However: in the case that we'll be making callbacks to user
611
 * code (via destroy notifies) we need to consider that the user code
612
 * might call back into the table again.  In this case, we setup a new
613
 * set of arrays so that any callers will see an empty (but valid)
614
 * table.
615
 */
616
static void
617
g_hash_table_remove_all_nodes (GHashTable *hash_table,
618
                               gboolean    notify,
619
                               gboolean    destruction)
620
22.2k
{
621
22.2k
  int i;
622
22.2k
  gpointer key;
623
22.2k
  gpointer value;
624
22.2k
  gint old_size;
625
22.2k
  gpointer *old_keys;
626
22.2k
  gpointer *old_values;
627
22.2k
  guint    *old_hashes;
628
22.2k
  gboolean  old_have_big_keys;
629
22.2k
  gboolean  old_have_big_values;
630
631
  /* If the hash table is already empty, there is nothing to be done. */
632
22.2k
  if (hash_table->nnodes == 0)
633
16.8k
    return;
634
635
5.34k
  hash_table->nnodes = 0;
636
5.34k
  hash_table->noccupied = 0;
637
638
  /* Easy case: no callbacks, so we just zero out the arrays */
639
5.34k
  if (!notify ||
640
5.34k
      (hash_table->key_destroy_func == NULL &&
641
5.34k
       hash_table->value_destroy_func == NULL))
642
5.23k
    {
643
5.23k
      if (!destruction)
644
5.23k
        {
645
5.23k
          memset (hash_table->hashes, 0, hash_table->size * sizeof (guint));
646
647
5.23k
#ifdef USE_SMALL_ARRAYS
648
5.23k
          memset (hash_table->keys, 0, hash_table->size * (hash_table->have_big_keys ? BIG_ENTRY_SIZE : SMALL_ENTRY_SIZE));
649
5.23k
          memset (hash_table->values, 0, hash_table->size * (hash_table->have_big_values ? BIG_ENTRY_SIZE : SMALL_ENTRY_SIZE));
650
#else
651
          memset (hash_table->keys, 0, hash_table->size * sizeof (gpointer));
652
          memset (hash_table->values, 0, hash_table->size * sizeof (gpointer));
653
#endif
654
5.23k
        }
655
656
5.23k
      return;
657
5.23k
    }
658
659
  /* Hard case: we need to do user callbacks.  There are two
660
   * possibilities here:
661
   *
662
   *   1) there are no outstanding references on the table and therefore
663
   *   nobody should be calling into it again (destroying == true)
664
   *
665
   *   2) there are outstanding references, and there may be future
666
   *   calls into the table, either after we return, or from the destroy
667
   *   notifies that we're about to do (destroying == false)
668
   *
669
   * We handle both cases by taking the current state of the table into
670
   * local variables and replacing it with something else: in the "no
671
   * outstanding references" cases we replace it with a bunch of
672
   * null/zero values so that any access to the table will fail.  In the
673
   * "may receive future calls" case, we reinitialise the struct to
674
   * appear like a newly-created empty table.
675
   *
676
   * In both cases, we take over the references for the current state,
677
   * freeing them below.
678
   */
679
103
  old_size = hash_table->size;
680
103
  old_have_big_keys = hash_table->have_big_keys;
681
103
  old_have_big_values = hash_table->have_big_values;
682
103
  old_keys   = g_steal_pointer (&hash_table->keys);
683
103
  old_values = g_steal_pointer (&hash_table->values);
684
103
  old_hashes = g_steal_pointer (&hash_table->hashes);
685
686
103
  if (!destruction)
687
    /* Any accesses will see an empty table */
688
103
    g_hash_table_setup_storage (hash_table);
689
0
  else
690
    /* Will cause a quick crash on any attempted access */
691
0
    hash_table->size = hash_table->mod = hash_table->mask = 0;
692
693
  /* Now do the actual destroy notifies */
694
927
  for (i = 0; i < old_size; i++)
695
824
    {
696
824
      if (HASH_IS_REAL (old_hashes[i]))
697
103
        {
698
103
          key = g_hash_table_fetch_key_or_value (old_keys, i, old_have_big_keys);
699
103
          value = g_hash_table_fetch_key_or_value (old_values, i, old_have_big_values);
700
701
103
          old_hashes[i] = UNUSED_HASH_VALUE;
702
703
103
          g_hash_table_assign_key_or_value (old_keys, i, old_have_big_keys, NULL);
704
103
          g_hash_table_assign_key_or_value (old_values, i, old_have_big_values, NULL);
705
706
103
          if (hash_table->key_destroy_func != NULL)
707
0
            hash_table->key_destroy_func (key);
708
709
103
          if (hash_table->value_destroy_func != NULL)
710
103
            hash_table->value_destroy_func (value);
711
103
        }
712
824
    }
713
714
  /* Destroy old storage space. */
715
103
  if (old_keys != old_values)
716
103
    g_free (old_values);
717
718
103
  g_free (old_keys);
719
103
  g_free (old_hashes);
720
103
}
721
722
static void
723
realloc_arrays (GHashTable *hash_table, gboolean is_a_set)
724
26
{
725
26
  hash_table->hashes = g_renew (guint, hash_table->hashes, hash_table->size);
726
26
  hash_table->keys = g_hash_table_realloc_key_or_value_array (hash_table->keys, hash_table->size, hash_table->have_big_keys);
727
728
26
  if (is_a_set)
729
0
    hash_table->values = hash_table->keys;
730
26
  else
731
26
    hash_table->values = g_hash_table_realloc_key_or_value_array (hash_table->values, hash_table->size, hash_table->have_big_values);
732
26
}
733
734
/* When resizing the table in place, we use a temporary bit array to keep
735
 * track of which entries have been assigned a proper location in the new
736
 * table layout.
737
 *
738
 * Each bit corresponds to a bucket. A bit is set if an entry was assigned
739
 * its corresponding location during the resize and thus should not be
740
 * evicted. The array starts out cleared to zero. */
741
742
static inline gboolean
743
get_status_bit (const guint32 *bitmap, guint index)
744
1.45k
{
745
1.45k
  return (bitmap[index / 32] >> (index % 32)) & 1;
746
1.45k
}
747
748
static inline void
749
set_status_bit (guint32 *bitmap, guint index)
750
562
{
751
562
  bitmap[index / 32] |= 1U << (index % 32);
752
562
}
753
754
/* By calling dedicated resize functions for sets and maps, we avoid 2x
755
 * test-and-branch per key in the inner loop. This yields a small
756
 * performance improvement at the cost of a bit of macro gunk. */
757
758
#define DEFINE_RESIZE_FUNC(fname) \
759
26
static void fname (GHashTable *hash_table, guint old_size, guint32 *reallocated_buckets_bitmap) \
760
26
{                                                                       \
761
26
  guint i;                                                              \
762
26
                                                                        \
763
602
  for (i = 0; i < old_size; i++)                                        \
764
576
    {                                                                   \
765
576
      guint node_hash = hash_table->hashes[i];                          \
766
576
      gpointer key, value G_GNUC_UNUSED;                                \
767
576
                                                                        \
768
576
      if (!HASH_IS_REAL (node_hash))                                    \
769
576
        {                                                               \
770
12
          /* Clear tombstones */                                        \
771
12
          hash_table->hashes[i] = UNUSED_HASH_VALUE;                    \
772
12
          continue;                                                     \
773
12
        }                                                               \
774
576
                                                                        \
775
576
      /* Skip entries relocated through eviction */                     \
776
576
      if (get_status_bit (reallocated_buckets_bitmap, i))               \
777
564
        continue;                                                       \
778
564
                                                                        \
779
564
      hash_table->hashes[i] = UNUSED_HASH_VALUE;                        \
780
405
      EVICT_KEYVAL (hash_table, i, NULL, NULL, key, value);             \
781
405
                                                                        \
782
405
      for (;;)                                                          \
783
562
        {                                                               \
784
562
          guint hash_val;                                               \
785
562
          guint replaced_hash;                                          \
786
562
          guint step = 0;                                               \
787
562
                                                                        \
788
562
          hash_val = g_hash_table_hash_to_index (hash_table, node_hash); \
789
562
                                                                        \
790
889
          while (get_status_bit (reallocated_buckets_bitmap, hash_val)) \
791
562
            {                                                           \
792
327
              step++;                                                   \
793
327
              hash_val += step;                                         \
794
327
              hash_val &= hash_table->mask;                             \
795
327
            }                                                           \
796
562
                                                                        \
797
562
          set_status_bit (reallocated_buckets_bitmap, hash_val);        \
798
562
                                                                        \
799
562
          replaced_hash = hash_table->hashes[hash_val];                 \
800
562
          hash_table->hashes[hash_val] = node_hash;                     \
801
562
          if (!HASH_IS_REAL (replaced_hash))                            \
802
562
            {                                                           \
803
405
              ASSIGN_KEYVAL (hash_table, hash_val, key, value);         \
804
405
              break;                                                    \
805
405
            }                                                           \
806
562
                                                                        \
807
562
          node_hash = replaced_hash;                                    \
808
157
          EVICT_KEYVAL (hash_table, hash_val, key, value, key, value);  \
809
157
        }                                                               \
810
405
    }                                                                   \
811
26
}
Unexecuted instantiation: ghash.c:resize_set
ghash.c:resize_map
Line
Count
Source
759
26
static void fname (GHashTable *hash_table, guint old_size, guint32 *reallocated_buckets_bitmap) \
760
26
{                                                                       \
761
26
  guint i;                                                              \
762
26
                                                                        \
763
602
  for (i = 0; i < old_size; i++)                                        \
764
576
    {                                                                   \
765
576
      guint node_hash = hash_table->hashes[i];                          \
766
576
      gpointer key, value G_GNUC_UNUSED;                                \
767
576
                                                                        \
768
576
      if (!HASH_IS_REAL (node_hash))                                    \
769
576
        {                                                               \
770
12
          /* Clear tombstones */                                        \
771
12
          hash_table->hashes[i] = UNUSED_HASH_VALUE;                    \
772
12
          continue;                                                     \
773
12
        }                                                               \
774
576
                                                                        \
775
576
      /* Skip entries relocated through eviction */                     \
776
576
      if (get_status_bit (reallocated_buckets_bitmap, i))               \
777
564
        continue;                                                       \
778
564
                                                                        \
779
564
      hash_table->hashes[i] = UNUSED_HASH_VALUE;                        \
780
405
      EVICT_KEYVAL (hash_table, i, NULL, NULL, key, value);             \
781
405
                                                                        \
782
405
      for (;;)                                                          \
783
562
        {                                                               \
784
562
          guint hash_val;                                               \
785
562
          guint replaced_hash;                                          \
786
562
          guint step = 0;                                               \
787
562
                                                                        \
788
562
          hash_val = g_hash_table_hash_to_index (hash_table, node_hash); \
789
562
                                                                        \
790
889
          while (get_status_bit (reallocated_buckets_bitmap, hash_val)) \
791
562
            {                                                           \
792
327
              step++;                                                   \
793
327
              hash_val += step;                                         \
794
327
              hash_val &= hash_table->mask;                             \
795
327
            }                                                           \
796
562
                                                                        \
797
562
          set_status_bit (reallocated_buckets_bitmap, hash_val);        \
798
562
                                                                        \
799
562
          replaced_hash = hash_table->hashes[hash_val];                 \
800
562
          hash_table->hashes[hash_val] = node_hash;                     \
801
562
          if (!HASH_IS_REAL (replaced_hash))                            \
802
562
            {                                                           \
803
405
              ASSIGN_KEYVAL (hash_table, hash_val, key, value);         \
804
405
              break;                                                    \
805
405
            }                                                           \
806
562
                                                                        \
807
562
          node_hash = replaced_hash;                                    \
808
157
          EVICT_KEYVAL (hash_table, hash_val, key, value, key, value);  \
809
157
        }                                                               \
810
405
    }                                                                   \
811
26
}
812
813
405
#define ASSIGN_KEYVAL(ht, index, key, value) G_STMT_START{ \
814
405
    g_hash_table_assign_key_or_value ((ht)->keys, (index), (ht)->have_big_keys, (key)); \
815
405
    g_hash_table_assign_key_or_value ((ht)->values, (index), (ht)->have_big_values, (value)); \
816
405
  }G_STMT_END
817
818
562
#define EVICT_KEYVAL(ht, index, key, value, outkey, outvalue) G_STMT_START{ \
819
562
    (outkey) = g_hash_table_evict_key_or_value ((ht)->keys, (index), (ht)->have_big_keys, (key)); \
820
562
    (outvalue) = g_hash_table_evict_key_or_value ((ht)->values, (index), (ht)->have_big_values, (value)); \
821
562
  }G_STMT_END
822
823
DEFINE_RESIZE_FUNC (resize_map)
824
825
#undef ASSIGN_KEYVAL
826
#undef EVICT_KEYVAL
827
828
0
#define ASSIGN_KEYVAL(ht, index, key, value) G_STMT_START{ \
829
0
    g_hash_table_assign_key_or_value ((ht)->keys, (index), (ht)->have_big_keys, (key)); \
830
0
  }G_STMT_END
831
832
0
#define EVICT_KEYVAL(ht, index, key, value, outkey, outvalue) G_STMT_START{ \
833
0
    (outkey) = g_hash_table_evict_key_or_value ((ht)->keys, (index), (ht)->have_big_keys, (key)); \
834
0
  }G_STMT_END
835
836
DEFINE_RESIZE_FUNC (resize_set)
837
838
#undef ASSIGN_KEYVAL
839
#undef EVICT_KEYVAL
840
841
/*
842
 * g_hash_table_resize:
843
 * @hash_table: our #GHashTable
844
 *
845
 * Resizes the hash table to the optimal size based on the number of
846
 * nodes currently held. If you call this function then a resize will
847
 * occur, even if one does not need to occur.
848
 * Use g_hash_table_maybe_resize() instead.
849
 *
850
 * This function may "resize" the hash table to its current size, with
851
 * the side effect of cleaning up tombstones and otherwise optimizing
852
 * the probe sequences.
853
 */
854
static void
855
g_hash_table_resize (GHashTable *hash_table)
856
26
{
857
26
  guint32 *reallocated_buckets_bitmap;
858
26
  gsize old_size;
859
26
  gboolean is_a_set;
860
861
26
  old_size = hash_table->size;
862
26
  is_a_set = hash_table->keys == hash_table->values;
863
864
  /* The outer checks in g_hash_table_maybe_resize() will only consider
865
   * cleanup/resize when the load factor goes below .25 (1/4, ignoring
866
   * tombstones) or above .9375 (15/16, including tombstones).
867
   *
868
   * Once this happens, tombstones will always be cleaned out. If our
869
   * load sans tombstones is greater than .75 (1/1.333, see below), we'll
870
   * take this opportunity to grow the table too.
871
   *
872
   * Immediately after growing, the load factor will be in the range
873
   * .375 .. .469. After shrinking, it will be exactly .5. */
874
875
26
  g_hash_table_set_shift_from_size (hash_table, hash_table->nnodes * 1.333);
876
877
26
  if (hash_table->size > old_size)
878
26
    {
879
26
      realloc_arrays (hash_table, is_a_set);
880
26
      memset (&hash_table->hashes[old_size], 0, (hash_table->size - old_size) * sizeof (guint));
881
882
26
      reallocated_buckets_bitmap = g_new0 (guint32, (hash_table->size + 31) / 32);
883
26
    }
884
0
  else
885
0
    {
886
0
      reallocated_buckets_bitmap = g_new0 (guint32, (old_size + 31) / 32);
887
0
    }
888
889
26
  if (is_a_set)
890
0
    resize_set (hash_table, old_size, reallocated_buckets_bitmap);
891
26
  else
892
26
    resize_map (hash_table, old_size, reallocated_buckets_bitmap);
893
894
26
  g_free (reallocated_buckets_bitmap);
895
896
26
  if (hash_table->size < old_size)
897
0
    realloc_arrays (hash_table, is_a_set);
898
899
26
  hash_table->noccupied = hash_table->nnodes;
900
26
}
901
902
/*
903
 * g_hash_table_maybe_resize:
904
 * @hash_table: our #GHashTable
905
 *
906
 * Resizes the hash table, if needed.
907
 *
908
 * Essentially, calls g_hash_table_resize() if the table has strayed
909
 * too far from its ideal size for its number of nodes.
910
 */
911
static inline void
912
g_hash_table_maybe_resize (GHashTable *hash_table)
913
31.3k
{
914
31.3k
  gsize noccupied = hash_table->noccupied;
915
31.3k
  gsize size = hash_table->size;
916
917
31.3k
  if ((size > hash_table->nnodes * 4 && size > 1 << HASH_TABLE_MIN_SHIFT) ||
918
31.3k
      (size <= noccupied + (noccupied / 16)))
919
26
    g_hash_table_resize (hash_table);
920
31.3k
}
921
922
#ifdef USE_SMALL_ARRAYS
923
924
static inline gboolean
925
entry_is_big (gpointer v)
926
17.4k
{
927
17.4k
  return (((guintptr) v) >> ((BIG_ENTRY_SIZE - SMALL_ENTRY_SIZE) * 8)) != 0;
928
17.4k
}
929
930
static inline gboolean
931
g_hash_table_maybe_make_big_keys_or_values (gpointer *a_p, gpointer v, gint ht_size)
932
17.4k
{
933
17.4k
  if (entry_is_big (v))
934
17.1k
    {
935
17.1k
      guint *a = (guint *) *a_p;
936
17.1k
      gpointer *a_new;
937
17.1k
      gint i;
938
939
17.1k
      a_new = g_new (gpointer, ht_size);
940
941
154k
      for (i = 0; i < ht_size; i++)
942
137k
        {
943
137k
          a_new[i] = GUINT_TO_POINTER (a[i]);
944
137k
        }
945
946
17.1k
      g_free (a);
947
17.1k
      *a_p = a_new;
948
17.1k
      return TRUE;
949
17.1k
    }
950
951
240
  return FALSE;
952
17.4k
}
953
954
#endif
955
956
static inline void
957
g_hash_table_ensure_keyval_fits (GHashTable *hash_table, gpointer key, gpointer value)
958
14.0k
{
959
14.0k
  gboolean is_a_set = (hash_table->keys == hash_table->values);
960
961
14.0k
#ifdef USE_SMALL_ARRAYS
962
963
  /* Convert from set to map? */
964
14.0k
  if (is_a_set)
965
8.60k
    {
966
8.60k
      if (hash_table->have_big_keys)
967
6
        {
968
6
          if (key != value)
969
0
            hash_table->values = g_memdup2 (hash_table->keys, sizeof (gpointer) * hash_table->size);
970
          /* Keys and values are both big now, so no need for further checks */
971
6
          return;
972
6
        }
973
8.59k
      else
974
8.59k
        {
975
8.59k
          if (key != value)
976
8.59k
            {
977
8.59k
              hash_table->values = g_memdup2 (hash_table->keys, sizeof (guint) * hash_table->size);
978
8.59k
              is_a_set = FALSE;
979
8.59k
            }
980
8.59k
        }
981
8.60k
    }
982
983
  /* Make keys big? */
984
14.0k
  if (!hash_table->have_big_keys)
985
8.59k
    {
986
8.59k
      hash_table->have_big_keys = g_hash_table_maybe_make_big_keys_or_values (&hash_table->keys, key, hash_table->size);
987
988
8.59k
      if (is_a_set)
989
2
        {
990
2
          hash_table->values = hash_table->keys;
991
2
          hash_table->have_big_values = hash_table->have_big_keys;
992
2
        }
993
8.59k
    }
994
995
  /* Make values big? */
996
14.0k
  if (!is_a_set && !hash_table->have_big_values)
997
8.82k
    {
998
8.82k
      hash_table->have_big_values = g_hash_table_maybe_make_big_keys_or_values (&hash_table->values, value, hash_table->size);
999
8.82k
    }
1000
1001
#else
1002
1003
  /* Just split if necessary */
1004
  if (is_a_set && key != value)
1005
    hash_table->values = g_memdup2 (hash_table->keys, sizeof (gpointer) * hash_table->size);
1006
1007
#endif
1008
14.0k
}
1009
1010
/**
1011
 * g_hash_table_new:
1012
 * @hash_func: a function to create a hash value from a key
1013
 * @key_equal_func: a function to check two keys for equality
1014
 *
1015
 * Creates a new #GHashTable with a reference count of 1.
1016
 *
1017
 * Hash values returned by @hash_func are used to determine where keys
1018
 * are stored within the #GHashTable data structure. The g_direct_hash(),
1019
 * g_int_hash(), g_int64_hash(), g_double_hash() and g_str_hash()
1020
 * functions are provided for some common types of keys.
1021
 * If @hash_func is %NULL, g_direct_hash() is used.
1022
 *
1023
 * @key_equal_func is used when looking up keys in the #GHashTable.
1024
 * The g_direct_equal(), g_int_equal(), g_int64_equal(), g_double_equal()
1025
 * and g_str_equal() functions are provided for the most common types
1026
 * of keys. If @key_equal_func is %NULL, keys are compared directly in
1027
 * a similar fashion to g_direct_equal(), but without the overhead of
1028
 * a function call. @key_equal_func is called with the key from the hash table
1029
 * as its first parameter, and the user-provided key to check against as
1030
 * its second.
1031
 *
1032
 * Returns: a new #GHashTable
1033
 */
1034
GHashTable *
1035
g_hash_table_new (GHashFunc  hash_func,
1036
                  GEqualFunc key_equal_func)
1037
8.51k
{
1038
8.51k
  return g_hash_table_new_full (hash_func, key_equal_func, NULL, NULL);
1039
8.51k
}
1040
1041
1042
/**
1043
 * g_hash_table_new_full:
1044
 * @hash_func: a function to create a hash value from a key
1045
 * @key_equal_func: a function to check two keys for equality
1046
 * @key_destroy_func: (nullable): a function to free the memory allocated for the key
1047
 *     used when removing the entry from the #GHashTable, or %NULL
1048
 *     if you don't want to supply such a function.
1049
 * @value_destroy_func: (nullable): a function to free the memory allocated for the
1050
 *     value used when removing the entry from the #GHashTable, or %NULL
1051
 *     if you don't want to supply such a function.
1052
 *
1053
 * Creates a new #GHashTable like g_hash_table_new() with a reference
1054
 * count of 1 and allows to specify functions to free the memory
1055
 * allocated for the key and value that get called when removing the
1056
 * entry from the #GHashTable.
1057
 *
1058
 * Since version 2.42 it is permissible for destroy notify functions to
1059
 * recursively remove further items from the hash table. This is only
1060
 * permissible if the application still holds a reference to the hash table.
1061
 * This means that you may need to ensure that the hash table is empty by
1062
 * calling g_hash_table_remove_all() before releasing the last reference using
1063
 * g_hash_table_unref().
1064
 *
1065
 * Returns: a new #GHashTable
1066
 */
1067
GHashTable *
1068
g_hash_table_new_full (GHashFunc      hash_func,
1069
                       GEqualFunc     key_equal_func,
1070
                       GDestroyNotify key_destroy_func,
1071
                       GDestroyNotify value_destroy_func)
1072
10.2k
{
1073
10.2k
  GHashTable *hash_table;
1074
1075
10.2k
  hash_table = g_slice_new (GHashTable);
1076
10.2k
  g_atomic_ref_count_init (&hash_table->ref_count);
1077
10.2k
  hash_table->nnodes             = 0;
1078
10.2k
  hash_table->noccupied          = 0;
1079
10.2k
  hash_table->hash_func          = hash_func ? hash_func : g_direct_hash;
1080
10.2k
  hash_table->key_equal_func     = key_equal_func;
1081
10.2k
#ifndef G_DISABLE_ASSERT
1082
10.2k
  hash_table->version            = 0;
1083
10.2k
#endif
1084
10.2k
  hash_table->key_destroy_func   = key_destroy_func;
1085
10.2k
  hash_table->value_destroy_func = value_destroy_func;
1086
1087
10.2k
  g_hash_table_setup_storage (hash_table);
1088
1089
10.2k
  return hash_table;
1090
10.2k
}
1091
1092
/**
1093
 * g_hash_table_new_similar:
1094
 * @other_hash_table: (not nullable) (transfer none): Another #GHashTable
1095
 *
1096
 * Creates a new #GHashTable like g_hash_table_new_full() with a reference
1097
 * count of 1.
1098
 *
1099
 * It inherits the hash function, the key equal function, the key destroy function,
1100
 * as well as the value destroy function, from @other_hash_table.
1101
 *
1102
 * The returned hash table will be empty; it will not contain the keys
1103
 * or values from @other_hash_table.
1104
 *
1105
 * Returns: (transfer full) (not nullable): a new #GHashTable
1106
 * Since: 2.72
1107
 */
1108
GHashTable *
1109
g_hash_table_new_similar (GHashTable *other_hash_table)
1110
0
{
1111
0
  g_return_val_if_fail (other_hash_table, NULL);
1112
1113
0
  return g_hash_table_new_full (other_hash_table->hash_func,
1114
0
                                other_hash_table->key_equal_func,
1115
0
                                other_hash_table->key_destroy_func,
1116
0
                                other_hash_table->value_destroy_func);
1117
0
}
1118
1119
/**
1120
 * g_hash_table_iter_init:
1121
 * @iter: an uninitialized #GHashTableIter
1122
 * @hash_table: a #GHashTable
1123
 *
1124
 * Initializes a key/value pair iterator and associates it with
1125
 * @hash_table. Modifying the hash table after calling this function
1126
 * invalidates the returned iterator.
1127
 *
1128
 * The iteration order of a #GHashTableIter over the keys/values in a hash
1129
 * table is not defined.
1130
 *
1131
 * |[<!-- language="C" -->
1132
 * GHashTableIter iter;
1133
 * gpointer key, value;
1134
 *
1135
 * g_hash_table_iter_init (&iter, hash_table);
1136
 * while (g_hash_table_iter_next (&iter, &key, &value))
1137
 *   {
1138
 *     // do something with key and value
1139
 *   }
1140
 * ]|
1141
 *
1142
 * Since: 2.16
1143
 */
1144
void
1145
g_hash_table_iter_init (GHashTableIter *iter,
1146
                        GHashTable     *hash_table)
1147
0
{
1148
0
  RealIter *ri = (RealIter *) iter;
1149
1150
0
  g_return_if_fail (iter != NULL);
1151
0
  g_return_if_fail (hash_table != NULL);
1152
1153
0
  ri->hash_table = hash_table;
1154
0
  ri->position = -1;
1155
0
#ifndef G_DISABLE_ASSERT
1156
0
  ri->version = hash_table->version;
1157
0
#endif
1158
0
}
1159
1160
/**
1161
 * g_hash_table_iter_next:
1162
 * @iter: an initialized #GHashTableIter
1163
 * @key: (out) (optional): a location to store the key
1164
 * @value: (out) (optional) (nullable): a location to store the value
1165
 *
1166
 * Advances @iter and retrieves the key and/or value that are now
1167
 * pointed to as a result of this advancement. If %FALSE is returned,
1168
 * @key and @value are not set, and the iterator becomes invalid.
1169
 *
1170
 * Returns: %FALSE if the end of the #GHashTable has been reached.
1171
 *
1172
 * Since: 2.16
1173
 */
1174
gboolean
1175
g_hash_table_iter_next (GHashTableIter *iter,
1176
                        gpointer       *key,
1177
                        gpointer       *value)
1178
0
{
1179
0
  RealIter *ri = (RealIter *) iter;
1180
0
  gint position;
1181
1182
0
  g_return_val_if_fail (iter != NULL, FALSE);
1183
0
#ifndef G_DISABLE_ASSERT
1184
0
  g_return_val_if_fail (ri->version == ri->hash_table->version, FALSE);
1185
0
#endif
1186
0
  g_return_val_if_fail (ri->position < (gssize) ri->hash_table->size, FALSE);
1187
1188
0
  position = ri->position;
1189
1190
0
  do
1191
0
    {
1192
0
      position++;
1193
0
      if (position >= (gssize) ri->hash_table->size)
1194
0
        {
1195
0
          ri->position = position;
1196
0
          return FALSE;
1197
0
        }
1198
0
    }
1199
0
  while (!HASH_IS_REAL (ri->hash_table->hashes[position]));
1200
1201
0
  if (key != NULL)
1202
0
    *key = g_hash_table_fetch_key_or_value (ri->hash_table->keys, position, ri->hash_table->have_big_keys);
1203
0
  if (value != NULL)
1204
0
    *value = g_hash_table_fetch_key_or_value (ri->hash_table->values, position, ri->hash_table->have_big_values);
1205
1206
0
  ri->position = position;
1207
0
  return TRUE;
1208
0
}
1209
1210
/**
1211
 * g_hash_table_iter_get_hash_table:
1212
 * @iter: an initialized #GHashTableIter
1213
 *
1214
 * Returns the #GHashTable associated with @iter.
1215
 *
1216
 * Returns: the #GHashTable associated with @iter.
1217
 *
1218
 * Since: 2.16
1219
 */
1220
GHashTable *
1221
g_hash_table_iter_get_hash_table (GHashTableIter *iter)
1222
0
{
1223
0
  g_return_val_if_fail (iter != NULL, NULL);
1224
1225
0
  return ((RealIter *) iter)->hash_table;
1226
0
}
1227
1228
static void
1229
iter_remove_or_steal (RealIter *ri, gboolean notify)
1230
0
{
1231
0
  g_return_if_fail (ri != NULL);
1232
0
#ifndef G_DISABLE_ASSERT
1233
0
  g_return_if_fail (ri->version == ri->hash_table->version);
1234
0
#endif
1235
0
  g_return_if_fail (ri->position >= 0);
1236
0
  g_return_if_fail ((gsize) ri->position < ri->hash_table->size);
1237
1238
0
  g_hash_table_remove_node (ri->hash_table, ri->position, notify);
1239
1240
0
#ifndef G_DISABLE_ASSERT
1241
0
  ri->version++;
1242
0
  ri->hash_table->version++;
1243
0
#endif
1244
0
}
1245
1246
/**
1247
 * g_hash_table_iter_remove:
1248
 * @iter: an initialized #GHashTableIter
1249
 *
1250
 * Removes the key/value pair currently pointed to by the iterator
1251
 * from its associated #GHashTable. Can only be called after
1252
 * g_hash_table_iter_next() returned %TRUE, and cannot be called
1253
 * more than once for the same key/value pair.
1254
 *
1255
 * If the #GHashTable was created using g_hash_table_new_full(),
1256
 * the key and value are freed using the supplied destroy functions,
1257
 * otherwise you have to make sure that any dynamically allocated
1258
 * values are freed yourself.
1259
 *
1260
 * It is safe to continue iterating the #GHashTable afterward:
1261
 * |[<!-- language="C" -->
1262
 * while (g_hash_table_iter_next (&iter, &key, &value))
1263
 *   {
1264
 *     if (condition)
1265
 *       g_hash_table_iter_remove (&iter);
1266
 *   }
1267
 * ]|
1268
 *
1269
 * Since: 2.16
1270
 */
1271
void
1272
g_hash_table_iter_remove (GHashTableIter *iter)
1273
0
{
1274
0
  iter_remove_or_steal ((RealIter *) iter, TRUE);
1275
0
}
1276
1277
/*
1278
 * g_hash_table_insert_node:
1279
 * @hash_table: our #GHashTable
1280
 * @node_index: pointer to node to insert/replace
1281
 * @key_hash: key hash
1282
 * @key: (nullable): key to replace with, or %NULL
1283
 * @value: value to replace with
1284
 * @keep_new_key: whether to replace the key in the node with @key
1285
 * @reusing_key: whether @key was taken out of the existing node
1286
 *
1287
 * Inserts a value at @node_index in the hash table and updates it.
1288
 *
1289
 * If @key has been taken out of the existing node (ie it is not
1290
 * passed in via a g_hash_table_insert/replace) call, then @reusing_key
1291
 * should be %TRUE.
1292
 *
1293
 * Returns: %TRUE if the key did not exist yet
1294
 */
1295
static gboolean
1296
g_hash_table_insert_node (GHashTable *hash_table,
1297
                          guint       node_index,
1298
                          guint       key_hash,
1299
                          gpointer    new_key,
1300
                          gpointer    new_value,
1301
                          gboolean    keep_new_key,
1302
                          gboolean    reusing_key)
1303
14.0k
{
1304
14.0k
  gboolean already_exists;
1305
14.0k
  guint old_hash;
1306
14.0k
  gpointer key_to_free = NULL;
1307
14.0k
  gpointer key_to_keep = NULL;
1308
14.0k
  gpointer value_to_free = NULL;
1309
1310
14.0k
  old_hash = hash_table->hashes[node_index];
1311
14.0k
  already_exists = HASH_IS_REAL (old_hash);
1312
1313
  /* Proceed in three steps.  First, deal with the key because it is the
1314
   * most complicated.  Then consider if we need to split the table in
1315
   * two (because writing the value will result in the set invariant
1316
   * becoming broken).  Then deal with the value.
1317
   *
1318
   * There are three cases for the key:
1319
   *
1320
   *  - entry already exists in table, reusing key:
1321
   *    free the just-passed-in new_key and use the existing value
1322
   *
1323
   *  - entry already exists in table, not reusing key:
1324
   *    free the entry in the table, use the new key
1325
   *
1326
   *  - entry not already in table:
1327
   *    use the new key, free nothing
1328
   *
1329
   * We update the hash at the same time...
1330
   */
1331
14.0k
  if (already_exists)
1332
0
    {
1333
      /* Note: we must record the old value before writing the new key
1334
       * because we might change the value in the event that the two
1335
       * arrays are shared.
1336
       */
1337
0
      value_to_free = g_hash_table_fetch_key_or_value (hash_table->values, node_index, hash_table->have_big_values);
1338
1339
0
      if (keep_new_key)
1340
0
        {
1341
0
          key_to_free = g_hash_table_fetch_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys);
1342
0
          key_to_keep = new_key;
1343
0
        }
1344
0
      else
1345
0
        {
1346
0
          key_to_free = new_key;
1347
0
          key_to_keep = g_hash_table_fetch_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys);
1348
0
        }
1349
0
    }
1350
14.0k
  else
1351
14.0k
    {
1352
14.0k
      hash_table->hashes[node_index] = key_hash;
1353
14.0k
      key_to_keep = new_key;
1354
14.0k
    }
1355
1356
  /* Resize key/value arrays and split table as necessary */
1357
14.0k
  g_hash_table_ensure_keyval_fits (hash_table, key_to_keep, new_value);
1358
14.0k
  g_hash_table_assign_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys, key_to_keep);
1359
1360
  /* Step 3: Actually do the write */
1361
14.0k
  g_hash_table_assign_key_or_value (hash_table->values, node_index, hash_table->have_big_values, new_value);
1362
1363
  /* Now, the bookkeeping... */
1364
14.0k
  if (!already_exists)
1365
14.0k
    {
1366
14.0k
      hash_table->nnodes++;
1367
1368
14.0k
      if (HASH_IS_UNUSED (old_hash))
1369
14.0k
        {
1370
          /* We replaced an empty node, and not a tombstone */
1371
14.0k
          hash_table->noccupied++;
1372
14.0k
          g_hash_table_maybe_resize (hash_table);
1373
14.0k
        }
1374
1375
14.0k
#ifndef G_DISABLE_ASSERT
1376
14.0k
      hash_table->version++;
1377
14.0k
#endif
1378
14.0k
    }
1379
1380
14.0k
  if (already_exists)
1381
0
    {
1382
0
      if (hash_table->key_destroy_func && !reusing_key)
1383
0
        (* hash_table->key_destroy_func) (key_to_free);
1384
0
      if (hash_table->value_destroy_func)
1385
0
        (* hash_table->value_destroy_func) (value_to_free);
1386
0
    }
1387
1388
14.0k
  return !already_exists;
1389
14.0k
}
1390
1391
/**
1392
 * g_hash_table_iter_replace:
1393
 * @iter: an initialized #GHashTableIter
1394
 * @value: the value to replace with
1395
 *
1396
 * Replaces the value currently pointed to by the iterator
1397
 * from its associated #GHashTable. Can only be called after
1398
 * g_hash_table_iter_next() returned %TRUE.
1399
 *
1400
 * If you supplied a @value_destroy_func when creating the
1401
 * #GHashTable, the old value is freed using that function.
1402
 *
1403
 * Since: 2.30
1404
 */
1405
void
1406
g_hash_table_iter_replace (GHashTableIter *iter,
1407
                           gpointer        value)
1408
0
{
1409
0
  RealIter *ri;
1410
0
  guint node_hash;
1411
0
  gpointer key;
1412
1413
0
  ri = (RealIter *) iter;
1414
1415
0
  g_return_if_fail (ri != NULL);
1416
0
#ifndef G_DISABLE_ASSERT
1417
0
  g_return_if_fail (ri->version == ri->hash_table->version);
1418
0
#endif
1419
0
  g_return_if_fail (ri->position >= 0);
1420
0
  g_return_if_fail ((gsize) ri->position < ri->hash_table->size);
1421
1422
0
  node_hash = ri->hash_table->hashes[ri->position];
1423
1424
0
  key = g_hash_table_fetch_key_or_value (ri->hash_table->keys, ri->position, ri->hash_table->have_big_keys);
1425
1426
0
  g_hash_table_insert_node (ri->hash_table, ri->position, node_hash, key, value, TRUE, TRUE);
1427
1428
0
#ifndef G_DISABLE_ASSERT
1429
0
  ri->version++;
1430
0
  ri->hash_table->version++;
1431
0
#endif
1432
0
}
1433
1434
/**
1435
 * g_hash_table_iter_steal:
1436
 * @iter: an initialized #GHashTableIter
1437
 *
1438
 * Removes the key/value pair currently pointed to by the
1439
 * iterator from its associated #GHashTable, without calling
1440
 * the key and value destroy functions. Can only be called
1441
 * after g_hash_table_iter_next() returned %TRUE, and cannot
1442
 * be called more than once for the same key/value pair.
1443
 *
1444
 * Since: 2.16
1445
 */
1446
void
1447
g_hash_table_iter_steal (GHashTableIter *iter)
1448
0
{
1449
0
  iter_remove_or_steal ((RealIter *) iter, FALSE);
1450
0
}
1451
1452
1453
/**
1454
 * g_hash_table_ref:
1455
 * @hash_table: a valid #GHashTable
1456
 *
1457
 * Atomically increments the reference count of @hash_table by one.
1458
 * This function is MT-safe and may be called from any thread.
1459
 *
1460
 * Returns: the passed in #GHashTable
1461
 *
1462
 * Since: 2.10
1463
 */
1464
GHashTable *
1465
g_hash_table_ref (GHashTable *hash_table)
1466
0
{
1467
0
  g_return_val_if_fail (hash_table != NULL, NULL);
1468
1469
0
  g_atomic_ref_count_inc (&hash_table->ref_count);
1470
1471
0
  return hash_table;
1472
0
}
1473
1474
/**
1475
 * g_hash_table_unref:
1476
 * @hash_table: a valid #GHashTable
1477
 *
1478
 * Atomically decrements the reference count of @hash_table by one.
1479
 * If the reference count drops to 0, all keys and values will be
1480
 * destroyed, and all memory allocated by the hash table is released.
1481
 * This function is MT-safe and may be called from any thread.
1482
 *
1483
 * Since: 2.10
1484
 */
1485
void
1486
g_hash_table_unref (GHashTable *hash_table)
1487
10.1k
{
1488
10.1k
  g_return_if_fail (hash_table != NULL);
1489
1490
10.1k
  if (g_atomic_ref_count_dec (&hash_table->ref_count))
1491
10.1k
    {
1492
10.1k
      g_hash_table_remove_all_nodes (hash_table, TRUE, TRUE);
1493
10.1k
      if (hash_table->keys != hash_table->values)
1494
8.48k
        g_free (hash_table->values);
1495
10.1k
      g_free (hash_table->keys);
1496
10.1k
      g_free (hash_table->hashes);
1497
10.1k
      g_slice_free (GHashTable, hash_table);
1498
10.1k
    }
1499
10.1k
}
1500
1501
/**
1502
 * g_hash_table_destroy:
1503
 * @hash_table: a #GHashTable
1504
 *
1505
 * Destroys all keys and values in the #GHashTable and decrements its
1506
 * reference count by 1. If keys and/or values are dynamically allocated,
1507
 * you should either free them first or create the #GHashTable with destroy
1508
 * notifiers using g_hash_table_new_full(). In the latter case the destroy
1509
 * functions you supplied will be called on all keys and values during the
1510
 * destruction phase.
1511
 */
1512
void
1513
g_hash_table_destroy (GHashTable *hash_table)
1514
9.33k
{
1515
9.33k
  g_return_if_fail (hash_table != NULL);
1516
1517
9.33k
  g_hash_table_remove_all (hash_table);
1518
9.33k
  g_hash_table_unref (hash_table);
1519
9.33k
}
1520
1521
/**
1522
 * g_hash_table_lookup:
1523
 * @hash_table: a #GHashTable
1524
 * @key: the key to look up
1525
 *
1526
 * Looks up a key in a #GHashTable. Note that this function cannot
1527
 * distinguish between a key that is not present and one which is present
1528
 * and has the value %NULL. If you need this distinction, use
1529
 * g_hash_table_lookup_extended().
1530
 *
1531
 * Returns: (nullable): the associated value, or %NULL if the key is not found
1532
 */
1533
gpointer
1534
g_hash_table_lookup (GHashTable    *hash_table,
1535
                     gconstpointer  key)
1536
142k
{
1537
142k
  guint node_index;
1538
142k
  guint node_hash;
1539
1540
142k
  g_return_val_if_fail (hash_table != NULL, NULL);
1541
1542
142k
  node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1543
1544
142k
  return HASH_IS_REAL (hash_table->hashes[node_index])
1545
142k
    ? g_hash_table_fetch_key_or_value (hash_table->values, node_index, hash_table->have_big_values)
1546
142k
    : NULL;
1547
142k
}
1548
1549
/**
1550
 * g_hash_table_lookup_extended:
1551
 * @hash_table: a #GHashTable
1552
 * @lookup_key: the key to look up
1553
 * @orig_key: (out) (optional): return location for the original key
1554
 * @value: (out) (optional) (nullable): return location for the value associated
1555
 * with the key
1556
 *
1557
 * Looks up a key in the #GHashTable, returning the original key and the
1558
 * associated value and a #gboolean which is %TRUE if the key was found. This
1559
 * is useful if you need to free the memory allocated for the original key,
1560
 * for example before calling g_hash_table_remove().
1561
 *
1562
 * You can actually pass %NULL for @lookup_key to test
1563
 * whether the %NULL key exists, provided the hash and equal functions
1564
 * of @hash_table are %NULL-safe.
1565
 *
1566
 * Returns: %TRUE if the key was found in the #GHashTable
1567
 */
1568
gboolean
1569
g_hash_table_lookup_extended (GHashTable    *hash_table,
1570
                              gconstpointer  lookup_key,
1571
                              gpointer      *orig_key,
1572
                              gpointer      *value)
1573
0
{
1574
0
  guint node_index;
1575
0
  guint node_hash;
1576
1577
0
  g_return_val_if_fail (hash_table != NULL, FALSE);
1578
1579
0
  node_index = g_hash_table_lookup_node (hash_table, lookup_key, &node_hash);
1580
1581
0
  if (!HASH_IS_REAL (hash_table->hashes[node_index]))
1582
0
    {
1583
0
      if (orig_key != NULL)
1584
0
        *orig_key = NULL;
1585
0
      if (value != NULL)
1586
0
        *value = NULL;
1587
1588
0
      return FALSE;
1589
0
    }
1590
1591
0
  if (orig_key)
1592
0
    *orig_key = g_hash_table_fetch_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys);
1593
1594
0
  if (value)
1595
0
    *value = g_hash_table_fetch_key_or_value (hash_table->values, node_index, hash_table->have_big_values);
1596
1597
0
  return TRUE;
1598
0
}
1599
1600
/*
1601
 * g_hash_table_insert_internal:
1602
 * @hash_table: our #GHashTable
1603
 * @key: the key to insert
1604
 * @value: the value to insert
1605
 * @keep_new_key: if %TRUE and this key already exists in the table
1606
 *   then call the destroy notify function on the old key.  If %FALSE
1607
 *   then call the destroy notify function on the new key.
1608
 *
1609
 * Implements the common logic for the g_hash_table_insert() and
1610
 * g_hash_table_replace() functions.
1611
 *
1612
 * Do a lookup of @key. If it is found, replace it with the new
1613
 * @value (and perhaps the new @key). If it is not found, create
1614
 * a new node.
1615
 *
1616
 * Returns: %TRUE if the key did not exist yet
1617
 */
1618
static gboolean
1619
g_hash_table_insert_internal (GHashTable *hash_table,
1620
                              gpointer    key,
1621
                              gpointer    value,
1622
                              gboolean    keep_new_key)
1623
14.0k
{
1624
14.0k
  guint key_hash;
1625
14.0k
  guint node_index;
1626
1627
14.0k
  g_return_val_if_fail (hash_table != NULL, FALSE);
1628
1629
14.0k
  node_index = g_hash_table_lookup_node (hash_table, key, &key_hash);
1630
1631
14.0k
  return g_hash_table_insert_node (hash_table, node_index, key_hash, key, value, keep_new_key, FALSE);
1632
14.0k
}
1633
1634
/**
1635
 * g_hash_table_insert:
1636
 * @hash_table: a #GHashTable
1637
 * @key: a key to insert
1638
 * @value: the value to associate with the key
1639
 *
1640
 * Inserts a new key and value into a #GHashTable.
1641
 *
1642
 * If the key already exists in the #GHashTable its current
1643
 * value is replaced with the new value. If you supplied a
1644
 * @value_destroy_func when creating the #GHashTable, the old
1645
 * value is freed using that function. If you supplied a
1646
 * @key_destroy_func when creating the #GHashTable, the passed
1647
 * key is freed using that function.
1648
 *
1649
 * Starting from GLib 2.40, this function returns a boolean value to
1650
 * indicate whether the newly added value was already in the hash table
1651
 * or not.
1652
 *
1653
 * Returns: %TRUE if the key did not exist yet
1654
 */
1655
gboolean
1656
g_hash_table_insert (GHashTable *hash_table,
1657
                     gpointer    key,
1658
                     gpointer    value)
1659
5.67k
{
1660
5.67k
  return g_hash_table_insert_internal (hash_table, key, value, FALSE);
1661
5.67k
}
1662
1663
/**
1664
 * g_hash_table_replace:
1665
 * @hash_table: a #GHashTable
1666
 * @key: a key to insert
1667
 * @value: the value to associate with the key
1668
 *
1669
 * Inserts a new key and value into a #GHashTable similar to
1670
 * g_hash_table_insert(). The difference is that if the key
1671
 * already exists in the #GHashTable, it gets replaced by the
1672
 * new key. If you supplied a @value_destroy_func when creating
1673
 * the #GHashTable, the old value is freed using that function.
1674
 * If you supplied a @key_destroy_func when creating the
1675
 * #GHashTable, the old key is freed using that function.
1676
 *
1677
 * Starting from GLib 2.40, this function returns a boolean value to
1678
 * indicate whether the newly added value was already in the hash table
1679
 * or not.
1680
 *
1681
 * Returns: %TRUE if the key did not exist yet
1682
 */
1683
gboolean
1684
g_hash_table_replace (GHashTable *hash_table,
1685
                      gpointer    key,
1686
                      gpointer    value)
1687
8.38k
{
1688
8.38k
  return g_hash_table_insert_internal (hash_table, key, value, TRUE);
1689
8.38k
}
1690
1691
/**
1692
 * g_hash_table_add:
1693
 * @hash_table: a #GHashTable
1694
 * @key: (transfer full): a key to insert
1695
 *
1696
 * This is a convenience function for using a #GHashTable as a set.  It
1697
 * is equivalent to calling g_hash_table_replace() with @key as both the
1698
 * key and the value.
1699
 *
1700
 * In particular, this means that if @key already exists in the hash table, then
1701
 * the old copy of @key in the hash table is freed and @key replaces it in the
1702
 * table.
1703
 *
1704
 * When a hash table only ever contains keys that have themselves as the
1705
 * corresponding value it is able to be stored more efficiently.  See
1706
 * the discussion in the section description.
1707
 *
1708
 * Starting from GLib 2.40, this function returns a boolean value to
1709
 * indicate whether the newly added value was already in the hash table
1710
 * or not.
1711
 *
1712
 * Returns: %TRUE if the key did not exist yet
1713
 *
1714
 * Since: 2.32
1715
 */
1716
gboolean
1717
g_hash_table_add (GHashTable *hash_table,
1718
                  gpointer    key)
1719
8
{
1720
8
  return g_hash_table_insert_internal (hash_table, key, key, TRUE);
1721
8
}
1722
1723
/**
1724
 * g_hash_table_contains:
1725
 * @hash_table: a #GHashTable
1726
 * @key: a key to check
1727
 *
1728
 * Checks if @key is in @hash_table.
1729
 *
1730
 * Returns: %TRUE if @key is in @hash_table, %FALSE otherwise.
1731
 *
1732
 * Since: 2.32
1733
 **/
1734
gboolean
1735
g_hash_table_contains (GHashTable    *hash_table,
1736
                       gconstpointer  key)
1737
103
{
1738
103
  guint node_index;
1739
103
  guint node_hash;
1740
1741
103
  g_return_val_if_fail (hash_table != NULL, FALSE);
1742
1743
103
  node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1744
1745
103
  return HASH_IS_REAL (hash_table->hashes[node_index]);
1746
103
}
1747
1748
/*
1749
 * g_hash_table_remove_internal:
1750
 * @hash_table: our #GHashTable
1751
 * @key: the key to remove
1752
 * @notify: %TRUE if the destroy notify handlers are to be called
1753
 * Returns: %TRUE if a node was found and removed, else %FALSE
1754
 *
1755
 * Implements the common logic for the g_hash_table_remove() and
1756
 * g_hash_table_steal() functions.
1757
 *
1758
 * Do a lookup of @key and remove it if it is found, calling the
1759
 * destroy notify handlers only if @notify is %TRUE.
1760
 */
1761
static gboolean
1762
g_hash_table_remove_internal (GHashTable    *hash_table,
1763
                              gconstpointer  key,
1764
                              gboolean       notify)
1765
5.25k
{
1766
5.25k
  guint node_index;
1767
5.25k
  guint node_hash;
1768
1769
5.25k
  g_return_val_if_fail (hash_table != NULL, FALSE);
1770
1771
5.25k
  node_index = g_hash_table_lookup_node (hash_table, key, &node_hash);
1772
1773
5.25k
  if (!HASH_IS_REAL (hash_table->hashes[node_index]))
1774
0
    return FALSE;
1775
1776
5.25k
  g_hash_table_remove_node (hash_table, node_index, notify);
1777
5.25k
  g_hash_table_maybe_resize (hash_table);
1778
1779
5.25k
#ifndef G_DISABLE_ASSERT
1780
5.25k
  hash_table->version++;
1781
5.25k
#endif
1782
1783
5.25k
  return TRUE;
1784
5.25k
}
1785
1786
/**
1787
 * g_hash_table_remove:
1788
 * @hash_table: a #GHashTable
1789
 * @key: the key to remove
1790
 *
1791
 * Removes a key and its associated value from a #GHashTable.
1792
 *
1793
 * If the #GHashTable was created using g_hash_table_new_full(), the
1794
 * key and value are freed using the supplied destroy functions, otherwise
1795
 * you have to make sure that any dynamically allocated values are freed
1796
 * yourself.
1797
 *
1798
 * Returns: %TRUE if the key was found and removed from the #GHashTable
1799
 */
1800
gboolean
1801
g_hash_table_remove (GHashTable    *hash_table,
1802
                     gconstpointer  key)
1803
5.25k
{
1804
5.25k
  return g_hash_table_remove_internal (hash_table, key, TRUE);
1805
5.25k
}
1806
1807
/**
1808
 * g_hash_table_steal:
1809
 * @hash_table: a #GHashTable
1810
 * @key: the key to remove
1811
 *
1812
 * Removes a key and its associated value from a #GHashTable without
1813
 * calling the key and value destroy functions.
1814
 *
1815
 * Returns: %TRUE if the key was found and removed from the #GHashTable
1816
 */
1817
gboolean
1818
g_hash_table_steal (GHashTable    *hash_table,
1819
                    gconstpointer  key)
1820
0
{
1821
0
  return g_hash_table_remove_internal (hash_table, key, FALSE);
1822
0
}
1823
1824
/**
1825
 * g_hash_table_steal_extended:
1826
 * @hash_table: a #GHashTable
1827
 * @lookup_key: the key to look up
1828
 * @stolen_key: (out) (optional) (transfer full): return location for the
1829
 *    original key
1830
 * @stolen_value: (out) (optional) (nullable) (transfer full): return location
1831
 *    for the value associated with the key
1832
 *
1833
 * Looks up a key in the #GHashTable, stealing the original key and the
1834
 * associated value and returning %TRUE if the key was found. If the key was
1835
 * not found, %FALSE is returned.
1836
 *
1837
 * If found, the stolen key and value are removed from the hash table without
1838
 * calling the key and value destroy functions, and ownership is transferred to
1839
 * the caller of this method, as with g_hash_table_steal(). That is the case
1840
 * regardless whether @stolen_key or @stolen_value output parameters are
1841
 * requested.
1842
 *
1843
 * You can pass %NULL for @lookup_key, provided the hash and equal functions
1844
 * of @hash_table are %NULL-safe.
1845
 *
1846
 * The dictionary implementation optimizes for having all values identical to
1847
 * their keys, for example by using g_hash_table_add(). When stealing both the
1848
 * key and the value from such a dictionary, the value will be %NULL.
1849
 *
1850
 * Returns: %TRUE if the key was found in the #GHashTable
1851
 * Since: 2.58
1852
 */
1853
gboolean
1854
g_hash_table_steal_extended (GHashTable    *hash_table,
1855
                             gconstpointer  lookup_key,
1856
                             gpointer      *stolen_key,
1857
                             gpointer      *stolen_value)
1858
0
{
1859
0
  guint node_index;
1860
0
  guint node_hash;
1861
1862
0
  g_return_val_if_fail (hash_table != NULL, FALSE);
1863
1864
0
  node_index = g_hash_table_lookup_node (hash_table, lookup_key, &node_hash);
1865
1866
0
  if (!HASH_IS_REAL (hash_table->hashes[node_index]))
1867
0
    {
1868
0
      if (stolen_key != NULL)
1869
0
        *stolen_key = NULL;
1870
0
      if (stolen_value != NULL)
1871
0
        *stolen_value = NULL;
1872
0
      return FALSE;
1873
0
    }
1874
1875
0
  if (stolen_key != NULL)
1876
0
  {
1877
0
    *stolen_key = g_hash_table_fetch_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys);
1878
0
    g_hash_table_assign_key_or_value (hash_table->keys, node_index, hash_table->have_big_keys, NULL);
1879
0
  }
1880
1881
0
  if (stolen_value != NULL)
1882
0
  {
1883
0
    *stolen_value = g_hash_table_fetch_key_or_value (hash_table->values, node_index, hash_table->have_big_values);
1884
0
    g_hash_table_assign_key_or_value (hash_table->values, node_index, hash_table->have_big_values, NULL);
1885
0
  }
1886
1887
0
  g_hash_table_remove_node (hash_table, node_index, FALSE);
1888
0
  g_hash_table_maybe_resize (hash_table);
1889
1890
0
#ifndef G_DISABLE_ASSERT
1891
0
  hash_table->version++;
1892
0
#endif
1893
1894
0
  return TRUE;
1895
0
}
1896
1897
/**
1898
 * g_hash_table_remove_all:
1899
 * @hash_table: a #GHashTable
1900
 *
1901
 * Removes all keys and their associated values from a #GHashTable.
1902
 *
1903
 * If the #GHashTable was created using g_hash_table_new_full(),
1904
 * the keys and values are freed using the supplied destroy functions,
1905
 * otherwise you have to make sure that any dynamically allocated
1906
 * values are freed yourself.
1907
 *
1908
 * Since: 2.12
1909
 */
1910
void
1911
g_hash_table_remove_all (GHashTable *hash_table)
1912
12.0k
{
1913
12.0k
  g_return_if_fail (hash_table != NULL);
1914
1915
12.0k
#ifndef G_DISABLE_ASSERT
1916
12.0k
  if (hash_table->nnodes != 0)
1917
5.34k
    hash_table->version++;
1918
12.0k
#endif
1919
1920
12.0k
  g_hash_table_remove_all_nodes (hash_table, TRUE, FALSE);
1921
12.0k
  g_hash_table_maybe_resize (hash_table);
1922
12.0k
}
1923
1924
/**
1925
 * g_hash_table_steal_all:
1926
 * @hash_table: a #GHashTable
1927
 *
1928
 * Removes all keys and their associated values from a #GHashTable
1929
 * without calling the key and value destroy functions.
1930
 *
1931
 * Since: 2.12
1932
 */
1933
void
1934
g_hash_table_steal_all (GHashTable *hash_table)
1935
0
{
1936
0
  g_return_if_fail (hash_table != NULL);
1937
1938
0
#ifndef G_DISABLE_ASSERT
1939
0
  if (hash_table->nnodes != 0)
1940
0
    hash_table->version++;
1941
0
#endif
1942
1943
0
  g_hash_table_remove_all_nodes (hash_table, FALSE, FALSE);
1944
0
  g_hash_table_maybe_resize (hash_table);
1945
0
}
1946
1947
/**
1948
 * g_hash_table_steal_all_keys: (skip)
1949
 * @hash_table: a #GHashTable
1950
 *
1951
 * Removes all keys and their associated values from a #GHashTable
1952
 * without calling the key destroy functions, returning the keys
1953
 * as a #GPtrArray with the free func set to the @hash_table key
1954
 * destroy function.
1955
 *
1956
 * Returns: (transfer container): a #GPtrArray containing each key of
1957
 * the table. Unref with with g_ptr_array_unref() when done.
1958
 *
1959
 * Since: 2.76
1960
 */
1961
GPtrArray *
1962
g_hash_table_steal_all_keys (GHashTable *hash_table)
1963
0
{
1964
0
  GPtrArray *array;
1965
0
  GDestroyNotify key_destroy_func;
1966
1967
0
  g_return_val_if_fail (hash_table != NULL, NULL);
1968
1969
0
  array = g_hash_table_get_keys_as_ptr_array (hash_table);
1970
1971
  /* Ignore the key destroy notify calls during removal, and use it for the
1972
   * array elements instead, but restore it after the hash table has been
1973
   * cleared, so that newly added keys will continue using it.
1974
   */
1975
0
  key_destroy_func = g_steal_pointer (&hash_table->key_destroy_func);
1976
0
  g_ptr_array_set_free_func (array, key_destroy_func);
1977
1978
0
  g_hash_table_remove_all (hash_table);
1979
0
  hash_table->key_destroy_func = g_steal_pointer (&key_destroy_func);
1980
1981
0
  return array;
1982
0
}
1983
1984
/**
1985
 * g_hash_table_steal_all_values: (skip)
1986
 * @hash_table: a #GHashTable
1987
 *
1988
 * Removes all keys and their associated values from a #GHashTable
1989
 * without calling the value destroy functions, returning the values
1990
 * as a #GPtrArray with the free func set to the @hash_table value
1991
 * destroy function.
1992
 *
1993
 * Returns: (transfer container): a #GPtrArray containing each value of
1994
 * the table. Unref with with g_ptr_array_unref() when done.
1995
 *
1996
 * Since: 2.76
1997
 */
1998
GPtrArray *
1999
g_hash_table_steal_all_values (GHashTable *hash_table)
2000
0
{
2001
0
  GPtrArray *array;
2002
0
  GDestroyNotify value_destroy_func;
2003
2004
0
  g_return_val_if_fail (hash_table != NULL, NULL);
2005
2006
0
  array = g_hash_table_get_values_as_ptr_array (hash_table);
2007
2008
  /* Ignore the value destroy notify calls during removal, and use it for the
2009
   * array elements instead, but restore it after the hash table has been
2010
   * cleared, so that newly added values will continue using it.
2011
   */
2012
0
  value_destroy_func = g_steal_pointer (&hash_table->value_destroy_func);
2013
0
  g_ptr_array_set_free_func (array, value_destroy_func);
2014
2015
0
  g_hash_table_remove_all (hash_table);
2016
0
  hash_table->value_destroy_func = g_steal_pointer (&value_destroy_func);
2017
2018
0
  return array;
2019
0
}
2020
2021
/*
2022
 * g_hash_table_foreach_remove_or_steal:
2023
 * @hash_table: a #GHashTable
2024
 * @func: the user's callback function
2025
 * @user_data: data for @func
2026
 * @notify: %TRUE if the destroy notify handlers are to be called
2027
 *
2028
 * Implements the common logic for g_hash_table_foreach_remove()
2029
 * and g_hash_table_foreach_steal().
2030
 *
2031
 * Iterates over every node in the table, calling @func with the key
2032
 * and value of the node (and @user_data). If @func returns %TRUE the
2033
 * node is removed from the table.
2034
 *
2035
 * If @notify is true then the destroy notify handlers will be called
2036
 * for each removed node.
2037
 */
2038
static guint
2039
g_hash_table_foreach_remove_or_steal (GHashTable *hash_table,
2040
                                      GHRFunc     func,
2041
                                      gpointer    user_data,
2042
                                      gboolean    notify)
2043
0
{
2044
0
  guint deleted = 0;
2045
0
  gsize i;
2046
0
#ifndef G_DISABLE_ASSERT
2047
0
  gint version = hash_table->version;
2048
0
#endif
2049
2050
0
  for (i = 0; i < hash_table->size; i++)
2051
0
    {
2052
0
      guint node_hash = hash_table->hashes[i];
2053
0
      gpointer node_key = g_hash_table_fetch_key_or_value (hash_table->keys, i, hash_table->have_big_keys);
2054
0
      gpointer node_value = g_hash_table_fetch_key_or_value (hash_table->values, i, hash_table->have_big_values);
2055
2056
0
      if (HASH_IS_REAL (node_hash) &&
2057
0
          (* func) (node_key, node_value, user_data))
2058
0
        {
2059
0
          g_hash_table_remove_node (hash_table, i, notify);
2060
0
          deleted++;
2061
0
        }
2062
2063
0
#ifndef G_DISABLE_ASSERT
2064
0
      g_return_val_if_fail (version == hash_table->version, 0);
2065
0
#endif
2066
0
    }
2067
2068
0
  g_hash_table_maybe_resize (hash_table);
2069
2070
0
#ifndef G_DISABLE_ASSERT
2071
0
  if (deleted > 0)
2072
0
    hash_table->version++;
2073
0
#endif
2074
2075
0
  return deleted;
2076
0
}
2077
2078
/**
2079
 * g_hash_table_foreach_remove:
2080
 * @hash_table: a #GHashTable
2081
 * @func: the function to call for each key/value pair
2082
 * @user_data: user data to pass to the function
2083
 *
2084
 * Calls the given function for each key/value pair in the
2085
 * #GHashTable. If the function returns %TRUE, then the key/value
2086
 * pair is removed from the #GHashTable. If you supplied key or
2087
 * value destroy functions when creating the #GHashTable, they are
2088
 * used to free the memory allocated for the removed keys and values.
2089
 *
2090
 * See #GHashTableIter for an alternative way to loop over the
2091
 * key/value pairs in the hash table.
2092
 *
2093
 * Returns: the number of key/value pairs removed
2094
 */
2095
guint
2096
g_hash_table_foreach_remove (GHashTable *hash_table,
2097
                             GHRFunc     func,
2098
                             gpointer    user_data)
2099
0
{
2100
0
  g_return_val_if_fail (hash_table != NULL, 0);
2101
0
  g_return_val_if_fail (func != NULL, 0);
2102
2103
0
  return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, TRUE);
2104
0
}
2105
2106
/**
2107
 * g_hash_table_foreach_steal:
2108
 * @hash_table: a #GHashTable
2109
 * @func: the function to call for each key/value pair
2110
 * @user_data: user data to pass to the function
2111
 *
2112
 * Calls the given function for each key/value pair in the
2113
 * #GHashTable. If the function returns %TRUE, then the key/value
2114
 * pair is removed from the #GHashTable, but no key or value
2115
 * destroy functions are called.
2116
 *
2117
 * See #GHashTableIter for an alternative way to loop over the
2118
 * key/value pairs in the hash table.
2119
 *
2120
 * Returns: the number of key/value pairs removed.
2121
 */
2122
guint
2123
g_hash_table_foreach_steal (GHashTable *hash_table,
2124
                            GHRFunc     func,
2125
                            gpointer    user_data)
2126
0
{
2127
0
  g_return_val_if_fail (hash_table != NULL, 0);
2128
0
  g_return_val_if_fail (func != NULL, 0);
2129
2130
0
  return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, FALSE);
2131
0
}
2132
2133
/**
2134
 * g_hash_table_foreach:
2135
 * @hash_table: a #GHashTable
2136
 * @func: the function to call for each key/value pair
2137
 * @user_data: user data to pass to the function
2138
 *
2139
 * Calls the given function for each of the key/value pairs in the
2140
 * #GHashTable.  The function is passed the key and value of each
2141
 * pair, and the given @user_data parameter.  The hash table may not
2142
 * be modified while iterating over it (you can't add/remove
2143
 * items). To remove all items matching a predicate, use
2144
 * g_hash_table_foreach_remove().
2145
 *
2146
 * The order in which g_hash_table_foreach() iterates over the keys/values in
2147
 * the hash table is not defined.
2148
 *
2149
 * See g_hash_table_find() for performance caveats for linear
2150
 * order searches in contrast to g_hash_table_lookup().
2151
 */
2152
void
2153
g_hash_table_foreach (GHashTable *hash_table,
2154
                      GHFunc      func,
2155
                      gpointer    user_data)
2156
2
{
2157
2
  gsize i;
2158
2
#ifndef G_DISABLE_ASSERT
2159
2
  gint version;
2160
2
#endif
2161
2162
2
  g_return_if_fail (hash_table != NULL);
2163
2
  g_return_if_fail (func != NULL);
2164
2165
2
#ifndef G_DISABLE_ASSERT
2166
2
  version = hash_table->version;
2167
2
#endif
2168
2169
18
  for (i = 0; i < hash_table->size; i++)
2170
16
    {
2171
16
      guint node_hash = hash_table->hashes[i];
2172
16
      gpointer node_key = g_hash_table_fetch_key_or_value (hash_table->keys, i, hash_table->have_big_keys);
2173
16
      gpointer node_value = g_hash_table_fetch_key_or_value (hash_table->values, i, hash_table->have_big_values);
2174
2175
16
      if (HASH_IS_REAL (node_hash))
2176
10
        (* func) (node_key, node_value, user_data);
2177
2178
16
#ifndef G_DISABLE_ASSERT
2179
16
      g_return_if_fail (version == hash_table->version);
2180
16
#endif
2181
16
    }
2182
2
}
2183
2184
/**
2185
 * g_hash_table_find:
2186
 * @hash_table: a #GHashTable
2187
 * @predicate: function to test the key/value pairs for a certain property
2188
 * @user_data: user data to pass to the function
2189
 *
2190
 * Calls the given function for key/value pairs in the #GHashTable
2191
 * until @predicate returns %TRUE. The function is passed the key
2192
 * and value of each pair, and the given @user_data parameter. The
2193
 * hash table may not be modified while iterating over it (you can't
2194
 * add/remove items).
2195
 *
2196
 * Note, that hash tables are really only optimized for forward
2197
 * lookups, i.e. g_hash_table_lookup(). So code that frequently issues
2198
 * g_hash_table_find() or g_hash_table_foreach() (e.g. in the order of
2199
 * once per every entry in a hash table) should probably be reworked
2200
 * to use additional or different data structures for reverse lookups
2201
 * (keep in mind that an O(n) find/foreach operation issued for all n
2202
 * values in a hash table ends up needing O(n*n) operations).
2203
 *
2204
 * Returns: (nullable): The value of the first key/value pair is returned,
2205
 *     for which @predicate evaluates to %TRUE. If no pair with the
2206
 *     requested property is found, %NULL is returned.
2207
 *
2208
 * Since: 2.4
2209
 */
2210
gpointer
2211
g_hash_table_find (GHashTable *hash_table,
2212
                   GHRFunc     predicate,
2213
                   gpointer    user_data)
2214
0
{
2215
0
  gsize i;
2216
0
#ifndef G_DISABLE_ASSERT
2217
0
  gint version;
2218
0
#endif
2219
0
  gboolean match;
2220
2221
0
  g_return_val_if_fail (hash_table != NULL, NULL);
2222
0
  g_return_val_if_fail (predicate != NULL, NULL);
2223
2224
0
#ifndef G_DISABLE_ASSERT
2225
0
  version = hash_table->version;
2226
0
#endif
2227
2228
0
  match = FALSE;
2229
2230
0
  for (i = 0; i < hash_table->size; i++)
2231
0
    {
2232
0
      guint node_hash = hash_table->hashes[i];
2233
0
      gpointer node_key = g_hash_table_fetch_key_or_value (hash_table->keys, i, hash_table->have_big_keys);
2234
0
      gpointer node_value = g_hash_table_fetch_key_or_value (hash_table->values, i, hash_table->have_big_values);
2235
2236
0
      if (HASH_IS_REAL (node_hash))
2237
0
        match = predicate (node_key, node_value, user_data);
2238
2239
0
#ifndef G_DISABLE_ASSERT
2240
0
      g_return_val_if_fail (version == hash_table->version, NULL);
2241
0
#endif
2242
2243
0
      if (match)
2244
0
        return node_value;
2245
0
    }
2246
2247
0
  return NULL;
2248
0
}
2249
2250
/**
2251
 * g_hash_table_size:
2252
 * @hash_table: a #GHashTable
2253
 *
2254
 * Returns the number of elements contained in the #GHashTable.
2255
 *
2256
 * Returns: the number of key/value pairs in the #GHashTable.
2257
 */
2258
guint
2259
g_hash_table_size (GHashTable *hash_table)
2260
0
{
2261
0
  g_return_val_if_fail (hash_table != NULL, 0);
2262
2263
0
  return hash_table->nnodes;
2264
0
}
2265
2266
/**
2267
 * g_hash_table_get_keys:
2268
 * @hash_table: a #GHashTable
2269
 *
2270
 * Retrieves every key inside @hash_table. The returned data is valid
2271
 * until changes to the hash release those keys.
2272
 *
2273
 * This iterates over every entry in the hash table to build its return value.
2274
 * To iterate over the entries in a #GHashTable more efficiently, use a
2275
 * #GHashTableIter.
2276
 *
2277
 * Returns: (transfer container): a #GList containing all the keys
2278
 *     inside the hash table. The content of the list is owned by the
2279
 *     hash table and should not be modified or freed. Use g_list_free()
2280
 *     when done using the list.
2281
 *
2282
 * Since: 2.14
2283
 */
2284
GList *
2285
g_hash_table_get_keys (GHashTable *hash_table)
2286
0
{
2287
0
  gsize i;
2288
0
  GList *retval;
2289
2290
0
  g_return_val_if_fail (hash_table != NULL, NULL);
2291
2292
0
  retval = NULL;
2293
0
  for (i = 0; i < hash_table->size; i++)
2294
0
    {
2295
0
      if (HASH_IS_REAL (hash_table->hashes[i]))
2296
0
        retval = g_list_prepend (retval, g_hash_table_fetch_key_or_value (hash_table->keys, i, hash_table->have_big_keys));
2297
0
    }
2298
2299
0
  return retval;
2300
0
}
2301
2302
/**
2303
 * g_hash_table_get_keys_as_array:
2304
 * @hash_table: a #GHashTable
2305
 * @length: (out) (optional): the length of the returned array
2306
 *
2307
 * Retrieves every key inside @hash_table, as an array.
2308
 *
2309
 * The returned array is %NULL-terminated but may contain %NULL as a
2310
 * key.  Use @length to determine the true length if it's possible that
2311
 * %NULL was used as the value for a key.
2312
 *
2313
 * Note: in the common case of a string-keyed #GHashTable, the return
2314
 * value of this function can be conveniently cast to (const gchar **).
2315
 *
2316
 * This iterates over every entry in the hash table to build its return value.
2317
 * To iterate over the entries in a #GHashTable more efficiently, use a
2318
 * #GHashTableIter.
2319
 *
2320
 * You should always free the return result with g_free().  In the
2321
 * above-mentioned case of a string-keyed hash table, it may be
2322
 * appropriate to use g_strfreev() if you call g_hash_table_steal_all()
2323
 * first to transfer ownership of the keys.
2324
 *
2325
 * Returns: (array length=length) (transfer container): a
2326
 *   %NULL-terminated array containing each key from the table.
2327
 *
2328
 * Since: 2.40
2329
 **/
2330
gpointer *
2331
g_hash_table_get_keys_as_array (GHashTable *hash_table,
2332
                                guint      *length)
2333
0
{
2334
0
  gpointer *result;
2335
0
  gsize i, j = 0;
2336
2337
0
  result = g_new (gpointer, hash_table->nnodes + 1);
2338
0
  for (i = 0; i < hash_table->size; i++)
2339
0
    {
2340
0
      if (HASH_IS_REAL (hash_table->hashes[i]))
2341
0
        result[j++] = g_hash_table_fetch_key_or_value (hash_table->keys, i, hash_table->have_big_keys);
2342
0
    }
2343
0
  g_assert (j == hash_table->nnodes);
2344
0
  result[j] = NULL;
2345
2346
0
  if (length)
2347
0
    *length = j;
2348
2349
0
  return result;
2350
0
}
2351
2352
/**
2353
 * g_hash_table_get_keys_as_ptr_array: (skip)
2354
 * @hash_table: a #GHashTable
2355
 *
2356
 * Retrieves every key inside @hash_table, as a #GPtrArray.
2357
 * The returned data is valid until changes to the hash release those keys.
2358
 *
2359
 * This iterates over every entry in the hash table to build its return value.
2360
 * To iterate over the entries in a #GHashTable more efficiently, use a
2361
 * #GHashTableIter.
2362
 *
2363
 * You should always unref the returned array with g_ptr_array_unref().
2364
 *
2365
 * Returns: (transfer container): a #GPtrArray containing each key from
2366
 * the table. Unref with with g_ptr_array_unref() when done.
2367
 *
2368
 * Since: 2.76
2369
 **/
2370
GPtrArray *
2371
g_hash_table_get_keys_as_ptr_array (GHashTable *hash_table)
2372
0
{
2373
0
  GPtrArray *array;
2374
2375
0
  g_return_val_if_fail (hash_table != NULL, NULL);
2376
2377
0
  array = g_ptr_array_sized_new (hash_table->size);
2378
0
  for (gsize i = 0; i < hash_table->size; ++i)
2379
0
    {
2380
0
      if (HASH_IS_REAL (hash_table->hashes[i]))
2381
0
        {
2382
0
          g_ptr_array_add (array, g_hash_table_fetch_key_or_value (
2383
0
            hash_table->keys, i, hash_table->have_big_keys));
2384
0
        }
2385
0
    }
2386
0
  g_assert (array->len == hash_table->nnodes);
2387
2388
0
  return array;
2389
0
}
2390
2391
/**
2392
 * g_hash_table_get_values:
2393
 * @hash_table: a #GHashTable
2394
 *
2395
 * Retrieves every value inside @hash_table. The returned data
2396
 * is valid until @hash_table is modified.
2397
 *
2398
 * This iterates over every entry in the hash table to build its return value.
2399
 * To iterate over the entries in a #GHashTable more efficiently, use a
2400
 * #GHashTableIter.
2401
 *
2402
 * Returns: (transfer container): a #GList containing all the values
2403
 *     inside the hash table. The content of the list is owned by the
2404
 *     hash table and should not be modified or freed. Use g_list_free()
2405
 *     when done using the list.
2406
 *
2407
 * Since: 2.14
2408
 */
2409
GList *
2410
g_hash_table_get_values (GHashTable *hash_table)
2411
0
{
2412
0
  gsize i;
2413
0
  GList *retval;
2414
2415
0
  g_return_val_if_fail (hash_table != NULL, NULL);
2416
2417
0
  retval = NULL;
2418
0
  for (i = 0; i < hash_table->size; i++)
2419
0
    {
2420
0
      if (HASH_IS_REAL (hash_table->hashes[i]))
2421
0
        retval = g_list_prepend (retval, g_hash_table_fetch_key_or_value (hash_table->values, i, hash_table->have_big_values));
2422
0
    }
2423
2424
0
  return retval;
2425
0
}
2426
2427
/**
2428
 * g_hash_table_get_values_as_ptr_array: (skip)
2429
 * @hash_table: a #GHashTable
2430
 *
2431
 * Retrieves every value inside @hash_table, as a #GPtrArray.
2432
 * The returned data is valid until changes to the hash release those values.
2433
 *
2434
 * This iterates over every entry in the hash table to build its return value.
2435
 * To iterate over the entries in a #GHashTable more efficiently, use a
2436
 * #GHashTableIter.
2437
 *
2438
 * You should always unref the returned array with g_ptr_array_unref().
2439
 *
2440
 * Returns: (transfer container): a #GPtrArray containing each value from
2441
 * the table. Unref with with g_ptr_array_unref() when done.
2442
 *
2443
 * Since: 2.76
2444
 **/
2445
GPtrArray *
2446
g_hash_table_get_values_as_ptr_array (GHashTable *hash_table)
2447
0
{
2448
0
  GPtrArray *array;
2449
2450
0
  g_return_val_if_fail (hash_table != NULL, NULL);
2451
2452
0
  array = g_ptr_array_sized_new (hash_table->size);
2453
0
  for (gsize i = 0; i < hash_table->size; ++i)
2454
0
    {
2455
0
      if (HASH_IS_REAL (hash_table->hashes[i]))
2456
0
        {
2457
0
          g_ptr_array_add (array, g_hash_table_fetch_key_or_value (
2458
0
            hash_table->values, i, hash_table->have_big_values));
2459
0
        }
2460
0
    }
2461
0
  g_assert (array->len == hash_table->nnodes);
2462
2463
0
  return array;
2464
0
}
2465
2466
/* Hash functions.
2467
 */
2468
2469
/**
2470
 * g_str_equal:
2471
 * @v1: (not nullable): a key
2472
 * @v2: (not nullable): a key to compare with @v1
2473
 *
2474
 * Compares two strings for byte-by-byte equality and returns %TRUE
2475
 * if they are equal. It can be passed to g_hash_table_new() as the
2476
 * @key_equal_func parameter, when using non-%NULL strings as keys in a
2477
 * #GHashTable.
2478
 *
2479
 * This function is typically used for hash table comparisons, but can be used
2480
 * for general purpose comparisons of non-%NULL strings. For a %NULL-safe string
2481
 * comparison function, see g_strcmp0().
2482
 *
2483
 * Returns: %TRUE if the two keys match
2484
 */
2485
gboolean
2486
(g_str_equal) (gconstpointer v1,
2487
               gconstpointer v2)
2488
37.3k
{
2489
37.3k
  const gchar *string1 = v1;
2490
37.3k
  const gchar *string2 = v2;
2491
2492
37.3k
  return strcmp (string1, string2) == 0;
2493
37.3k
}
2494
2495
/**
2496
 * g_str_hash:
2497
 * @v: (not nullable): a string key
2498
 *
2499
 * Converts a string to a hash value.
2500
 *
2501
 * This function implements the widely used "djb" hash apparently
2502
 * posted by Daniel Bernstein to comp.lang.c some time ago.  The 32
2503
 * bit unsigned hash value starts at 5381 and for each byte 'c' in
2504
 * the string, is updated: `hash = hash * 33 + c`. This function
2505
 * uses the signed value of each byte.
2506
 *
2507
 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2508
 * when using non-%NULL strings as keys in a #GHashTable.
2509
 *
2510
 * Note that this function may not be a perfect fit for all use cases.
2511
 * For example, it produces some hash collisions with strings as short
2512
 * as 2.
2513
 *
2514
 * Returns: a hash value corresponding to the key
2515
 */
2516
guint
2517
g_str_hash (gconstpointer v)
2518
90.6k
{
2519
90.6k
  const signed char *p;
2520
90.6k
  guint32 h = 5381;
2521
2522
521M
  for (p = v; *p != '\0'; p++)
2523
521M
    h = (h << 5) + h + *p;
2524
2525
90.6k
  return h;
2526
90.6k
}
2527
2528
/**
2529
 * g_direct_hash:
2530
 * @v: (nullable): a #gpointer key
2531
 *
2532
 * Converts a gpointer to a hash value.
2533
 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2534
 * when using opaque pointers compared by pointer value as keys in a
2535
 * #GHashTable.
2536
 *
2537
 * This hash function is also appropriate for keys that are integers
2538
 * stored in pointers, such as `GINT_TO_POINTER (n)`.
2539
 *
2540
 * Returns: a hash value corresponding to the key.
2541
 */
2542
guint
2543
g_direct_hash (gconstpointer v)
2544
66.8k
{
2545
66.8k
  return GPOINTER_TO_UINT (v);
2546
66.8k
}
2547
2548
/**
2549
 * g_direct_equal:
2550
 * @v1: (nullable): a key
2551
 * @v2: (nullable): a key to compare with @v1
2552
 *
2553
 * Compares two #gpointer arguments and returns %TRUE if they are equal.
2554
 * It can be passed to g_hash_table_new() as the @key_equal_func
2555
 * parameter, when using opaque pointers compared by pointer value as
2556
 * keys in a #GHashTable.
2557
 *
2558
 * This equality function is also appropriate for keys that are integers
2559
 * stored in pointers, such as `GINT_TO_POINTER (n)`.
2560
 *
2561
 * Returns: %TRUE if the two keys match.
2562
 */
2563
gboolean
2564
g_direct_equal (gconstpointer v1,
2565
                gconstpointer v2)
2566
0
{
2567
0
  return v1 == v2;
2568
0
}
2569
2570
/**
2571
 * g_int_equal:
2572
 * @v1: (not nullable): a pointer to a #gint key
2573
 * @v2: (not nullable): a pointer to a #gint key to compare with @v1
2574
 *
2575
 * Compares the two #gint values being pointed to and returns
2576
 * %TRUE if they are equal.
2577
 * It can be passed to g_hash_table_new() as the @key_equal_func
2578
 * parameter, when using non-%NULL pointers to integers as keys in a
2579
 * #GHashTable.
2580
 *
2581
 * Note that this function acts on pointers to #gint, not on #gint
2582
 * directly: if your hash table's keys are of the form
2583
 * `GINT_TO_POINTER (n)`, use g_direct_equal() instead.
2584
 *
2585
 * Returns: %TRUE if the two keys match.
2586
 */
2587
gboolean
2588
g_int_equal (gconstpointer v1,
2589
             gconstpointer v2)
2590
0
{
2591
0
  return *((const gint*) v1) == *((const gint*) v2);
2592
0
}
2593
2594
/**
2595
 * g_int_hash:
2596
 * @v: (not nullable): a pointer to a #gint key
2597
 *
2598
 * Converts a pointer to a #gint to a hash value.
2599
 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2600
 * when using non-%NULL pointers to integer values as keys in a #GHashTable.
2601
 *
2602
 * Note that this function acts on pointers to #gint, not on #gint
2603
 * directly: if your hash table's keys are of the form
2604
 * `GINT_TO_POINTER (n)`, use g_direct_hash() instead.
2605
 *
2606
 * Returns: a hash value corresponding to the key.
2607
 */
2608
guint
2609
g_int_hash (gconstpointer v)
2610
0
{
2611
0
  return *(const gint*) v;
2612
0
}
2613
2614
/**
2615
 * g_int64_equal:
2616
 * @v1: (not nullable): a pointer to a #gint64 key
2617
 * @v2: (not nullable): a pointer to a #gint64 key to compare with @v1
2618
 *
2619
 * Compares the two #gint64 values being pointed to and returns
2620
 * %TRUE if they are equal.
2621
 * It can be passed to g_hash_table_new() as the @key_equal_func
2622
 * parameter, when using non-%NULL pointers to 64-bit integers as keys in a
2623
 * #GHashTable.
2624
 *
2625
 * Returns: %TRUE if the two keys match.
2626
 *
2627
 * Since: 2.22
2628
 */
2629
gboolean
2630
g_int64_equal (gconstpointer v1,
2631
               gconstpointer v2)
2632
0
{
2633
0
  return *((const gint64*) v1) == *((const gint64*) v2);
2634
0
}
2635
2636
/**
2637
 * g_int64_hash:
2638
 * @v: (not nullable): a pointer to a #gint64 key
2639
 *
2640
 * Converts a pointer to a #gint64 to a hash value.
2641
 *
2642
 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2643
 * when using non-%NULL pointers to 64-bit integer values as keys in a
2644
 * #GHashTable.
2645
 *
2646
 * Returns: a hash value corresponding to the key.
2647
 *
2648
 * Since: 2.22
2649
 */
2650
guint
2651
g_int64_hash (gconstpointer v)
2652
0
{
2653
0
  const guint64 *bits = v;
2654
2655
0
  return (guint) ((*bits >> 32) ^ (*bits & 0xffffffffU));
2656
0
}
2657
2658
/**
2659
 * g_double_equal:
2660
 * @v1: (not nullable): a pointer to a #gdouble key
2661
 * @v2: (not nullable): a pointer to a #gdouble key to compare with @v1
2662
 *
2663
 * Compares the two #gdouble values being pointed to and returns
2664
 * %TRUE if they are equal.
2665
 * It can be passed to g_hash_table_new() as the @key_equal_func
2666
 * parameter, when using non-%NULL pointers to doubles as keys in a
2667
 * #GHashTable.
2668
 *
2669
 * Returns: %TRUE if the two keys match.
2670
 *
2671
 * Since: 2.22
2672
 */
2673
gboolean
2674
g_double_equal (gconstpointer v1,
2675
                gconstpointer v2)
2676
0
{
2677
0
  return *((const gdouble*) v1) == *((const gdouble*) v2);
2678
0
}
2679
2680
/**
2681
 * g_double_hash:
2682
 * @v: (not nullable): a pointer to a #gdouble key
2683
 *
2684
 * Converts a pointer to a #gdouble to a hash value.
2685
 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2686
 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2687
 * when using non-%NULL pointers to doubles as keys in a #GHashTable.
2688
 *
2689
 * Returns: a hash value corresponding to the key.
2690
 *
2691
 * Since: 2.22
2692
 */
2693
guint
2694
g_double_hash (gconstpointer v)
2695
0
{
2696
  /* Same as g_int64_hash() */
2697
0
  const guint64 *bits = v;
2698
2699
0
  return (guint) ((*bits >> 32) ^ (*bits & 0xffffffffU));
2700
0
}