Coverage Report

Created: 2026-09-28 06:47

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wget2/libwget/hashmap.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2012 Tim Ruehsen
3
 * Copyright (c) 2015-2026 Free Software Foundation, Inc.
4
 *
5
 * This file is part of libwget.
6
 *
7
 * Libwget is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Lesser General Public License as published by
9
 * the Free Software Foundation, either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * Libwget is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public License
18
 * along with libwget.  If not, see <https://www.gnu.org/licenses/>.
19
 *
20
 *
21
 * hashmap routines
22
 *
23
 * Changelog
24
 * 06.11.2012  Tim Ruehsen  created
25
 *
26
 */
27
28
#include <config.h>
29
30
#include <stdio.h>
31
#include <stdlib.h>
32
#include <string.h>
33
#include <stdarg.h>
34
35
#include <wget.h>
36
#include "private.h"
37
38
typedef struct entry_st entry_t;
39
40
struct entry_st {
41
  void
42
    *key,
43
    *value;
44
  entry_t
45
    *next;
46
  unsigned int
47
    hash;
48
};
49
50
struct wget_hashmap_st {
51
  wget_hashmap_hash_fn
52
    *hash; // hash function
53
  wget_hashmap_compare_fn
54
    *cmp; // compare function
55
  wget_hashmap_key_destructor
56
    *key_destructor; // key destructor function
57
  wget_hashmap_value_destructor
58
    *value_destructor; // value destructor function
59
  entry_t
60
    **entry;   // pointer to array of pointers to entries
61
  int
62
    max,       // allocated entries
63
    cur,       // number of entries in use
64
    threshold; // resize when max reaches threshold
65
  float
66
    resize_factor, // resize strategy: >0: resize = off * max, <0: resize = max + (-off)
67
    load_factor;
68
};
69
70
struct wget_hashmap_iterator_st {
71
  struct wget_hashmap_st
72
    *h;
73
  entry_t
74
    *entry;
75
  int
76
    pos;
77
};
78
79
/**
80
 * \file
81
 * \brief Hashmap functions
82
 * \defgroup libwget-hashmap Hashmap functions
83
 * @{
84
 *
85
 * Hashmaps are key/value stores that perform at O(1) for insertion, searching and removing.
86
 */
87
88
/**
89
 * \param[in] h Hashmap
90
 * \return New iterator instance for \p h
91
 *
92
 * Creates a hashmap iterator for \p h.
93
 */
94
wget_hashmap_iterator *wget_hashmap_iterator_alloc(wget_hashmap *h)
95
0
{
96
0
  struct wget_hashmap_iterator_st *iter = wget_calloc(1, sizeof(struct wget_hashmap_iterator_st));
97
98
0
  if (iter)
99
0
    iter->h = h;
100
101
0
  return (wget_hashmap_iterator *) iter;
102
0
}
103
104
/**
105
 * \param[in] iter Hashmap iterator
106
 *
107
 * Free the given iterator \p iter.
108
 */
109
void wget_hashmap_iterator_free(wget_hashmap_iterator **iter)
110
0
{
111
0
  if (iter)
112
0
    xfree(*iter);
113
0
}
114
115
/**
116
 * \param[in] iter Hashmap iterator
117
 * \param[out] value Pointer to the value belonging to the returned key
118
 * \return Pointer to the key or NULL if no more elements left
119
 *
120
 * Returns the next key / value in the hashmap. If all key/value pairs have been
121
 * iterated over the function returns NULL and \p value is untouched.
122
 *
123
 * When iterating over a hashmap, the order of returned key/value pairs is not defined.
124
 */
125
void *wget_hashmap_iterator_next(wget_hashmap_iterator *iter, void **value)
126
0
{
127
0
  struct wget_hashmap_iterator_st *_iter = (struct wget_hashmap_iterator_st *) iter;
128
0
  struct wget_hashmap_st *h = _iter->h;
129
130
0
  if (_iter->entry) {
131
0
    if ((_iter->entry = _iter->entry->next)) {
132
0
found:
133
0
      if (value)
134
0
        *value = _iter->entry->value;
135
0
      return _iter->entry->key;
136
0
    }
137
138
0
    _iter->pos++;
139
0
  }
140
141
0
  if (!_iter->entry && h) {
142
0
    for (; _iter->pos < h->max; _iter->pos++) {
143
0
      if (h->entry[_iter->pos]) {
144
0
        _iter->entry = h->entry[_iter->pos];
145
0
        goto found;
146
0
      }
147
0
    }
148
0
  }
149
150
0
  return NULL;
151
0
}
152
153
/**
154
 * \param[in] max Initial number of pre-allocated entries
155
 * \param[in] hash Hash function to build hashes from elements
156
 * \param[in] cmp Comparison function used to find elements
157
 * \return New hashmap instance
158
 *
159
 * Create a new hashmap instance with initial size \p max.
160
 * It should be free'd after use with wget_hashmap_free().
161
 *
162
 * Before the first insertion of an element, \p hash and \p cmp must be set.
163
 * So if you use %NULL values here, you have to call wget_hashmap_setcmpfunc() and/or
164
 * wget_hashmap_hashcmpfunc() with appropriate function pointers. No doing so will result
165
 * in undefined behavior (likely you'll see a segmentation fault).
166
 */
