]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/hashmap.c
path-util: make use of TAKE_PTR() where we can
[thirdparty/systemd.git] / src / basic / hashmap.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
a7334b09 2
60918275 3#include <errno.h>
11c3a366 4#include <stdint.h>
d4510856 5#include <stdlib.h>
60918275 6
b5efdb8a 7#include "alloc-util.h"
556c7bae 8#include "fileio.h"
b4f60743 9#include "hashmap.h"
60918275 10#include "macro.h"
0a970718 11#include "memory-util.h"
b3dcf58e 12#include "mempool.h"
f5947a5e 13#include "missing_syscall.h"
d4510856 14#include "process-util.h"
3df3e884 15#include "random-util.h"
d4510856
LP
16#include "set.h"
17#include "siphash24.h"
556c7bae 18#include "string-util.h"
d4510856 19#include "strv.h"
60918275 20
349cc4a5 21#if ENABLE_DEBUG_HASHMAP
3d4db144 22#include <pthread.h>
2eec67ac
TA
23#include "list.h"
24#endif
25
89439d4f
MS
26/*
27 * Implementation of hashmaps.
28 * Addressing: open
29 * - uses less RAM compared to closed addressing (chaining), because
30 * our entries are small (especially in Sets, which tend to contain
31 * the majority of entries in systemd).
32 * Collision resolution: Robin Hood
33 * - tends to equalize displacement of entries from their optimal buckets.
34 * Probe sequence: linear
35 * - though theoretically worse than random probing/uniform hashing/double
36 * hashing, it is good for cache locality.
37 *
38 * References:
39 * Celis, P. 1986. Robin Hood Hashing.
40 * Ph.D. Dissertation. University of Waterloo, Waterloo, Ont., Canada, Canada.
41 * https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf
42 * - The results are derived for random probing. Suggests deletion with
43 * tombstones and two mean-centered search methods. None of that works
44 * well for linear probing.
45 *
46 * Janson, S. 2005. Individual displacements for linear probing hashing with different insertion policies.
47 * ACM Trans. Algorithms 1, 2 (October 2005), 177-213.
48 * DOI=10.1145/1103963.1103964 http://doi.acm.org/10.1145/1103963.1103964
49 * http://www.math.uu.se/~svante/papers/sj157.pdf
50 * - Applies to Robin Hood with linear probing. Contains remarks on
51 * the unsuitability of mean-centered search with linear probing.
52 *
53 * Viola, A. 2005. Exact distribution of individual displacements in linear probing hashing.
54 * ACM Trans. Algorithms 1, 2 (October 2005), 214-242.
55 * DOI=10.1145/1103963.1103965 http://doi.acm.org/10.1145/1103963.1103965
56 * - Similar to Janson. Note that Viola writes about C_{m,n} (number of probes
57 * in a successful search), and Janson writes about displacement. C = d + 1.
58 *
59 * Goossaert, E. 2013. Robin Hood hashing: backward shift deletion.
60 * http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/
61 * - Explanation of backward shift deletion with pictures.
62 *
63 * Khuong, P. 2013. The Other Robin Hood Hashing.
64 * http://www.pvk.ca/Blog/2013/11/26/the-other-robin-hood-hashing/
65 * - Short summary of random vs. linear probing, and tombstones vs. backward shift.
66 */
67
68/*
69 * XXX Ideas for improvement:
70 * For unordered hashmaps, randomize iteration order, similarly to Perl:
71 * http://blog.booking.com/hardening-perls-hash-function.html
72 */
73
74/* INV_KEEP_FREE = 1 / (1 - max_load_factor)
75 * e.g. 1 / (1 - 0.8) = 5 ... keep one fifth of the buckets free. */
76#define INV_KEEP_FREE 5U
77
78/* Fields common to entries of all hashmap/set types */
79struct hashmap_base_entry {
60918275 80 const void *key;
89439d4f
MS
81};
82
83/* Entry types for specific hashmap/set types
84 * hashmap_base_entry must be at the beginning of each entry struct. */
85
86struct plain_hashmap_entry {
87 struct hashmap_base_entry b;
60918275 88 void *value;
60918275
LP
89};
90
89439d4f
MS
91struct ordered_hashmap_entry {
92 struct plain_hashmap_entry p;
93 unsigned iterate_next, iterate_previous;
94};
60918275 95
89439d4f
MS
96struct set_entry {
97 struct hashmap_base_entry b;
98};
45fa9e29 99
89439d4f
MS
100/* In several functions it is advantageous to have the hash table extended
101 * virtually by a couple of additional buckets. We reserve special index values
102 * for these "swap" buckets. */
103#define _IDX_SWAP_BEGIN (UINT_MAX - 3)
104#define IDX_PUT (_IDX_SWAP_BEGIN + 0)
105#define IDX_TMP (_IDX_SWAP_BEGIN + 1)
106#define _IDX_SWAP_END (_IDX_SWAP_BEGIN + 2)
39c2a6f1 107
89439d4f
MS
108#define IDX_FIRST (UINT_MAX - 1) /* special index for freshly initialized iterators */
109#define IDX_NIL UINT_MAX /* special index value meaning "none" or "end" */
110
111assert_cc(IDX_FIRST == _IDX_SWAP_END);
112assert_cc(IDX_FIRST == _IDX_ITERATOR_FIRST);
113
114/* Storage space for the "swap" buckets.
115 * All entry types can fit into a ordered_hashmap_entry. */
116struct swap_entries {
117 struct ordered_hashmap_entry e[_IDX_SWAP_END - _IDX_SWAP_BEGIN];
60918275
LP
118};
119
89439d4f
MS
120/* Distance from Initial Bucket */
121typedef uint8_t dib_raw_t;
3ef11dcf
ZJS
122#define DIB_RAW_OVERFLOW ((dib_raw_t)0xfdU) /* indicates DIB value is greater than representable */
123#define DIB_RAW_REHASH ((dib_raw_t)0xfeU) /* entry yet to be rehashed during in-place resize */
124#define DIB_RAW_FREE ((dib_raw_t)0xffU) /* a free bucket */
125#define DIB_RAW_INIT ((char)DIB_RAW_FREE) /* a byte to memset a DIB store with when initializing */
89439d4f
MS
126
127#define DIB_FREE UINT_MAX
128
349cc4a5 129#if ENABLE_DEBUG_HASHMAP
89439d4f
MS
130struct hashmap_debug_info {
131 LIST_FIELDS(struct hashmap_debug_info, debug_list);
132 unsigned max_entries; /* high watermark of n_entries */
133
134 /* who allocated this hashmap */
135 int line;
136 const char *file;
137 const char *func;
138
139 /* fields to detect modification while iterating */
140 unsigned put_count; /* counts puts into the hashmap */
141 unsigned rem_count; /* counts removals from hashmap */
142 unsigned last_rem_idx; /* remembers last removal index */
39c2a6f1
LP
143};
144
89439d4f
MS
145/* Tracks all existing hashmaps. Get at it from gdb. See sd_dump_hashmaps.py */
146static LIST_HEAD(struct hashmap_debug_info, hashmap_debug_list);
4f1b3061 147static pthread_mutex_t hashmap_debug_list_mutex = PTHREAD_MUTEX_INITIALIZER;
55825de5 148#endif
39c2a6f1 149
89439d4f
MS
150enum HashmapType {
151 HASHMAP_TYPE_PLAIN,
152 HASHMAP_TYPE_ORDERED,
153 HASHMAP_TYPE_SET,
154 _HASHMAP_TYPE_MAX
155};
39c2a6f1 156
89439d4f 157struct _packed_ indirect_storage {
1a39bc8c 158 void *storage; /* where buckets and DIBs are stored */
89439d4f
MS
159 uint8_t hash_key[HASH_KEY_SIZE]; /* hash key; changes during resize */
160
161 unsigned n_entries; /* number of stored entries */
162 unsigned n_buckets; /* number of buckets */
163
164 unsigned idx_lowest_entry; /* Index below which all buckets are free.
165 Makes "while(hashmap_steal_first())" loops
166 O(n) instead of O(n^2) for unordered hashmaps. */
167 uint8_t _pad[3]; /* padding for the whole HashmapBase */
168 /* The bitfields in HashmapBase complete the alignment of the whole thing. */
169};
170
171struct direct_storage {
172 /* This gives us 39 bytes on 64bit, or 35 bytes on 32bit.
173 * That's room for 4 set_entries + 4 DIB bytes + 3 unused bytes on 64bit,
174 * or 7 set_entries + 7 DIB bytes + 0 unused bytes on 32bit. */
1a39bc8c 175 uint8_t storage[sizeof(struct indirect_storage)];
89439d4f
MS
176};
177
178#define DIRECT_BUCKETS(entry_t) \
179 (sizeof(struct direct_storage) / (sizeof(entry_t) + sizeof(dib_raw_t)))
180
181/* We should be able to store at least one entry directly. */
182assert_cc(DIRECT_BUCKETS(struct ordered_hashmap_entry) >= 1);
183
184/* We have 3 bits for n_direct_entries. */
185assert_cc(DIRECT_BUCKETS(struct set_entry) < (1 << 3));
186
187/* Hashmaps with directly stored entries all use this shared hash key.
188 * It's no big deal if the key is guessed, because there can be only
189 * a handful of directly stored entries in a hashmap. When a hashmap
190 * outgrows direct storage, it gets its own key for indirect storage. */
191static uint8_t shared_hash_key[HASH_KEY_SIZE];
192static bool shared_hash_key_initialized;
193
194/* Fields that all hashmap/set types must have */
195struct HashmapBase {
196 const struct hash_ops *hash_ops; /* hash and compare ops to use */
197
198 union _packed_ {
199 struct indirect_storage indirect; /* if has_indirect */
200 struct direct_storage direct; /* if !has_indirect */
201 };
202
203 enum HashmapType type:2; /* HASHMAP_TYPE_* */
204 bool has_indirect:1; /* whether indirect storage is used */
205 unsigned n_direct_entries:3; /* Number of entries in direct storage.
206 * Only valid if !has_indirect. */
207 bool from_pool:1; /* whether was allocated from mempool */
45ea84d8
VC
208 bool dirty:1; /* whether dirtied since last iterated_cache_get() */
209 bool cached:1; /* whether this hashmap is being cached */
55825de5
ZJS
210
211#if ENABLE_DEBUG_HASHMAP
212 struct hashmap_debug_info debug;
213#endif
89439d4f
MS
214};
215
216/* Specific hash types
217 * HashmapBase must be at the beginning of each hashmap struct. */
218
219struct Hashmap {
220 struct HashmapBase b;
221};
222
223struct OrderedHashmap {
224 struct HashmapBase b;
225 unsigned iterate_list_head, iterate_list_tail;
226};
227
228struct Set {
229 struct HashmapBase b;
230};
231
45ea84d8
VC
232typedef struct CacheMem {
233 const void **ptr;
234 size_t n_populated, n_allocated;
235 bool active:1;
236} CacheMem;
237
238struct IteratedCache {
239 HashmapBase *hashmap;
240 CacheMem keys, values;
241};
242
89439d4f
MS
243DEFINE_MEMPOOL(hashmap_pool, Hashmap, 8);
244DEFINE_MEMPOOL(ordered_hashmap_pool, OrderedHashmap, 8);
245/* No need for a separate Set pool */
246assert_cc(sizeof(Hashmap) == sizeof(Set));
247
248struct hashmap_type_info {
249 size_t head_size;
250 size_t entry_size;
251 struct mempool *mempool;
252 unsigned n_direct_buckets;
253};
254
43874aa7 255static _used_ const struct hashmap_type_info hashmap_type_info[_HASHMAP_TYPE_MAX] = {
89439d4f
MS
256 [HASHMAP_TYPE_PLAIN] = {
257 .head_size = sizeof(Hashmap),
258 .entry_size = sizeof(struct plain_hashmap_entry),
259 .mempool = &hashmap_pool,
260 .n_direct_buckets = DIRECT_BUCKETS(struct plain_hashmap_entry),
261 },
262 [HASHMAP_TYPE_ORDERED] = {
263 .head_size = sizeof(OrderedHashmap),
264 .entry_size = sizeof(struct ordered_hashmap_entry),
265 .mempool = &ordered_hashmap_pool,
266 .n_direct_buckets = DIRECT_BUCKETS(struct ordered_hashmap_entry),
267 },
268 [HASHMAP_TYPE_SET] = {
269 .head_size = sizeof(Set),
270 .entry_size = sizeof(struct set_entry),
271 .mempool = &hashmap_pool,
272 .n_direct_buckets = DIRECT_BUCKETS(struct set_entry),
273 },
274};
39c2a6f1 275
d18cb393 276#if VALGRIND
d34dae18 277_destructor_ static void cleanup_pools(void) {
556c7bae
ZJS
278 _cleanup_free_ char *t = NULL;
279 int r;
280
281 /* Be nice to valgrind */
282
283 /* The pool is only allocated by the main thread, but the memory can
284 * be passed to other threads. Let's clean up if we are the main thread
285 * and no other threads are live. */
31c9d74d
FS
286 /* We build our own is_main_thread() here, which doesn't use C11
287 * TLS based caching of the result. That's because valgrind apparently
288 * doesn't like malloc() (which C11 TLS internally uses) to be called
289 * from a GCC destructors. */
290 if (getpid() != gettid())
556c7bae
ZJS
291 return;
292
293 r = get_proc_field("/proc/self/status", "Threads", WHITESPACE, &t);
294 if (r < 0 || !streq(t, "1"))
295 return;
296
297 mempool_drop(&hashmap_pool);
298 mempool_drop(&ordered_hashmap_pool);
299}
300#endif
301
89439d4f
MS
302static unsigned n_buckets(HashmapBase *h) {
303 return h->has_indirect ? h->indirect.n_buckets
304 : hashmap_type_info[h->type].n_direct_buckets;
305}
306
307static unsigned n_entries(HashmapBase *h) {
308 return h->has_indirect ? h->indirect.n_entries
309 : h->n_direct_entries;
310}
311
312static void n_entries_inc(HashmapBase *h) {
313 if (h->has_indirect)
314 h->indirect.n_entries++;
315 else
316 h->n_direct_entries++;
317}
318
319static void n_entries_dec(HashmapBase *h) {
320 if (h->has_indirect)
321 h->indirect.n_entries--;
322 else
323 h->n_direct_entries--;
324}
325
1a39bc8c 326static void *storage_ptr(HashmapBase *h) {
89439d4f
MS
327 return h->has_indirect ? h->indirect.storage
328 : h->direct.storage;
329}
330
331static uint8_t *hash_key(HashmapBase *h) {
332 return h->has_indirect ? h->indirect.hash_key
333 : shared_hash_key;
334}
335
336static unsigned base_bucket_hash(HashmapBase *h, const void *p) {
b826ab58 337 struct siphash state;
0cb3c286 338 uint64_t hash;
b826ab58 339
0cb3c286 340 siphash24_init(&state, hash_key(h));
b826ab58
TG
341
342 h->hash_ops->hash(p, &state);
343
933f9cae 344 hash = siphash24_finalize(&state);
0cb3c286
TG
345
346 return (unsigned) (hash % n_buckets(h));
9bf3b535 347}
89439d4f 348#define bucket_hash(h, p) base_bucket_hash(HASHMAP_BASE(h), p)
9bf3b535 349
a1e92eee 350static void base_set_dirty(HashmapBase *h) {
84dcca75
VC
351 h->dirty = true;
352}
353#define hashmap_set_dirty(h) base_set_dirty(HASHMAP_BASE(h))
354
9bf3b535
LP
355static void get_hash_key(uint8_t hash_key[HASH_KEY_SIZE], bool reuse_is_ok) {
356 static uint8_t current[HASH_KEY_SIZE];
357 static bool current_initialized = false;
358
359 /* Returns a hash function key to use. In order to keep things
360 * fast we will not generate a new key each time we allocate a
361 * new hash table. Instead, we'll just reuse the most recently
362 * generated one, except if we never generated one or when we
363 * are rehashing an entire hash table because we reached a
364 * fill level */
365
366 if (!current_initialized || !reuse_is_ok) {
367 random_bytes(current, sizeof(current));
368 current_initialized = true;
369 }
370
371 memcpy(hash_key, current, sizeof(current));
a3b6fafe
LP
372}
373
89439d4f
MS
374static struct hashmap_base_entry *bucket_at(HashmapBase *h, unsigned idx) {
375 return (struct hashmap_base_entry*)
1a39bc8c 376 ((uint8_t*) storage_ptr(h) + idx * hashmap_type_info[h->type].entry_size);
89439d4f
MS
377}
378
379static struct plain_hashmap_entry *plain_bucket_at(Hashmap *h, unsigned idx) {
380 return (struct plain_hashmap_entry*) bucket_at(HASHMAP_BASE(h), idx);
381}
382
383static struct ordered_hashmap_entry *ordered_bucket_at(OrderedHashmap *h, unsigned idx) {
384 return (struct ordered_hashmap_entry*) bucket_at(HASHMAP_BASE(h), idx);
385}
39c2a6f1 386
89439d4f
MS
387static struct set_entry *set_bucket_at(Set *h, unsigned idx) {
388 return (struct set_entry*) bucket_at(HASHMAP_BASE(h), idx);
389}
39c2a6f1 390
89439d4f
MS
391static struct ordered_hashmap_entry *bucket_at_swap(struct swap_entries *swap, unsigned idx) {
392 return &swap->e[idx - _IDX_SWAP_BEGIN];
393}
39c2a6f1 394
89439d4f
MS
395/* Returns a pointer to the bucket at index idx.
396 * Understands real indexes and swap indexes, hence "_virtual". */
397static struct hashmap_base_entry *bucket_at_virtual(HashmapBase *h, struct swap_entries *swap,
398 unsigned idx) {
399 if (idx < _IDX_SWAP_BEGIN)
400 return bucket_at(h, idx);
401
402 if (idx < _IDX_SWAP_END)
403 return &bucket_at_swap(swap, idx)->p.b;
404
405 assert_not_reached("Invalid index");
406}
407
408static dib_raw_t *dib_raw_ptr(HashmapBase *h) {
409 return (dib_raw_t*)
1a39bc8c 410 ((uint8_t*) storage_ptr(h) + hashmap_type_info[h->type].entry_size * n_buckets(h));
89439d4f
MS
411}
412
413static unsigned bucket_distance(HashmapBase *h, unsigned idx, unsigned from) {
414 return idx >= from ? idx - from
415 : n_buckets(h) + idx - from;
416}
417
418static unsigned bucket_calculate_dib(HashmapBase *h, unsigned idx, dib_raw_t raw_dib) {
419 unsigned initial_bucket;
420
421 if (raw_dib == DIB_RAW_FREE)
422 return DIB_FREE;
423
424 if (_likely_(raw_dib < DIB_RAW_OVERFLOW))
425 return raw_dib;
426
427 /*
428 * Having an overflow DIB value is very unlikely. The hash function
429 * would have to be bad. For example, in a table of size 2^24 filled
430 * to load factor 0.9 the maximum observed DIB is only about 60.
431 * In theory (assuming I used Maxima correctly), for an infinite size
432 * hash table with load factor 0.8 the probability of a given entry
433 * having DIB > 40 is 1.9e-8.
434 * This returns the correct DIB value by recomputing the hash value in
435 * the unlikely case. XXX Hitting this case could be a hint to rehash.
436 */
437 initial_bucket = bucket_hash(h, bucket_at(h, idx)->key);
438 return bucket_distance(h, idx, initial_bucket);
439}
440
441static void bucket_set_dib(HashmapBase *h, unsigned idx, unsigned dib) {
442 dib_raw_ptr(h)[idx] = dib != DIB_FREE ? MIN(dib, DIB_RAW_OVERFLOW) : DIB_RAW_FREE;
443}
444
445static unsigned skip_free_buckets(HashmapBase *h, unsigned idx) {
446 dib_raw_t *dibs;
447
448 dibs = dib_raw_ptr(h);
449
450 for ( ; idx < n_buckets(h); idx++)
451 if (dibs[idx] != DIB_RAW_FREE)
452 return idx;
453
454 return IDX_NIL;
455}
456
457static void bucket_mark_free(HashmapBase *h, unsigned idx) {
eccaf899 458 memzero(bucket_at(h, idx), hashmap_type_info[h->type].entry_size);
89439d4f
MS
459 bucket_set_dib(h, idx, DIB_FREE);
460}
461
462static void bucket_move_entry(HashmapBase *h, struct swap_entries *swap,
463 unsigned from, unsigned to) {
464 struct hashmap_base_entry *e_from, *e_to;
465
466 assert(from != to);
39c2a6f1 467
89439d4f
MS
468 e_from = bucket_at_virtual(h, swap, from);
469 e_to = bucket_at_virtual(h, swap, to);
470
471 memcpy(e_to, e_from, hashmap_type_info[h->type].entry_size);
472
473 if (h->type == HASHMAP_TYPE_ORDERED) {
474 OrderedHashmap *lh = (OrderedHashmap*) h;
475 struct ordered_hashmap_entry *le, *le_to;
476
477 le_to = (struct ordered_hashmap_entry*) e_to;
478
479 if (le_to->iterate_next != IDX_NIL) {
480 le = (struct ordered_hashmap_entry*)
481 bucket_at_virtual(h, swap, le_to->iterate_next);
482 le->iterate_previous = to;
483 }
484
485 if (le_to->iterate_previous != IDX_NIL) {
486 le = (struct ordered_hashmap_entry*)
487 bucket_at_virtual(h, swap, le_to->iterate_previous);
488 le->iterate_next = to;
489 }
490
491 if (lh->iterate_list_head == from)
492 lh->iterate_list_head = to;
493 if (lh->iterate_list_tail == from)
494 lh->iterate_list_tail = to;
39c2a6f1 495 }
89439d4f 496}
60918275 497
89439d4f
MS
498static unsigned next_idx(HashmapBase *h, unsigned idx) {
499 return (idx + 1U) % n_buckets(h);
500}
60918275 501
89439d4f
MS
502static unsigned prev_idx(HashmapBase *h, unsigned idx) {
503 return (n_buckets(h) + idx - 1U) % n_buckets(h);
504}
60918275 505
89439d4f
MS
506static void *entry_value(HashmapBase *h, struct hashmap_base_entry *e) {
507 switch (h->type) {
45fa9e29 508
89439d4f
MS
509 case HASHMAP_TYPE_PLAIN:
510 case HASHMAP_TYPE_ORDERED:
511 return ((struct plain_hashmap_entry*)e)->value;
39c2a6f1 512
89439d4f
MS
513 case HASHMAP_TYPE_SET:
514 return (void*) e->key;
a3b6fafe 515
89439d4f
MS
516 default:
517 assert_not_reached("Unknown hashmap type");
518 }
60918275
LP
519}
520
89439d4f
MS
521static void base_remove_entry(HashmapBase *h, unsigned idx) {
522 unsigned left, right, prev, dib;
523 dib_raw_t raw_dib, *dibs;
45fa9e29 524
89439d4f
MS
525 dibs = dib_raw_ptr(h);
526 assert(dibs[idx] != DIB_RAW_FREE);
034c6ed7 527
349cc4a5 528#if ENABLE_DEBUG_HASHMAP
89439d4f
MS
529 h->debug.rem_count++;
530 h->debug.last_rem_idx = idx;
531#endif
034c6ed7 532
89439d4f
MS
533 left = idx;
534 /* Find the stop bucket ("right"). It is either free or has DIB == 0. */
535 for (right = next_idx(h, left); ; right = next_idx(h, right)) {
536 raw_dib = dibs[right];
4c701096 537 if (IN_SET(raw_dib, 0, DIB_RAW_FREE))
89439d4f
MS
538 break;
539
540 /* The buckets are not supposed to be all occupied and with DIB > 0.
541 * That would mean we could make everyone better off by shifting them
542 * backward. This scenario is impossible. */
543 assert(left != right);
544 }
034c6ed7 545
89439d4f
MS
546 if (h->type == HASHMAP_TYPE_ORDERED) {
547 OrderedHashmap *lh = (OrderedHashmap*) h;
548 struct ordered_hashmap_entry *le = ordered_bucket_at(lh, idx);
549
550 if (le->iterate_next != IDX_NIL)
551 ordered_bucket_at(lh, le->iterate_next)->iterate_previous = le->iterate_previous;
552 else
553 lh->iterate_list_tail = le->iterate_previous;
554
555 if (le->iterate_previous != IDX_NIL)
556 ordered_bucket_at(lh, le->iterate_previous)->iterate_next = le->iterate_next;
557 else
558 lh->iterate_list_head = le->iterate_next;
559 }
560
561 /* Now shift all buckets in the interval (left, right) one step backwards */
562 for (prev = left, left = next_idx(h, left); left != right;
563 prev = left, left = next_idx(h, left)) {
564 dib = bucket_calculate_dib(h, left, dibs[left]);
565 assert(dib != 0);
566 bucket_move_entry(h, NULL, left, prev);
567 bucket_set_dib(h, prev, dib - 1);
568 }
569
570 bucket_mark_free(h, prev);
571 n_entries_dec(h);
84dcca75 572 base_set_dirty(h);
034c6ed7 573}
89439d4f
MS
574#define remove_entry(h, idx) base_remove_entry(HASHMAP_BASE(h), idx)
575
576static unsigned hashmap_iterate_in_insertion_order(OrderedHashmap *h, Iterator *i) {
577 struct ordered_hashmap_entry *e;
578 unsigned idx;
034c6ed7 579
101d8e63 580 assert(h);
89439d4f
MS
581 assert(i);
582
583 if (i->idx == IDX_NIL)
584 goto at_end;
585
586 if (i->idx == IDX_FIRST && h->iterate_list_head == IDX_NIL)
587 goto at_end;
588
589 if (i->idx == IDX_FIRST) {
590 idx = h->iterate_list_head;
591 e = ordered_bucket_at(h, idx);
101d8e63 592 } else {
89439d4f
MS
593 idx = i->idx;
594 e = ordered_bucket_at(h, idx);
595 /*
596 * We allow removing the current entry while iterating, but removal may cause
597 * a backward shift. The next entry may thus move one bucket to the left.
598 * To detect when it happens, we remember the key pointer of the entry we were
599 * going to iterate next. If it does not match, there was a backward shift.
600 */
601 if (e->p.b.key != i->next_key) {
602 idx = prev_idx(HASHMAP_BASE(h), idx);
603 e = ordered_bucket_at(h, idx);
604 }
605 assert(e->p.b.key == i->next_key);
101d8e63 606 }
101d8e63 607
349cc4a5 608#if ENABLE_DEBUG_HASHMAP
89439d4f
MS
609 i->prev_idx = idx;
610#endif
611
612 if (e->iterate_next != IDX_NIL) {
613 struct ordered_hashmap_entry *n;
614 i->idx = e->iterate_next;
615 n = ordered_bucket_at(h, i->idx);
616 i->next_key = n->p.b.key;
617 } else
618 i->idx = IDX_NIL;
619
620 return idx;
621
622at_end:
623 i->idx = IDX_NIL;
624 return IDX_NIL;
101d8e63
LP
625}
626
89439d4f
MS
627static unsigned hashmap_iterate_in_internal_order(HashmapBase *h, Iterator *i) {
628 unsigned idx;
629
60918275 630 assert(h);
89439d4f 631 assert(i);
60918275 632
89439d4f
MS
633 if (i->idx == IDX_NIL)
634 goto at_end;
60918275 635
89439d4f
MS
636 if (i->idx == IDX_FIRST) {
637 /* fast forward to the first occupied bucket */
638 if (h->has_indirect) {
639 i->idx = skip_free_buckets(h, h->indirect.idx_lowest_entry);
640 h->indirect.idx_lowest_entry = i->idx;
641 } else
642 i->idx = skip_free_buckets(h, 0);
643
644 if (i->idx == IDX_NIL)
645 goto at_end;
646 } else {
647 struct hashmap_base_entry *e;
648
649 assert(i->idx > 0);
60918275 650
89439d4f
MS
651 e = bucket_at(h, i->idx);
652 /*
653 * We allow removing the current entry while iterating, but removal may cause
654 * a backward shift. The next entry may thus move one bucket to the left.
655 * To detect when it happens, we remember the key pointer of the entry we were
656 * going to iterate next. If it does not match, there was a backward shift.
657 */
658 if (e->key != i->next_key)
659 e = bucket_at(h, --i->idx);
60918275 660
89439d4f
MS
661 assert(e->key == i->next_key);
662 }
663
664 idx = i->idx;
349cc4a5 665#if ENABLE_DEBUG_HASHMAP
89439d4f
MS
666 i->prev_idx = idx;
667#endif
668
669 i->idx = skip_free_buckets(h, i->idx + 1);
670 if (i->idx != IDX_NIL)
671 i->next_key = bucket_at(h, i->idx)->key;
101d8e63 672 else
89439d4f
MS
673 i->idx = IDX_NIL;
674
675 return idx;
60918275 676
89439d4f
MS
677at_end:
678 i->idx = IDX_NIL;
679 return IDX_NIL;
60918275
LP
680}
681
89439d4f
MS
682static unsigned hashmap_iterate_entry(HashmapBase *h, Iterator *i) {
683 if (!h) {
684 i->idx = IDX_NIL;
685 return IDX_NIL;
686 }
101d8e63 687
349cc4a5 688#if ENABLE_DEBUG_HASHMAP
89439d4f
MS
689 if (i->idx == IDX_FIRST) {
690 i->put_count = h->debug.put_count;
691 i->rem_count = h->debug.rem_count;
692 } else {
693 /* While iterating, must not add any new entries */
694 assert(i->put_count == h->debug.put_count);
695 /* ... or remove entries other than the current one */
696 assert(i->rem_count == h->debug.rem_count ||
697 (i->rem_count == h->debug.rem_count - 1 &&
698 i->prev_idx == h->debug.last_rem_idx));
699 /* Reset our removals counter */
700 i->rem_count = h->debug.rem_count;
701 }
702#endif
101d8e63 703
89439d4f
MS
704 return h->type == HASHMAP_TYPE_ORDERED ? hashmap_iterate_in_insertion_order((OrderedHashmap*) h, i)
705 : hashmap_iterate_in_internal_order(h, i);
706}
39c2a6f1 707
138f49e4 708bool _hashmap_iterate(HashmapBase *h, Iterator *i, void **value, const void **key) {
89439d4f
MS
709 struct hashmap_base_entry *e;
710 void *data;
711 unsigned idx;
712
713 idx = hashmap_iterate_entry(h, i);
714 if (idx == IDX_NIL) {
8927b1da
DH
715 if (value)
716 *value = NULL;
89439d4f
MS
717 if (key)
718 *key = NULL;
719
8927b1da 720 return false;
89439d4f
MS
721 }
722
723 e = bucket_at(h, idx);
724 data = entry_value(h, e);
8927b1da
DH
725 if (value)
726 *value = data;
89439d4f
MS
727 if (key)
728 *key = e->key;
729
8927b1da 730 return true;
101d8e63
LP
731}
732
3c4e3031 733bool set_iterate(const Set *s, Iterator *i, void **value) {
138f49e4 734 return _hashmap_iterate(HASHMAP_BASE((Set*) s), i, value, NULL);
89439d4f 735}
60918275 736
89439d4f
MS
737#define HASHMAP_FOREACH_IDX(idx, h, i) \
738 for ((i) = ITERATOR_FIRST, (idx) = hashmap_iterate_entry((h), &(i)); \
739 (idx != IDX_NIL); \
740 (idx) = hashmap_iterate_entry((h), &(i)))
741
138f49e4 742IteratedCache *_hashmap_iterated_cache_new(HashmapBase *h) {
45ea84d8
VC
743 IteratedCache *cache;
744
745 assert(h);
746 assert(!h->cached);
747
748 if (h->cached)
749 return NULL;
750
751 cache = new0(IteratedCache, 1);
752 if (!cache)
753 return NULL;
754
755 cache->hashmap = h;
756 h->cached = true;
757
758 return cache;
759}
760
89439d4f
MS
761static void reset_direct_storage(HashmapBase *h) {
762 const struct hashmap_type_info *hi = &hashmap_type_info[h->type];
763 void *p;
764
765 assert(!h->has_indirect);
766
767 p = mempset(h->direct.storage, 0, hi->entry_size * hi->n_direct_buckets);
768 memset(p, DIB_RAW_INIT, sizeof(dib_raw_t) * hi->n_direct_buckets);
769}
770
add74e89 771static struct HashmapBase *hashmap_base_new(const struct hash_ops *hash_ops, enum HashmapType type HASHMAP_DEBUG_PARAMS) {
89439d4f
MS
772 HashmapBase *h;
773 const struct hashmap_type_info *hi = &hashmap_type_info[type];
b4f60743 774 bool up;
89439d4f 775
7c48ea02 776 up = mempool_enabled();
67f3c402 777
b4f60743 778 h = up ? mempool_alloc0_tile(hi->mempool) : malloc0(hi->head_size);
60918275 779 if (!h)
89439d4f
MS
780 return NULL;
781
782 h->type = type;
b4f60743 783 h->from_pool = up;
70b400d9 784 h->hash_ops = hash_ops ?: &trivial_hash_ops;
89439d4f
MS
785
786 if (type == HASHMAP_TYPE_ORDERED) {
787 OrderedHashmap *lh = (OrderedHashmap*)h;
788 lh->iterate_list_head = lh->iterate_list_tail = IDX_NIL;
789 }
790
791 reset_direct_storage(h);
60918275 792
89439d4f
MS
793 if (!shared_hash_key_initialized) {
794 random_bytes(shared_hash_key, sizeof(shared_hash_key));
795 shared_hash_key_initialized= true;
796 }
797
349cc4a5 798#if ENABLE_DEBUG_HASHMAP
89439d4f
MS
799 h->debug.func = func;
800 h->debug.file = file;
801 h->debug.line = line;
4f1b3061
TG
802 assert_se(pthread_mutex_lock(&hashmap_debug_list_mutex) == 0);
803 LIST_PREPEND(debug_list, hashmap_debug_list, &h->debug);
804 assert_se(pthread_mutex_unlock(&hashmap_debug_list_mutex) == 0);
89439d4f
MS
805#endif
806
807 return h;
808}
60918275 809
138f49e4 810Hashmap *_hashmap_new(const struct hash_ops *hash_ops HASHMAP_DEBUG_PARAMS) {
add74e89 811 return (Hashmap*) hashmap_base_new(hash_ops, HASHMAP_TYPE_PLAIN HASHMAP_DEBUG_PASS_ARGS);
89439d4f
MS
812}
813
138f49e4 814OrderedHashmap *_ordered_hashmap_new(const struct hash_ops *hash_ops HASHMAP_DEBUG_PARAMS) {
add74e89 815 return (OrderedHashmap*) hashmap_base_new(hash_ops, HASHMAP_TYPE_ORDERED HASHMAP_DEBUG_PASS_ARGS);
89439d4f
MS
816}
817
138f49e4 818Set *_set_new(const struct hash_ops *hash_ops HASHMAP_DEBUG_PARAMS) {
add74e89 819 return (Set*) hashmap_base_new(hash_ops, HASHMAP_TYPE_SET HASHMAP_DEBUG_PASS_ARGS);
89439d4f
MS
820}
821
822static int hashmap_base_ensure_allocated(HashmapBase **h, const struct hash_ops *hash_ops,
add74e89 823 enum HashmapType type HASHMAP_DEBUG_PARAMS) {
89439d4f
MS
824 HashmapBase *q;
825
826 assert(h);
827
828 if (*h)
829 return 0;
830
add74e89 831 q = hashmap_base_new(hash_ops, type HASHMAP_DEBUG_PASS_ARGS);
89439d4f
MS
832 if (!q)
833 return -ENOMEM;
834
835 *h = q;
9ff7c5b0 836 return 1;
89439d4f
MS
837}
838
138f49e4 839int _hashmap_ensure_allocated(Hashmap **h, const struct hash_ops *hash_ops HASHMAP_DEBUG_PARAMS) {
add74e89 840 return hashmap_base_ensure_allocated((HashmapBase**)h, hash_ops, HASHMAP_TYPE_PLAIN HASHMAP_DEBUG_PASS_ARGS);
89439d4f
MS
841}
842
138f49e4 843int _ordered_hashmap_ensure_allocated(OrderedHashmap **h, const struct hash_ops *hash_ops HASHMAP_DEBUG_PARAMS) {
add74e89 844 return hashmap_base_ensure_allocated((HashmapBase**)h, hash_ops, HASHMAP_TYPE_ORDERED HASHMAP_DEBUG_PASS_ARGS);
89439d4f
MS
845}
846
138f49e4 847int _set_ensure_allocated(Set **s, const struct hash_ops *hash_ops HASHMAP_DEBUG_PARAMS) {
add74e89 848 return hashmap_base_ensure_allocated((HashmapBase**)s, hash_ops, HASHMAP_TYPE_SET HASHMAP_DEBUG_PASS_ARGS);
89439d4f
MS
849}
850
851static void hashmap_free_no_clear(HashmapBase *h) {
852 assert(!h->has_indirect);
ee05335f 853 assert(h->n_direct_entries == 0);
89439d4f 854
349cc4a5 855#if ENABLE_DEBUG_HASHMAP
4f1b3061 856 assert_se(pthread_mutex_lock(&hashmap_debug_list_mutex) == 0);
89439d4f 857 LIST_REMOVE(debug_list, hashmap_debug_list, &h->debug);
4f1b3061 858 assert_se(pthread_mutex_unlock(&hashmap_debug_list_mutex) == 0);
89439d4f 859#endif
45fa9e29 860
205c085b
LP
861 if (h->from_pool) {
862 /* Ensure that the object didn't get migrated between threads. */
863 assert_se(is_main_thread());
89439d4f 864 mempool_free_tile(hashmap_type_info[h->type].mempool, h);
205c085b 865 } else
39c2a6f1 866 free(h);
60918275
LP
867}
868
138f49e4 869HashmapBase *_hashmap_free(HashmapBase *h, free_func_t default_free_key, free_func_t default_free_value) {
cfe561a4 870 if (h) {
138f49e4 871 _hashmap_clear(h, default_free_key, default_free_value);
cfe561a4
DH
872 hashmap_free_no_clear(h);
873 }
89439d4f 874
cfe561a4 875 return NULL;
89439d4f
MS
876}
877
138f49e4 878void _hashmap_clear(HashmapBase *h, free_func_t default_free_key, free_func_t default_free_value) {
59a5cda7
YW
879 free_func_t free_key, free_value;
880 if (!h)
881 return;
67f3c402 882
59a5cda7
YW
883 free_key = h->hash_ops->free_key ?: default_free_key;
884 free_value = h->hash_ops->free_value ?: default_free_value;
67f3c402 885
59a5cda7 886 if (free_key || free_value) {
449ddb2d 887
c380b84d
LP
888 /* If destructor calls are defined, let's destroy things defensively: let's take the item out of the
889 * hash table, and only then call the destructor functions. If these destructors then try to unregister
890 * themselves from our hash table a second time, the entry is already gone. */
891
138f49e4 892 while (_hashmap_size(h) > 0) {
ca323715
TH
893 void *k = NULL;
894 void *v;
c380b84d 895
138f49e4 896 v = _hashmap_first_key_and_value(h, true, &k);
fabe5c0e 897
59a5cda7 898 if (free_key)
c380b84d 899 free_key(k);
fabe5c0e 900
59a5cda7 901 if (free_value)
c380b84d 902 free_value(v);
59a5cda7 903 }
cfe561a4 904 }
fabe5c0e 905
89439d4f
MS
906 if (h->has_indirect) {
907 free(h->indirect.storage);
908 h->has_indirect = false;
909 }
910
911 h->n_direct_entries = 0;
912 reset_direct_storage(h);
913
914 if (h->type == HASHMAP_TYPE_ORDERED) {
915 OrderedHashmap *lh = (OrderedHashmap*) h;
916 lh->iterate_list_head = lh->iterate_list_tail = IDX_NIL;
917 }
84dcca75
VC
918
919 base_set_dirty(h);
11dd41ce
LP
920}
921
89439d4f
MS
922static int resize_buckets(HashmapBase *h, unsigned entries_add);
923
924/*
925 * Finds an empty bucket to put an entry into, starting the scan at 'idx'.
926 * Performs Robin Hood swaps as it goes. The entry to put must be placed
927 * by the caller into swap slot IDX_PUT.
928 * If used for in-place resizing, may leave a displaced entry in swap slot
929 * IDX_PUT. Caller must rehash it next.
930 * Returns: true if it left a displaced entry to rehash next in IDX_PUT,
931 * false otherwise.
932 */
933static bool hashmap_put_robin_hood(HashmapBase *h, unsigned idx,
934 struct swap_entries *swap) {
935 dib_raw_t raw_dib, *dibs;
936 unsigned dib, distance;
937
349cc4a5 938#if ENABLE_DEBUG_HASHMAP
89439d4f
MS
939 h->debug.put_count++;
940#endif
941
942 dibs = dib_raw_ptr(h);
943
944 for (distance = 0; ; distance++) {
945 raw_dib = dibs[idx];
3742095b 946 if (IN_SET(raw_dib, DIB_RAW_FREE, DIB_RAW_REHASH)) {
89439d4f
MS
947 if (raw_dib == DIB_RAW_REHASH)
948 bucket_move_entry(h, swap, idx, IDX_TMP);
949
950 if (h->has_indirect && h->indirect.idx_lowest_entry > idx)
951 h->indirect.idx_lowest_entry = idx;
60918275 952
89439d4f
MS
953 bucket_set_dib(h, idx, distance);
954 bucket_move_entry(h, swap, IDX_PUT, idx);
955 if (raw_dib == DIB_RAW_REHASH) {
956 bucket_move_entry(h, swap, IDX_TMP, IDX_PUT);
957 return true;
958 }
60918275 959
89439d4f
MS
960 return false;
961 }
962
963 dib = bucket_calculate_dib(h, idx, raw_dib);
964
965 if (dib < distance) {
966 /* Found a wealthier entry. Go Robin Hood! */
89439d4f
MS
967 bucket_set_dib(h, idx, distance);
968
969 /* swap the entries */
970 bucket_move_entry(h, swap, idx, IDX_TMP);
971 bucket_move_entry(h, swap, IDX_PUT, idx);
972 bucket_move_entry(h, swap, IDX_TMP, IDX_PUT);
973
974 distance = dib;
975 }
976
977 idx = next_idx(h, idx);
978 }
60918275
LP
979}
980
89439d4f
MS
981/*
982 * Puts an entry into a hashmap, boldly - no check whether key already exists.
983 * The caller must place the entry (only its key and value, not link indexes)
984 * in swap slot IDX_PUT.
985 * Caller must ensure: the key does not exist yet in the hashmap.
986 * that resize is not needed if !may_resize.
987 * Returns: 1 if entry was put successfully.
988 * -ENOMEM if may_resize==true and resize failed with -ENOMEM.
989 * Cannot return -ENOMEM if !may_resize.
990 */
991static int hashmap_base_put_boldly(HashmapBase *h, unsigned idx,
992 struct swap_entries *swap, bool may_resize) {
993 struct ordered_hashmap_entry *new_entry;
994 int r;
995
996 assert(idx < n_buckets(h));
997
998 new_entry = bucket_at_swap(swap, IDX_PUT);
999
1000 if (may_resize) {
1001 r = resize_buckets(h, 1);
1002 if (r < 0)
1003 return r;
1004 if (r > 0)
1005 idx = bucket_hash(h, new_entry->p.b.key);
1006 }
1007 assert(n_entries(h) < n_buckets(h));
1008
1009 if (h->type == HASHMAP_TYPE_ORDERED) {
1010 OrderedHashmap *lh = (OrderedHashmap*) h;
1011
1012 new_entry->iterate_next = IDX_NIL;
1013 new_entry->iterate_previous = lh->iterate_list_tail;
1014
1015 if (lh->iterate_list_tail != IDX_NIL) {
1016 struct ordered_hashmap_entry *old_tail;
1017
1018 old_tail = ordered_bucket_at(lh, lh->iterate_list_tail);
1019 assert(old_tail->iterate_next == IDX_NIL);
1020 old_tail->iterate_next = IDX_PUT;
1021 }
1022
1023 lh->iterate_list_tail = IDX_PUT;
1024 if (lh->iterate_list_head == IDX_NIL)
1025 lh->iterate_list_head = IDX_PUT;
1026 }
1027
1028 assert_se(hashmap_put_robin_hood(h, idx, swap) == false);
1029
1030 n_entries_inc(h);
349cc4a5 1031#if ENABLE_DEBUG_HASHMAP
89439d4f
MS
1032 h->debug.max_entries = MAX(h->debug.max_entries, n_entries(h));
1033#endif
1034
84dcca75
VC
1035 base_set_dirty(h);
1036
89439d4f
MS
1037 return 1;
1038}
1039#define hashmap_put_boldly(h, idx, swap, may_resize) \
1040 hashmap_base_put_boldly(HASHMAP_BASE(h), idx, swap, may_resize)
1041
1042/*
1043 * Returns 0 if resize is not needed.
f131770b 1044 * 1 if successfully resized.
89439d4f
MS
1045 * -ENOMEM on allocation failure.
1046 */
1047static int resize_buckets(HashmapBase *h, unsigned entries_add) {
1048 struct swap_entries swap;
1a39bc8c 1049 void *new_storage;
89439d4f
MS
1050 dib_raw_t *old_dibs, *new_dibs;
1051 const struct hashmap_type_info *hi;
1052 unsigned idx, optimal_idx;
1053 unsigned old_n_buckets, new_n_buckets, n_rehashed, new_n_entries;
1054 uint8_t new_shift;
1055 bool rehash_next;
45fa9e29
LP
1056
1057 assert(h);
1058
89439d4f
MS
1059 hi = &hashmap_type_info[h->type];
1060 new_n_entries = n_entries(h) + entries_add;
e4c691b5
MS
1061
1062 /* overflow? */
89439d4f 1063 if (_unlikely_(new_n_entries < entries_add))
e4c691b5
MS
1064 return -ENOMEM;
1065
89439d4f
MS
1066 /* For direct storage we allow 100% load, because it's tiny. */
1067 if (!h->has_indirect && new_n_entries <= hi->n_direct_buckets)
9700d698 1068 return 0;
45fa9e29 1069
89439d4f
MS
1070 /*
1071 * Load factor = n/m = 1 - (1/INV_KEEP_FREE).
1072 * From it follows: m = n + n/(INV_KEEP_FREE - 1)
1073 */
1074 new_n_buckets = new_n_entries + new_n_entries / (INV_KEEP_FREE - 1);
1075 /* overflow? */
1076 if (_unlikely_(new_n_buckets < new_n_entries))
9700d698 1077 return -ENOMEM;
45fa9e29 1078
89439d4f
MS
1079 if (_unlikely_(new_n_buckets > UINT_MAX / (hi->entry_size + sizeof(dib_raw_t))))
1080 return -ENOMEM;
a3b6fafe 1081
89439d4f 1082 old_n_buckets = n_buckets(h);
45fa9e29 1083
89439d4f
MS
1084 if (_likely_(new_n_buckets <= old_n_buckets))
1085 return 0;
45fa9e29 1086
89439d4f
MS
1087 new_shift = log2u_round_up(MAX(
1088 new_n_buckets * (hi->entry_size + sizeof(dib_raw_t)),
1089 2 * sizeof(struct direct_storage)));
45fa9e29 1090
89439d4f
MS
1091 /* Realloc storage (buckets and DIB array). */
1092 new_storage = realloc(h->has_indirect ? h->indirect.storage : NULL,
1093 1U << new_shift);
1094 if (!new_storage)
1095 return -ENOMEM;
45fa9e29 1096
89439d4f
MS
1097 /* Must upgrade direct to indirect storage. */
1098 if (!h->has_indirect) {
1099 memcpy(new_storage, h->direct.storage,
1100 old_n_buckets * (hi->entry_size + sizeof(dib_raw_t)));
1101 h->indirect.n_entries = h->n_direct_entries;
1102 h->indirect.idx_lowest_entry = 0;
1103 h->n_direct_entries = 0;
1104 }
45fa9e29 1105
89439d4f
MS
1106 /* Get a new hash key. If we've just upgraded to indirect storage,
1107 * allow reusing a previously generated key. It's still a different key
1108 * from the shared one that we used for direct storage. */
1109 get_hash_key(h->indirect.hash_key, !h->has_indirect);
1110
1111 h->has_indirect = true;
1112 h->indirect.storage = new_storage;
1113 h->indirect.n_buckets = (1U << new_shift) /
1114 (hi->entry_size + sizeof(dib_raw_t));
1115
1a39bc8c 1116 old_dibs = (dib_raw_t*)((uint8_t*) new_storage + hi->entry_size * old_n_buckets);
89439d4f
MS
1117 new_dibs = dib_raw_ptr(h);
1118
1119 /*
1120 * Move the DIB array to the new place, replacing valid DIB values with
1121 * DIB_RAW_REHASH to indicate all of the used buckets need rehashing.
1122 * Note: Overlap is not possible, because we have at least doubled the
1123 * number of buckets and dib_raw_t is smaller than any entry type.
1124 */
1125 for (idx = 0; idx < old_n_buckets; idx++) {
1126 assert(old_dibs[idx] != DIB_RAW_REHASH);
1127 new_dibs[idx] = old_dibs[idx] == DIB_RAW_FREE ? DIB_RAW_FREE
1128 : DIB_RAW_REHASH;
45fa9e29
LP
1129 }
1130
89439d4f 1131 /* Zero the area of newly added entries (including the old DIB area) */
eccaf899 1132 memzero(bucket_at(h, old_n_buckets),
89439d4f 1133 (n_buckets(h) - old_n_buckets) * hi->entry_size);
45fa9e29 1134
89439d4f
MS
1135 /* The upper half of the new DIB array needs initialization */
1136 memset(&new_dibs[old_n_buckets], DIB_RAW_INIT,
1137 (n_buckets(h) - old_n_buckets) * sizeof(dib_raw_t));
9bf3b535 1138
89439d4f
MS
1139 /* Rehash entries that need it */
1140 n_rehashed = 0;
1141 for (idx = 0; idx < old_n_buckets; idx++) {
1142 if (new_dibs[idx] != DIB_RAW_REHASH)
1143 continue;
45fa9e29 1144
89439d4f 1145 optimal_idx = bucket_hash(h, bucket_at(h, idx)->key);
45fa9e29 1146
89439d4f
MS
1147 /*
1148 * Not much to do if by luck the entry hashes to its current
1149 * location. Just set its DIB.
1150 */
1151 if (optimal_idx == idx) {
1152 new_dibs[idx] = 0;
1153 n_rehashed++;
1154 continue;
1155 }
1156
1157 new_dibs[idx] = DIB_RAW_FREE;
1158 bucket_move_entry(h, &swap, idx, IDX_PUT);
1159 /* bucket_move_entry does not clear the source */
eccaf899 1160 memzero(bucket_at(h, idx), hi->entry_size);
89439d4f
MS
1161
1162 do {
1163 /*
1164 * Find the new bucket for the current entry. This may make
1165 * another entry homeless and load it into IDX_PUT.
1166 */
1167 rehash_next = hashmap_put_robin_hood(h, optimal_idx, &swap);
1168 n_rehashed++;
1169
1170 /* Did the current entry displace another one? */
1171 if (rehash_next)
1172 optimal_idx = bucket_hash(h, bucket_at_swap(&swap, IDX_PUT)->p.b.key);
1173 } while (rehash_next);
1174 }
60918275 1175
89439d4f 1176 assert(n_rehashed == n_entries(h));
60918275 1177
89439d4f
MS
1178 return 1;
1179}
45fa9e29 1180
89439d4f
MS
1181/*
1182 * Finds an entry with a matching key
1183 * Returns: index of the found entry, or IDX_NIL if not found.
1184 */
1185static unsigned base_bucket_scan(HashmapBase *h, unsigned idx, const void *key) {
1186 struct hashmap_base_entry *e;
1187 unsigned dib, distance;
1188 dib_raw_t *dibs = dib_raw_ptr(h);
39c2a6f1 1189
89439d4f 1190 assert(idx < n_buckets(h));
60918275 1191
89439d4f
MS
1192 for (distance = 0; ; distance++) {
1193 if (dibs[idx] == DIB_RAW_FREE)
1194 return IDX_NIL;
60918275 1195
89439d4f 1196 dib = bucket_calculate_dib(h, idx, dibs[idx]);
60918275 1197
89439d4f
MS
1198 if (dib < distance)
1199 return IDX_NIL;
1200 if (dib == distance) {
1201 e = bucket_at(h, idx);
1202 if (h->hash_ops->compare(e->key, key) == 0)
1203 return idx;
1204 }
1205
1206 idx = next_idx(h, idx);
1207 }
60918275 1208}
89439d4f 1209#define bucket_scan(h, idx, key) base_bucket_scan(HASHMAP_BASE(h), idx, key)
60918275 1210
923041cb 1211int hashmap_put(Hashmap *h, const void *key, void *value) {
89439d4f
MS
1212 struct swap_entries swap;
1213 struct plain_hashmap_entry *e;
1214 unsigned hash, idx;
923041cb
MS
1215
1216 assert(h);
1217
1218 hash = bucket_hash(h, key);
89439d4f
MS
1219 idx = bucket_scan(h, hash, key);
1220 if (idx != IDX_NIL) {
1221 e = plain_bucket_at(h, idx);
923041cb
MS
1222 if (e->value == value)
1223 return 0;
1224 return -EEXIST;
1225 }
1226
89439d4f
MS
1227 e = &bucket_at_swap(&swap, IDX_PUT)->p;
1228 e->b.key = key;
1229 e->value = value;
1230 return hashmap_put_boldly(h, hash, &swap, true);
1231}
1232
1233int set_put(Set *s, const void *key) {
1234 struct swap_entries swap;
1235 struct hashmap_base_entry *e;
1236 unsigned hash, idx;
1237
1238 assert(s);
1239
1240 hash = bucket_hash(s, key);
1241 idx = bucket_scan(s, hash, key);
1242 if (idx != IDX_NIL)
1243 return 0;
1244
1245 e = &bucket_at_swap(&swap, IDX_PUT)->p.b;
1246 e->key = key;
1247 return hashmap_put_boldly(s, hash, &swap, true);
923041cb
MS
1248}
1249
0f9ccd95
ZJS
1250int _set_ensure_put(Set **s, const struct hash_ops *hash_ops, const void *key HASHMAP_DEBUG_PARAMS) {
1251 int r;
1252
1253 r = _set_ensure_allocated(s, hash_ops HASHMAP_DEBUG_PASS_ARGS);
1254 if (r < 0)
1255 return r;
1256
1257 return set_put(*s, key);
1258}
1259
fcc1d031
ZJS
1260int _set_ensure_consume(Set **s, const struct hash_ops *hash_ops, void *key HASHMAP_DEBUG_PARAMS) {
1261 int r;
1262
1263 r = _set_ensure_put(s, hash_ops, key HASHMAP_DEBUG_PASS_ARGS);
1264 if (r <= 0) {
1265 if (hash_ops && hash_ops->free_key)
1266 hash_ops->free_key(key);
1267 else
1268 free(key);
1269 }
1270
1271 return r;
1272}
1273
3158713e 1274int hashmap_replace(Hashmap *h, const void *key, void *value) {
89439d4f
MS
1275 struct swap_entries swap;
1276 struct plain_hashmap_entry *e;
1277 unsigned hash, idx;
3158713e
LP
1278
1279 assert(h);
1280
a3b6fafe 1281 hash = bucket_hash(h, key);
89439d4f
MS
1282 idx = bucket_scan(h, hash, key);
1283 if (idx != IDX_NIL) {
1284 e = plain_bucket_at(h, idx);
349cc4a5 1285#if ENABLE_DEBUG_HASHMAP
89439d4f
MS
1286 /* Although the key is equal, the key pointer may have changed,
1287 * and this would break our assumption for iterating. So count
1288 * this operation as incompatible with iteration. */
1289 if (e->b.key != key) {
1290 h->b.debug.put_count++;
1291 h->b.debug.rem_count++;
1292 h->b.debug.last_rem_idx = idx;
1293 }
1294#endif
1295 e->b.key = key;
3158713e 1296 e->value = value;
84dcca75
VC
1297 hashmap_set_dirty(h);
1298
3158713e
LP
1299 return 0;
1300 }
1301
89439d4f
MS
1302 e = &bucket_at_swap(&swap, IDX_PUT)->p;
1303 e->b.key = key;
1304 e->value = value;
1305 return hashmap_put_boldly(h, hash, &swap, true);
3158713e
LP
1306}
1307
d99ae53a 1308int hashmap_update(Hashmap *h, const void *key, void *value) {
89439d4f
MS
1309 struct plain_hashmap_entry *e;
1310 unsigned hash, idx;
d99ae53a
LP
1311
1312 assert(h);
1313
a3b6fafe 1314 hash = bucket_hash(h, key);
89439d4f
MS
1315 idx = bucket_scan(h, hash, key);
1316 if (idx == IDX_NIL)
d99ae53a
LP
1317 return -ENOENT;
1318
89439d4f 1319 e = plain_bucket_at(h, idx);
d99ae53a 1320 e->value = value;
84dcca75
VC
1321 hashmap_set_dirty(h);
1322
d99ae53a
LP
1323 return 0;
1324}
1325
138f49e4 1326void *_hashmap_get(HashmapBase *h, const void *key) {
89439d4f
MS
1327 struct hashmap_base_entry *e;
1328 unsigned hash, idx;
60918275
LP
1329
1330 if (!h)
1331 return NULL;
1332
a3b6fafe 1333 hash = bucket_hash(h, key);
89439d4f
MS
1334 idx = bucket_scan(h, hash, key);
1335 if (idx == IDX_NIL)
60918275
LP
1336 return NULL;
1337
89439d4f
MS
1338 e = bucket_at(h, idx);
1339 return entry_value(h, e);
60918275
LP
1340}
1341
89439d4f
MS
1342void *hashmap_get2(Hashmap *h, const void *key, void **key2) {
1343 struct plain_hashmap_entry *e;
1344 unsigned hash, idx;
d99ae53a
LP
1345
1346 if (!h)
1347 return NULL;
1348
a3b6fafe 1349 hash = bucket_hash(h, key);
89439d4f
MS
1350 idx = bucket_scan(h, hash, key);
1351 if (idx == IDX_NIL)
d99ae53a
LP
1352 return NULL;
1353
89439d4f 1354 e = plain_bucket_at(h, idx);
d99ae53a 1355 if (key2)
89439d4f 1356 *key2 = (void*) e->b.key;
d99ae53a
LP
1357
1358 return e->value;
1359}
1360
138f49e4 1361bool _hashmap_contains(HashmapBase *h, const void *key) {
96342de6 1362 unsigned hash;
96342de6
LN
1363
1364 if (!h)
1365 return false;
1366
a3b6fafe 1367 hash = bucket_hash(h, key);
89439d4f 1368 return bucket_scan(h, hash, key) != IDX_NIL;
96342de6
LN
1369}
1370
138f49e4 1371void *_hashmap_remove(HashmapBase *h, const void *key) {
89439d4f
MS
1372 struct hashmap_base_entry *e;
1373 unsigned hash, idx;
60918275
LP
1374 void *data;
1375
1376 if (!h)
1377 return NULL;
1378
a3b6fafe 1379 hash = bucket_hash(h, key);
89439d4f
MS
1380 idx = bucket_scan(h, hash, key);
1381 if (idx == IDX_NIL)
60918275
LP
1382 return NULL;
1383
89439d4f
MS
1384 e = bucket_at(h, idx);
1385 data = entry_value(h, e);
1386 remove_entry(h, idx);
60918275
LP
1387
1388 return data;
1389}
1390
89439d4f
MS
1391void *hashmap_remove2(Hashmap *h, const void *key, void **rkey) {
1392 struct plain_hashmap_entry *e;
1393 unsigned hash, idx;
c582a3b3
LP
1394 void *data;
1395
1396 if (!h) {
1397 if (rkey)
1398 *rkey = NULL;
1399 return NULL;
1400 }
1401
1402 hash = bucket_hash(h, key);
89439d4f
MS
1403 idx = bucket_scan(h, hash, key);
1404 if (idx == IDX_NIL) {
c582a3b3
LP
1405 if (rkey)
1406 *rkey = NULL;
1407 return NULL;
1408 }
1409
89439d4f 1410 e = plain_bucket_at(h, idx);
c582a3b3
LP
1411 data = e->value;
1412 if (rkey)
89439d4f 1413 *rkey = (void*) e->b.key;
c582a3b3 1414
89439d4f 1415 remove_entry(h, idx);
c582a3b3
LP
1416
1417 return data;
1418}
1419
101d8e63 1420int hashmap_remove_and_put(Hashmap *h, const void *old_key, const void *new_key, void *value) {
89439d4f
MS
1421 struct swap_entries swap;
1422 struct plain_hashmap_entry *e;
1423 unsigned old_hash, new_hash, idx;
101d8e63
LP
1424
1425 if (!h)
1426 return -ENOENT;
1427
a3b6fafe 1428 old_hash = bucket_hash(h, old_key);
89439d4f
MS
1429 idx = bucket_scan(h, old_hash, old_key);
1430 if (idx == IDX_NIL)
101d8e63
LP
1431 return -ENOENT;
1432
a3b6fafe 1433 new_hash = bucket_hash(h, new_key);
89439d4f 1434 if (bucket_scan(h, new_hash, new_key) != IDX_NIL)
101d8e63
LP
1435 return -EEXIST;
1436
89439d4f 1437 remove_entry(h, idx);
101d8e63 1438
89439d4f
MS
1439 e = &bucket_at_swap(&swap, IDX_PUT)->p;
1440 e->b.key = new_key;
101d8e63 1441 e->value = value;
89439d4f
MS
1442 assert_se(hashmap_put_boldly(h, new_hash, &swap, false) == 1);
1443
1444 return 0;
1445}
1446
1447int set_remove_and_put(Set *s, const void *old_key, const void *new_key) {
1448 struct swap_entries swap;
1449 struct hashmap_base_entry *e;
1450 unsigned old_hash, new_hash, idx;
101d8e63 1451
89439d4f
MS
1452 if (!s)
1453 return -ENOENT;
1454
1455 old_hash = bucket_hash(s, old_key);
1456 idx = bucket_scan(s, old_hash, old_key);
1457 if (idx == IDX_NIL)
1458 return -ENOENT;
1459
1460 new_hash = bucket_hash(s, new_key);
1461 if (bucket_scan(s, new_hash, new_key) != IDX_NIL)
1462 return -EEXIST;
1463
1464 remove_entry(s, idx);
1465
1466 e = &bucket_at_swap(&swap, IDX_PUT)->p.b;
1467 e->key = new_key;
1468 assert_se(hashmap_put_boldly(s, new_hash, &swap, false) == 1);
101d8e63
LP
1469
1470 return 0;
1471}
1472
8fe914ec 1473int hashmap_remove_and_replace(Hashmap *h, const void *old_key, const void *new_key, void *value) {
89439d4f
MS
1474 struct swap_entries swap;
1475 struct plain_hashmap_entry *e;
1476 unsigned old_hash, new_hash, idx_old, idx_new;
8fe914ec
LP
1477
1478 if (!h)
1479 return -ENOENT;
1480
a3b6fafe 1481 old_hash = bucket_hash(h, old_key);
89439d4f
MS
1482 idx_old = bucket_scan(h, old_hash, old_key);
1483 if (idx_old == IDX_NIL)
8fe914ec
LP
1484 return -ENOENT;
1485
89439d4f 1486 old_key = bucket_at(HASHMAP_BASE(h), idx_old)->key;
8fe914ec 1487
89439d4f
MS
1488 new_hash = bucket_hash(h, new_key);
1489 idx_new = bucket_scan(h, new_hash, new_key);
1490 if (idx_new != IDX_NIL)
1491 if (idx_old != idx_new) {
1492 remove_entry(h, idx_new);
1493 /* Compensate for a possible backward shift. */
1494 if (old_key != bucket_at(HASHMAP_BASE(h), idx_old)->key)
1495 idx_old = prev_idx(HASHMAP_BASE(h), idx_old);
1496 assert(old_key == bucket_at(HASHMAP_BASE(h), idx_old)->key);
1497 }
1498
1499 remove_entry(h, idx_old);
1500
1501 e = &bucket_at_swap(&swap, IDX_PUT)->p;
1502 e->b.key = new_key;
8fe914ec 1503 e->value = value;
89439d4f 1504 assert_se(hashmap_put_boldly(h, new_hash, &swap, false) == 1);
8fe914ec
LP
1505
1506 return 0;
1507}
1508
138f49e4 1509void *_hashmap_remove_value(HashmapBase *h, const void *key, void *value) {
c380b84d 1510 struct hashmap_base_entry *e;
89439d4f 1511 unsigned hash, idx;
3158713e
LP
1512
1513 if (!h)
1514 return NULL;
1515
a3b6fafe 1516 hash = bucket_hash(h, key);
89439d4f
MS
1517 idx = bucket_scan(h, hash, key);
1518 if (idx == IDX_NIL)
3158713e
LP
1519 return NULL;
1520
c380b84d
LP
1521 e = bucket_at(h, idx);
1522 if (entry_value(h, e) != value)
3158713e
LP
1523 return NULL;
1524
89439d4f 1525 remove_entry(h, idx);
3158713e
LP
1526
1527 return value;
1528}
1529
89439d4f
MS
1530static unsigned find_first_entry(HashmapBase *h) {
1531 Iterator i = ITERATOR_FIRST;
60918275 1532
89439d4f
MS
1533 if (!h || !n_entries(h))
1534 return IDX_NIL;
60918275 1535
89439d4f 1536 return hashmap_iterate_entry(h, &i);
60918275
LP
1537}
1538
138f49e4 1539void *_hashmap_first_key_and_value(HashmapBase *h, bool remove, void **ret_key) {
89439d4f 1540 struct hashmap_base_entry *e;
7ef670c3 1541 void *key, *data;
89439d4f 1542 unsigned idx;
60918275 1543
89439d4f 1544 idx = find_first_entry(h);
51c682df
TH
1545 if (idx == IDX_NIL) {
1546 if (ret_key)
1547 *ret_key = NULL;
60918275 1548 return NULL;
51c682df 1549 }
60918275 1550
89439d4f 1551 e = bucket_at(h, idx);
7ef670c3 1552 key = (void*) e->key;
89439d4f 1553 data = entry_value(h, e);
60918275 1554
7ef670c3
YW
1555 if (remove)
1556 remove_entry(h, idx);
60918275 1557
7ef670c3
YW
1558 if (ret_key)
1559 *ret_key = key;
22be093f 1560
7ef670c3 1561 return data;
22be093f
LP
1562}
1563
138f49e4 1564unsigned _hashmap_size(HashmapBase *h) {
60918275
LP
1565 if (!h)
1566 return 0;
1567
89439d4f 1568 return n_entries(h);
60918275
LP
1569}
1570
138f49e4 1571unsigned _hashmap_buckets(HashmapBase *h) {
45fa9e29
LP
1572 if (!h)
1573 return 0;
1574
89439d4f 1575 return n_buckets(h);
45fa9e29
LP
1576}
1577
138f49e4 1578int _hashmap_merge(Hashmap *h, Hashmap *other) {
89439d4f
MS
1579 Iterator i;
1580 unsigned idx;
60918275 1581
89439d4f 1582 assert(h);
60918275 1583
89439d4f
MS
1584 HASHMAP_FOREACH_IDX(idx, HASHMAP_BASE(other), i) {
1585 struct plain_hashmap_entry *pe = plain_bucket_at(other, idx);
1586 int r;
91cdde8a 1587
89439d4f
MS
1588 r = hashmap_put(h, pe->b.key, pe->value);
1589 if (r < 0 && r != -EEXIST)
1590 return r;
1591 }
91cdde8a 1592
89439d4f
MS
1593 return 0;
1594}
91cdde8a 1595
89439d4f
MS
1596int set_merge(Set *s, Set *other) {
1597 Iterator i;
1598 unsigned idx;
91cdde8a 1599
89439d4f
MS
1600 assert(s);
1601
1602 HASHMAP_FOREACH_IDX(idx, HASHMAP_BASE(other), i) {
1603 struct set_entry *se = set_bucket_at(other, idx);
91cdde8a
LP
1604 int r;
1605
89439d4f
MS
1606 r = set_put(s, se->b.key);
1607 if (r < 0)
a3b6fafe 1608 return r;
91cdde8a
LP
1609 }
1610
1611 return 0;
1612}
1613
138f49e4 1614int _hashmap_reserve(HashmapBase *h, unsigned entries_add) {
e4c691b5
MS
1615 int r;
1616
1617 assert(h);
1618
1619 r = resize_buckets(h, entries_add);
1620 if (r < 0)
1621 return r;
1622
1623 return 0;
1624}
1625
89439d4f
MS
1626/*
1627 * The same as hashmap_merge(), but every new item from other is moved to h.
1628 * Keys already in h are skipped and stay in other.
1629 * Returns: 0 on success.
1630 * -ENOMEM on alloc failure, in which case no move has been done.
1631 */
138f49e4 1632int _hashmap_move(HashmapBase *h, HashmapBase *other) {
89439d4f
MS
1633 struct swap_entries swap;
1634 struct hashmap_base_entry *e, *n;
1635 Iterator i;
1636 unsigned idx;
1637 int r;
101d8e63
LP
1638
1639 assert(h);
1640
101d8e63 1641 if (!other)
7ad63f57 1642 return 0;
101d8e63 1643
89439d4f
MS
1644 assert(other->type == h->type);
1645
1646 /*
1647 * This reserves buckets for the worst case, where none of other's
1648 * entries are yet present in h. This is preferable to risking
1649 * an allocation failure in the middle of the moving and having to
1650 * rollback or return a partial result.
1651 */
1652 r = resize_buckets(h, n_entries(other));
1653 if (r < 0)
1654 return r;
101d8e63 1655
89439d4f
MS
1656 HASHMAP_FOREACH_IDX(idx, other, i) {
1657 unsigned h_hash;
101d8e63 1658
89439d4f 1659 e = bucket_at(other, idx);
a3b6fafe 1660 h_hash = bucket_hash(h, e->key);
89439d4f 1661 if (bucket_scan(h, h_hash, e->key) != IDX_NIL)
101d8e63
LP
1662 continue;
1663
89439d4f
MS
1664 n = &bucket_at_swap(&swap, IDX_PUT)->p.b;
1665 n->key = e->key;
1666 if (h->type != HASHMAP_TYPE_SET)
1667 ((struct plain_hashmap_entry*) n)->value =
1668 ((struct plain_hashmap_entry*) e)->value;
1669 assert_se(hashmap_put_boldly(h, h_hash, &swap, false) == 1);
1670
1671 remove_entry(other, idx);
101d8e63 1672 }
7ad63f57
MS
1673
1674 return 0;
101d8e63
LP
1675}
1676
138f49e4 1677int _hashmap_move_one(HashmapBase *h, HashmapBase *other, const void *key) {
89439d4f
MS
1678 struct swap_entries swap;
1679 unsigned h_hash, other_hash, idx;
1680 struct hashmap_base_entry *e, *n;
1681 int r;
101d8e63 1682
101d8e63
LP
1683 assert(h);
1684
a3b6fafe 1685 h_hash = bucket_hash(h, key);
89439d4f 1686 if (bucket_scan(h, h_hash, key) != IDX_NIL)
101d8e63
LP
1687 return -EEXIST;
1688
bf3d3e2b
MS
1689 if (!other)
1690 return -ENOENT;
1691
89439d4f
MS
1692 assert(other->type == h->type);
1693
a3b6fafe 1694 other_hash = bucket_hash(other, key);
89439d4f
MS
1695 idx = bucket_scan(other, other_hash, key);
1696 if (idx == IDX_NIL)
101d8e63
LP
1697 return -ENOENT;
1698
89439d4f
MS
1699 e = bucket_at(other, idx);
1700
1701 n = &bucket_at_swap(&swap, IDX_PUT)->p.b;
1702 n->key = e->key;
1703 if (h->type != HASHMAP_TYPE_SET)
1704 ((struct plain_hashmap_entry*) n)->value =
1705 ((struct plain_hashmap_entry*) e)->value;
1706 r = hashmap_put_boldly(h, h_hash, &swap, true);
1707 if (r < 0)
1708 return r;
101d8e63 1709
89439d4f 1710 remove_entry(other, idx);
101d8e63
LP
1711 return 0;
1712}
1713
add74e89 1714HashmapBase *_hashmap_copy(HashmapBase *h HASHMAP_DEBUG_PARAMS) {
89439d4f
MS
1715 HashmapBase *copy;
1716 int r;
91cdde8a
LP
1717
1718 assert(h);
1719
add74e89 1720 copy = hashmap_base_new(h->hash_ops, h->type HASHMAP_DEBUG_PASS_ARGS);
45fa9e29 1721 if (!copy)
91cdde8a
LP
1722 return NULL;
1723
89439d4f
MS
1724 switch (h->type) {
1725 case HASHMAP_TYPE_PLAIN:
1726 case HASHMAP_TYPE_ORDERED:
1727 r = hashmap_merge((Hashmap*)copy, (Hashmap*)h);
1728 break;
1729 case HASHMAP_TYPE_SET:
1730 r = set_merge((Set*)copy, (Set*)h);
1731 break;
1732 default:
1733 assert_not_reached("Unknown hashmap type");
1734 }
1735
add74e89
ZJS
1736 if (r < 0)
1737 return _hashmap_free(copy, false, false);
91cdde8a
LP
1738
1739 return copy;
1740}
db1413d7 1741
138f49e4 1742char **_hashmap_get_strv(HashmapBase *h) {
db1413d7 1743 char **sv;
89439d4f
MS
1744 Iterator i;
1745 unsigned idx, n;
db1413d7 1746
89439d4f 1747 sv = new(char*, n_entries(h)+1);
729e3769 1748 if (!sv)
db1413d7
KS
1749 return NULL;
1750
1751 n = 0;
89439d4f
MS
1752 HASHMAP_FOREACH_IDX(idx, h, i)
1753 sv[n++] = entry_value(h, bucket_at(h, idx));
db1413d7
KS
1754 sv[n] = NULL;
1755
1756 return sv;
1757}
3c1668da 1758
89439d4f
MS
1759void *ordered_hashmap_next(OrderedHashmap *h, const void *key) {
1760 struct ordered_hashmap_entry *e;
1761 unsigned hash, idx;
3c1668da 1762
3c1668da
LP
1763 if (!h)
1764 return NULL;
1765
a3b6fafe 1766 hash = bucket_hash(h, key);
89439d4f
MS
1767 idx = bucket_scan(h, hash, key);
1768 if (idx == IDX_NIL)
3c1668da
LP
1769 return NULL;
1770
89439d4f
MS
1771 e = ordered_bucket_at(h, idx);
1772 if (e->iterate_next == IDX_NIL)
3c1668da 1773 return NULL;
89439d4f
MS
1774 return ordered_bucket_at(h, e->iterate_next)->p.value;
1775}
3c1668da 1776
89439d4f
MS
1777int set_consume(Set *s, void *value) {
1778 int r;
1779
d97c5aea
LP
1780 assert(s);
1781 assert(value);
1782
89439d4f 1783 r = set_put(s, value);
575ccc1b 1784 if (r <= 0)
89439d4f
MS
1785 free(value);
1786
1787 return r;
1788}
1789
b8b46b1c 1790int _hashmap_put_strdup(Hashmap **h, const char *k, const char *v HASHMAP_DEBUG_PARAMS) {
87da8784
ZJS
1791 int r;
1792
b8b46b1c 1793 r = _hashmap_ensure_allocated(h, &string_hash_ops_free_free HASHMAP_DEBUG_PASS_ARGS);
87da8784
ZJS
1794 if (r < 0)
1795 return r;
1796
1797 _cleanup_free_ char *kdup = NULL, *vdup = NULL;
25b3e2a8 1798
87da8784 1799 kdup = strdup(k);
25b3e2a8 1800 if (!kdup)
87da8784
ZJS
1801 return -ENOMEM;
1802
25b3e2a8
ZJS
1803 if (v) {
1804 vdup = strdup(v);
1805 if (!vdup)
1806 return -ENOMEM;
1807 }
1808
87da8784
ZJS
1809 r = hashmap_put(*h, kdup, vdup);
1810 if (r < 0) {
25b3e2a8 1811 if (r == -EEXIST && streq_ptr(v, hashmap_get(*h, kdup)))
87da8784
ZJS
1812 return 0;
1813 return r;
1814 }
1815
25b3e2a8
ZJS
1816 /* 0 with non-null vdup would mean vdup is already in the hashmap, which cannot be */
1817 assert(vdup == NULL || r > 0);
1818 if (r > 0)
1819 kdup = vdup = NULL;
87da8784 1820
25b3e2a8 1821 return r;
87da8784
ZJS
1822}
1823
b8b46b1c 1824int _set_put_strdup(Set **s, const char *p HASHMAP_DEBUG_PARAMS) {
89439d4f 1825 char *c;
be327321 1826 int r;
89439d4f
MS
1827
1828 assert(s);
1829 assert(p);
1830
b8b46b1c 1831 r = _set_ensure_allocated(s, &string_hash_ops_free HASHMAP_DEBUG_PASS_ARGS);
be327321
ZJS
1832 if (r < 0)
1833 return r;
1834
1835 if (set_contains(*s, (char*) p))
454f0f86
LP
1836 return 0;
1837
89439d4f
MS
1838 c = strdup(p);
1839 if (!c)
1840 return -ENOMEM;
1841
be327321 1842 return set_consume(*s, c);
89439d4f
MS
1843}
1844
b8b46b1c 1845int _set_put_strdupv(Set **s, char **l HASHMAP_DEBUG_PARAMS) {
89439d4f
MS
1846 int n = 0, r;
1847 char **i;
1848
d97c5aea
LP
1849 assert(s);
1850
89439d4f 1851 STRV_FOREACH(i, l) {
b8b46b1c 1852 r = _set_put_strdup(s, *i HASHMAP_DEBUG_PASS_ARGS);
89439d4f
MS
1853 if (r < 0)
1854 return r;
1855
1856 n += r;
1857 }
1858
1859 return n;
3c1668da 1860}
d97c5aea
LP
1861
1862int set_put_strsplit(Set *s, const char *v, const char *separators, ExtractFlags flags) {
1863 const char *p = v;
1864 int r;
1865
1866 assert(s);
1867 assert(v);
1868
1869 for (;;) {
1870 char *word;
1871
1872 r = extract_first_word(&p, &word, separators, flags);
1873 if (r <= 0)
1874 return r;
1875
1876 r = set_consume(s, word);
1877 if (r < 0)
1878 return r;
1879 }
1880}
45ea84d8
VC
1881
1882/* expand the cachemem if needed, return true if newly (re)activated. */
1883static int cachemem_maintain(CacheMem *mem, unsigned size) {
45ea84d8
VC
1884 assert(mem);
1885
1886 if (!GREEDY_REALLOC(mem->ptr, mem->n_allocated, size)) {
1887 if (size > 0)
1888 return -ENOMEM;
1889 }
1890
afbbc068
ZJS
1891 if (!mem->active) {
1892 mem->active = true;
1893 return true;
1894 }
45ea84d8 1895
afbbc068 1896 return false;
45ea84d8
VC
1897}
1898
1899int iterated_cache_get(IteratedCache *cache, const void ***res_keys, const void ***res_values, unsigned *res_n_entries) {
1900 bool sync_keys = false, sync_values = false;
1901 unsigned size;
1902 int r;
1903
1904 assert(cache);
1905 assert(cache->hashmap);
1906
1907 size = n_entries(cache->hashmap);
1908
1909 if (res_keys) {
1910 r = cachemem_maintain(&cache->keys, size);
1911 if (r < 0)
1912 return r;
1913
1914 sync_keys = r;
1915 } else
1916 cache->keys.active = false;
1917
1918 if (res_values) {
1919 r = cachemem_maintain(&cache->values, size);
1920 if (r < 0)
1921 return r;
1922
1923 sync_values = r;
1924 } else
1925 cache->values.active = false;
1926
1927 if (cache->hashmap->dirty) {
1928 if (cache->keys.active)
1929 sync_keys = true;
1930 if (cache->values.active)
1931 sync_values = true;
1932
1933 cache->hashmap->dirty = false;
1934 }
1935
1936 if (sync_keys || sync_values) {
1937 unsigned i, idx;
1938 Iterator iter;
1939
1940 i = 0;
1941 HASHMAP_FOREACH_IDX(idx, cache->hashmap, iter) {
1942 struct hashmap_base_entry *e;
1943
1944 e = bucket_at(cache->hashmap, idx);
1945
1946 if (sync_keys)
1947 cache->keys.ptr[i] = e->key;
1948 if (sync_values)
1949 cache->values.ptr[i] = entry_value(cache->hashmap, e);
1950 i++;
1951 }
1952 }
1953
1954 if (res_keys)
1955 *res_keys = cache->keys.ptr;
1956 if (res_values)
1957 *res_values = cache->values.ptr;
1958 if (res_n_entries)
1959 *res_n_entries = size;
1960
1961 return 0;
1962}
1963
1964IteratedCache *iterated_cache_free(IteratedCache *cache) {
1965 if (cache) {
1966 free(cache->keys.ptr);
1967 free(cache->values.ptr);
45ea84d8
VC
1968 }
1969
b61658fd 1970 return mfree(cache);
45ea84d8 1971}