167
wget_hashmap *wget_hashmap_create(int max, wget_hashmap_hash_fn *hash, wget_hashmap_compare_fn *cmp)
168
19.6k
{
169
19.6k
  wget_hashmap *h = wget_malloc(sizeof(wget_hashmap));
170
171
19.6k
  if (!h)
172
0
    return NULL;
173
174
19.6k
  h->entry = wget_calloc(max, sizeof(entry_t *));
175
176
19.6k
  if (!h->entry) {
177
0
    xfree(h);
178
0
    return NULL;
179
0
  }
180
181
19.6k
  h->max = max;
182
19.6k
  h->cur = 0;
183
19.6k
  h->resize_factor = 2;
184
19.6k
  h->hash = hash;
185
19.6k
  h->cmp = cmp;
186
19.6k
  h->key_destructor = free;
187
19.6k
  h->value_destructor = free;
188
19.6k
  h->load_factor = 0.75;
189
19.6k
  h->threshold = (int)(max * h->load_factor);
190
191
19.6k
  return h;
192
19.6k
}
193
194
WGET_GCC_NONNULL_ALL
195
static entry_t * hashmap_find_entry(const wget_hashmap *h, const char *key, unsigned int hash)
196
31.4k
{
197
46.8k
  for (entry_t * e = h->entry[hash % h->max]; e; e = e->next) {
198
20.0k
    if (hash == e->hash && (key == e->key || !h->cmp(key, e->key))) {
199
4.61k
      return e;
200
4.61k
    }
201
20.0k
  }
202
203
26.7k
  return NULL;
204
31.4k
}
205
206
WGET_GCC_NONNULL_ALL
207
static void hashmap_rehash(wget_hashmap *h, entry_t **new_entry, int newmax, int recalc_hash)
208
107
{
209
107
  entry_t *entry, *next;
210
107
  int cur = h->cur;
211
212
1.49k
  for (int it = 0; it < h->max && cur; it++) {
213
2.82k
    for (entry = h->entry[it]; entry; entry = next) {
214
1.44k
      next = entry->next;
215
216
      // now move entry from 'h' to 'new_hashmap'
217
1.44k
      if (recalc_hash)
218
0
        entry->hash = h->hash(entry->key);
219
1.44k
      int pos = entry->hash % newmax;
220
1.44k
      entry->next = new_entry[pos];
221
1.44k
      new_entry[pos] = entry;
222
223
1.44k
      cur--;
224
1.44k
    }
225
1.38k
  }
226
227
107
  xfree(h->entry);
228
107
  h->entry = new_entry;
229
107
  h->max = newmax;
230
107
  h->threshold = (int)(newmax * h->load_factor);
231
107
}
232
233
WGET_GCC_NONNULL((1,3))
234
static int hashmap_new_entry(wget_hashmap *h, unsigned int hash, const char *key, const char *value)
235
8.80k
{
236
8.80k
  entry_t *entry;
237
238
8.80k
  if (!(entry = wget_malloc(sizeof(entry_t))))
239
0
    return WGET_E_MEMORY;
240
241
8.80k
  int pos = hash % h->max;
242
243
8.80k
  entry->key = (void *)key;
244
8.80k
  entry->value = (void *)value;
245
8.80k
  entry->hash = hash;
246
8.80k
  entry->next = h->entry[pos];
247
8.80k
  h->entry[pos] = entry;
248
249
8.80k
  if (++h->cur >= h->threshold) {
250
107
    int newsize = (int) (h->max * h->resize_factor);
251
252
107
    if (newsize > 0) {
253
107
      entry_t **new_entry;
254
255
107
      if (!(new_entry = wget_calloc(newsize, sizeof(entry_t *)))) {
256
0
        h->cur--;
257
0
        xfree(h->entry[pos]);
258
0
        return WGET_E_MEMORY;
259
0
      }
260
261
      // h->cur is always > 0 here, so we don't need a check
262
107
      hashmap_rehash(h, new_entry, newsize, 0);
263
107
    }
264
107
  }
265
266
8.80k
  return WGET_E_SUCCESS;
267
8.80k
}
268
269
/**
270
 * \param[in] h Hashmap to put data into
271
 * \param[in] key Key to insert into \p h
272
 * \param[in] value Value to insert into \p h
273
 * \return 0 if inserted a new entry, 1 if entry existed, WGET_E_MEMORY if internal allocation failed
274
 *
275
 * Insert a key/value pair into hashmap \p h.
276
 *
277
 * \p key and \p value are *not* cloned, the hashmap takes 'ownership' of both.
278
 *
279
 * If \p key already exists and the pointer values the old and the new key differ,
280
 * the old key will be destroyed by calling the key destructor function (default is free()).
281
 *
282
 * To realize a hashset (just keys without values), \p value may be %NULL.
283
 *
284
 * Neither \p h nor \p key must be %NULL, else the return value will always be 0.
285
 */
286
int wget_hashmap_put(wget_hashmap *h, const void *key, const void *value)
287
11.2k
{
288
11.2k
  if (h && key) {
289
11.2k
    entry_t *entry;
290
11.2k
    unsigned int hash = h->hash(key);
291
11.2k
    int rc;
292
293
11.2k
    if ((entry = hashmap_find_entry(h, key, hash))) {
294
2.41k
      if (entry->key != key && entry->key != value) {
295
2.41k
        if (h->key_destructor)
296
2.41k
          h->key_destructor(entry->key);
297
2.41k
        if (entry->key == entry->value)
298
2.41k
          entry->value = NULL;
299
2.41k
      }
300
2.41k
      if (entry->value != value && entry->value != key) {
301
2.41k
        if (h->value_destructor)
302
2.41k
          h->value_destructor(entry->value);
303
2.41k
      }
304
305
2.41k
      entry->key = (void *) key;
306
2.41k
      entry->value = (void *) value;
307
308
2.41k
      return 1;
309
2.41k
    }
310
311
    // a new entry
312
8.80k
    if ((rc = hashmap_new_entry(h, hash, key, value)) < 0)
313
0
      return rc;
314
8.80k
  }
315
316
8.80k
  return 0;
317
11.2k
}
318
319
/**
320
 * \param[in] h Hashmap
321
 * \param[in] key Key to search for
322
 * \return 1 if \p key has been found, 0 if not found
323
 *
324
 * Check if \p key exists in \p h.
325
 */
326
int wget_hashmap_contains(const wget_hashmap *h, const void *key)
327
0
{
328
0
  return wget_hashmap_get(h, key, NULL);
329
0
}
330
331
/**
332
 * \param[in] h Hashmap
333
 * \param[in] key Key to search for
334
 * \param[out] value Value to be returned
335
 * \return 1 if \p key has been found, 0 if not found
336
 *
337
 * Get the value for a given key.
338
 *
339
 * Neither \p h nor \p key must be %NULL.
340
 */
341
#undef wget_hashmap_get
342
int wget_hashmap_get(const wget_hashmap *h, const void *key, void **value)
343
20.1k
{
344
20.1k
  if (h && key) {
345
20.1k
    entry_t *entry;
346
347
20.1k
    if ((entry = hashmap_find_entry(h, key, h->hash(key)))) {
348
2.20k
      if (value)
349
2.20k
        *value = entry->value;
350
2.20k
      return 1;
351
2.20k
    }
352
20.1k
  }
353
354
17.9k
  return 0;
355
20.1k
}
356
357
WGET_GCC_NONNULL_ALL
358
static int hashmap_remove_entry(wget_hashmap *h, const char *key, int free_kv)
359
1.00k
{
360
1.00k
  entry_t *entry, *next, *prev = NULL;
361
1.00k
  unsigned int hash = h->hash(key);
362
1.00k
  int pos = hash % h->max;
363
364
1.83k
  for (entry = h->entry[pos]; entry; prev = entry, entry = next) {
365
1.22k
    next = entry->next;
366
367
1.22k
    if (hash == entry->hash && (key == entry->key || !h->cmp(key, entry->key))) {
368
393
      if (prev)
369
182
        prev->next = next;
370
211
      else
371
211
        h->entry[pos] = next;
372
373
393
      if (free_kv) {
374
393
        if (h->key_destructor)
375
393
          h->key_destructor(entry->key);
376
393
        if (entry->value != entry->key) {
377
0
          if (h->value_destructor)
378
0
            h->value_destructor(entry->value);
379
0
        }
380
393
        entry->key = NULL;
381
393
        entry->value = NULL;
382
393
      }
383
393
      xfree(entry);
384
385
393
      h->cur--;
386
393
      return 1;
387
393
    }
388
1.22k
  }
389
390
611
  return 0;
391
1.00k
}
392
393
/**
394
 * \param[in] h Hashmap
395
 * \param[in] key Key to be removed
396
 * \return 1 if \p key has been removed, 0 if not found
397
 *
398
 * Remove \p key from hashmap \p h.
399
 *
400
 * If \p key is found, the key and value destructor functions are called
401
 * when removing the entry from the hashmap.
402
 */
403
int wget_hashmap_remove(wget_hashmap *h, const void *key)
404
1.00k
{
405
1.00k
  if (h && key)
406
1.00k
    return hashmap_remove_entry(h, key, 1);
407
0
  else
408
0
    return 0;
409
1.00k
}
410
411
/**
412
 * \param[in] h Hashmap
413
 * \param[in] key Key to be removed
414
 * \return 1 if \p key has been removed, 0 if not found
415
 *
416
 * Remove \p key from hashmap \p h.
417
 *
418
 * Key and value destructor functions are *not* called when removing the entry from the hashmap.
419
 */
420
int wget_hashmap_remove_nofree(wget_hashmap *h, const void *key)
421
0
{
422
0
  if (h && key)
423
0
    return hashmap_remove_entry(h, key, 0);
424
0
  else
425
0
    return 0;
426
0
}
427
428
/**
429
 * \param[in] h Hashmap to be free'd
430
 *
431
 * Remove all entries from hashmap \p h and free the hashmap instance.
432
 *
433
 * Key and value destructor functions are called for each entry in the hashmap.
434
 */
435
void wget_hashmap_free(wget_hashmap **h)
436
24.9k
{
437
24.9k
  if (h && *h) {
438
19.6k
    wget_hashmap_clear(*h);
439
19.6k
    xfree((*h)->entry);
440
19.6k
    xfree(*h);
441
19.6k
  }
442
24.9k
}
443
444
/**
445
 * \param[in] h Hashmap to be cleared
446
 *
447
 * Remove all entries from hashmap \p h.
448
 *
449
 * Key and value destructor functions are called for each entry in the hashmap.
450
 */
451
void wget_hashmap_clear(wget_hashmap *h)
452
19.6k
{
453
19.6k
  if (h) {
454
19.6k
    entry_t *entry, *next;
455
19.6k
    int it, cur = h->cur;
456
457
62.8k
    for (it = 0; it < h->max && cur; it++) {
458
51.5k
      for (entry = h->entry[it]; entry; entry = next) {
459
8.40k
        next = entry->next;
460
461
8.40k
        if (h->key_destructor)
462
8.40k
          h->key_destructor(entry->key);
463
464
        // free value if different from key
465
8.40k
        if (h->value_destructor) {
466
8.40k
          if (entry->value != entry->key || (entry->value == entry->key && !h->key_destructor))
467
0
            h->value_destructor(entry->value);
468
8.40k
        }
469
470
8.40k
        entry->key = NULL;
471
8.40k
        entry->value = NULL;
472
473
8.40k
        xfree(entry);
474
8.40k
        cur--;
475
8.40k
      }
476
43.1k
      h->entry[it] = NULL;
477
43.1k
    }
478
19.6k
    h->cur = 0;
479
19.6k
  }
480
19.6k
}
481
482
/**
483
 * \param[in] h Hashmap
484
 * \return Number of entries in hashmap \p h
485
 *
486
 * Return the number of entries in the hashmap \p h.
487
 */
488
int wget_hashmap_size(const wget_hashmap *h)
489
2.91k
{
490
2.91k
  return h ? h->cur : 0;
491
2.91k
}
492
493
/**
494
 * \param[in] h Hashmap
495
 * \param[in] browse Function to be called for each element of \p h
496
 * \param[in] ctx Context variable use as param to \p browse
497
 * \return Return value of the last call to \p browse
498
 *
499
 * Call function \p browse for each element of hashmap \p h or until \p browse
500
 * returns a value not equal to zero.
501
 *
502
 * \p browse is called with \p ctx and the pointer to the current element.
503
 *
504
 * The return value of the last call to \p browse is returned or 0 if either \p h or \p browse is %NULL.
505
 */
506
int wget_hashmap_browse(const wget_hashmap *h, wget_hashmap_browse_fn *browse, void *ctx)
507
0
{
508
0
  if (h && browse) {
509
0
    entry_t *entry;
510
0
    int it, ret, cur = h->cur;
511
512
0
    for (it = 0; it < h->max && cur; it++) {
513
0
      for (entry = h->entry[it]; entry; entry = entry->next) {
514
0
        if ((ret = browse(ctx, entry->key, entry->value)) != 0)
515
0
          return ret;
516
0
        cur--;
517
0
      }
518
0
    }
519
0
  }
520
521
0
  return 0;
522
0
}
523
524
/**
525
 * \param[in] h Hashmap
526
 * \param[in] cmp Comparison function used to find keys
527
 *
528
 * Set the comparison function.
529
 */
530
void wget_hashmap_setcmpfunc(wget_hashmap *h, wget_hashmap_compare_fn *cmp)
531
0
{
532
0
  if (h)
533
0
    h->cmp = cmp;
534
0
}
535
536
/**
537
 * \param[in] h Hashmap
538
 * \param[in] hash Hash function used to hash keys
539
 * \return WGET_E_SUCCESS if set successfully, else WGET_E_MEMORY or WGET_E_INVALID
540
 *
541
 * Set the key hash function.
542
 *
543
 * The keys of all entries in the hashmap will be hashed again. This includes a memory allocation, so
544
 * there is a possibility of failure.
545
 */
546
int wget_hashmap_sethashfunc(wget_hashmap *h, wget_hashmap_hash_fn *hash)
547
0
{
548
0
  if (!h)
549
0
    return WGET_E_INVALID;
550
551
0
  if (!h->cur)
552
0
    return WGET_E_SUCCESS; // no re-hashing needed
553
554
0
  entry_t **new_entry = wget_calloc(h->max, sizeof(entry_t *));
555
556
0
  if (!new_entry)
557
0
    return WGET_E_MEMORY;
558
559
0
  h->hash = hash;
560
0
  hashmap_rehash(h, new_entry, h->max, 1);
561
562
0
  return WGET_E_SUCCESS;
563
0
}
564
565
/**
566
 * \param[in] h Hashmap
567
 * \param[in] destructor Destructor function for keys
568
 *
569
 * Set the key destructor function.
570
 *
571
 * Default is free().
572
 */
573
void wget_hashmap_set_key_destructor(wget_hashmap *h, wget_hashmap_key_destructor *destructor)
574
19.6k
{
575
19.6k
  if (h)
576
19.6k
    h->key_destructor = destructor;
577
19.6k
}
578
579
/**
580
 * \param[in] h Hashmap
581
 * \param[in] destructor Destructor function for values
582
 *
583
 * Set the value destructor function.
584
 *
585
 * Default is free().
586
 */
587
void wget_hashmap_set_value_destructor(wget_hashmap *h, wget_hashmap_value_destructor *destructor)
588
17.8k
{
589
17.8k
  if (h)
590
17.8k
    h->value_destructor = destructor;
591
17.8k
}
592
593
/**
594
 * \param[in] h Hashmap
595
 * \param[in] factor The load factor
596
 *
597
 * Set the load factor function.
598
 *
599
 * The load factor is determines when to resize the internal memory.
600
 * 0.75 means "resize if 75% or more of all slots are used".
601
 *
602
 * The resize strategy is set by wget_hashmap_set_growth_policy().
603
 *
604
 * The resize (and rehashing) occurs earliest on the next insertion of a new key.
605
 *
606
 * Default is 0.75.
607
 */
608
void wget_hashmap_set_load_factor(wget_hashmap *h, float factor)
609
0
{
610
0
  if (h) {
611
0
    h->load_factor = factor;
612
0
    h->threshold = (int)(h->max * h->load_factor);
613
    // rehashing occurs earliest on next put()
614
0
  }
615
0
}
616
617
/**
618
 * \param[in] h Hashmap
619
 * \param[in] factor Hashmap growth factor
620
 *
621
 * Set the factor for resizing the hashmap when it's load factor is reached.
622
 *
623
 * The new size is 'factor * oldsize'. If the new size is less or equal 0,
624
 * the involved put function will do nothing and the internal state of
625
 * the hashmap will not change.
626
 *
627
 * Default is 2.
628
 */
629
void wget_hashmap_set_resize_factor(wget_hashmap *h, float factor)
630
0
{
631
0
  if (h)
632
0
    h->resize_factor = factor;
633
0
}
634
635
/**@}*/