Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : #include <chashmap.h>
26 : #include <internal/chashinsert.h>
27 : #include <internal/chashkey.h>
28 : #include <internal/cpow2.h>
29 : #include <internal/cprocsintern.h>
30 : #include <internal/crandom.h>
31 : #include <internal/test_helpers/chashmap.h>
32 : #include <math.h>
33 : #include <stdatomic.h>
34 : #include <stdlib.h>
35 : #include <string.h>
36 : #include <time.h>
37 : #include <unistd.h>
38 :
39 : // The smallest bucket or slot array of a map made by the public constructors,
40 : // and the factor separate chaining grows and shrinks by. A map made by
41 : // ccol_chmap_create_compact() starts at compact_bucket_array_size, which must
42 : // be a power of two of at least 2 (see hash_index_for()).
43 : static const size_t minimum_allowed_bucket_array_size = 16;
44 : static const size_t compact_bucket_array_size = 4;
45 : static const size_t scale_factor = 4;
46 :
47 : // The loads at which an open-addressing table grows and shrinks, and the
48 : // largest key or value that a separate-chaining node keeps inline.
49 : #define OPEN_ADDR_MAX_LOAD_FACTOR 0.70
50 : #define OPEN_ADDR_MIN_LOAD_FACTOR 0.25
51 : #define INLINE_STORAGE_THRESHOLD 23
52 :
53 : // The mixers and the reduction to an index come in a 64-bit and a 32-bit form.
54 : #if SIZE_MAX != UINT64_MAX && SIZE_MAX != UINT32_MAX
55 : #error "Unsupported architecture: SIZE_MAX is neither UINT32_MAX nor UINT64_MAX"
56 : #endif
57 :
58 : // The secret of the built-in hashes. There's one per process (see
59 : // g_chmap_hash_secret), so no map stores any of it. sip_v is the SipHash-1-3
60 : // state for the key (k0, k1), kept instead of the key so a hash skips the four
61 : // xors; the keyed byte hash and the long double hash use it. int_seed keys the
62 : // mixer of fixed-width keys and custom results in the keyed mode, and
63 : // byte_seed seeds XXH64 in the fast mode.
64 : typedef struct chmap_hash_secret {
65 : uint64_t sip_v[4];
66 : uint64_t int_seed;
67 : uint64_t byte_seed;
68 : } chmap_hash_secret;
69 :
70 : // An open-addressing slot: An 8-byte key and an 8-byte value, 16 bytes with no
71 : // padding. The occupied bit lives in the metadata array instead, because a
72 : // third member would pad the slot to 24 bytes and spread the bits a probe
73 : // tests. The natural alignment lets chmap_get_ptr() hand out an aligned
74 : // pointer into the slot.
75 : typedef struct {
76 : uint64_t key_data;
77 : uint64_t val_data;
78 : } oa_slot;
79 :
80 : // The metadata bit of an occupied slot; 0 means empty.
81 : #define SLOT_OCCUPIED 0x01
82 :
83 : // The state of an open-addressing map. The fields up to val_type, with the hash
84 : // mode and the window in the header, are what insert, lookup and delete read;
85 : // the rest is colder.
86 : typedef struct {
87 : oa_slot* slots;
88 : // One occupied byte per slot, at the tail of the slots block (see
89 : // oa_alloc_block()), so one cache line holds the bits of 64 slots.
90 : uint8_t* metadata;
91 : size_t capacity;
92 : // One more than the largest displacement in the table, at least
93 : // min(OA_DEEP_INSERT, capacity). Lookups, deletes and the backward-shift walk
94 : // stop after this many slots, which bounds a probe through a long run of keys
95 : // with consecutive home slots that no insert sees as displaced. Inserts widen
96 : // it and rebuilds set it; deletes never need to.
97 : size_t probe_span;
98 : size_t count;
99 : ccol_hashing_proc custom_hashing_proc;
100 : ccol_data_type key_type;
101 : ccol_data_type val_type;
102 : size_t key_size;
103 : size_t val_size;
104 : ccol_memmgmt_procs* m_procs;
105 : } open_addr_map;
106 :
107 : // The links of a node on the insertion-order list. Not packed, so it stays
108 : // 8-byte aligned inside llist_node.
109 : typedef struct dllist_ref_node {
110 : struct dllist_ref_node* prev;
111 : struct dllist_ref_node* next;
112 : } dllist_ref_node;
113 :
114 : // The ends of the list of all live entries: head is the newest and tail the
115 : // oldest. The public iterator walks from head, the ordered cursor of
116 : // chashinsert.h from tail.
117 : typedef struct dllist_root {
118 : dllist_ref_node* head;
119 : dllist_ref_node* tail;
120 : } dllist_root;
121 :
122 : // One entry of a separate-chaining map. A key or value of at most
123 : // INLINE_STORAGE_THRESHOLD bytes lives inline in its union, anything bigger in
124 : // a heap buffer, and the size in the accessor alone says which; every store
125 : // keeps that true. Each union is _Alignas(max_align_t) and the struct isn't
126 : // packed, because the typed macros cast a pointer into inline_data to the
127 : // caller's type (long double needs 16 bytes), just as they would for a malloc
128 : // buffer. On LP64 the order leaves no padding, and hash_val and next, which a
129 : // chain walk reads, share the first line with an inline key. The node keeps no
130 : // allocator; its map's procs are passed in.
131 : typedef struct llist_node {
132 : _Alignas(max_align_t) union {
133 : void* ptr;
134 : char inline_data[INLINE_STORAGE_THRESHOLD + 1];
135 : } key_storage;
136 : size_t hash_val;
137 : _Alignas(max_align_t) union {
138 : void* ptr;
139 : char inline_data[INLINE_STORAGE_THRESHOLD + 1];
140 : } val_storage;
141 : struct llist_node* next;
142 : // The stable {ptr, size} of the stored key and value that the map hands out.
143 : cmap_pair key_pair_accessor;
144 : cmap_pair val_pair_accessor;
145 : dllist_ref_node dllist_refs;
146 : } llist_node;
147 :
148 : // Pins the layout above on LP64 with a 16-byte max_align_t (x86-64, aarch64).
149 : _Static_assert(SIZE_MAX != UINT64_MAX || _Alignof(max_align_t) != 16 ||
150 : (sizeof(llist_node) == 112 &&
151 : offsetof(llist_node, hash_val) == 24 &&
152 : offsetof(llist_node, val_storage) == 32 &&
153 : offsetof(llist_node, next) == 56),
154 : "llist_node must stay 112 bytes with no padding");
155 :
156 : // The state of a separate-chaining map.
157 : typedef struct sep_chain_map {
158 : size_t elem_count;
159 : size_t bucket_arr_size;
160 : size_t elem_count_to_scale_up;
161 : size_t elem_count_to_scale_down;
162 : llist_node** bucket_arr;
163 : dllist_root all_elems;
164 : ccol_memmgmt_procs* m_procs;
165 : ccol_hashing_proc custom_hashing_proc;
166 : // NULL selects the built-in comparison of sc_compare_keys().
167 : ccol_key_equality_proc custom_key_equality_proc;
168 : // ccol_data_type values, one byte each so they share the last word.
169 : uint8_t key_type;
170 : uint8_t val_type;
171 : // How many bucket pointers the map's block holds after struct chashmap, or 0;
172 : // see sc_inline_bucket_arr().
173 : uint8_t inline_buckets;
174 : } sep_chain_map;
175 :
176 : // The two backends.
177 : typedef enum { IMPL_OPEN_ADDRESSING, IMPL_SEPARATE_CHAINING } hashmap_impl_type;
178 :
179 : // A map is one allocation: This struct with its backend in state, then the
180 : // first bucket array of a small separate-chaining map (see
181 : // sc_inline_bucket_arr()), then the map's own procs copy when it needs one.
182 : // Operations reach the backend through impl, which measured cheaper than
183 : // fixed-offset addressing of state. The first eight bytes hold the backend,
184 : // the hash mode and the insert window, which both backends reach at a constant
185 : // offset back from their state (chmap_of_oa(), chmap_of_sc()).
186 : struct chashmap {
187 : uint8_t impl_type;
188 : // CHMAP_HASH_FAST or CHMAP_HASH_KEYED.
189 : uint8_t hash_mode;
190 : // The bound and the running sum of the insert window; see chmap_window_add().
191 : uint16_t window_bound;
192 : uint32_t insert_window;
193 : union {
194 : open_addr_map* oa;
195 : sep_chain_map* sc;
196 : } impl;
197 : union {
198 : open_addr_map oa;
199 : sep_chain_map sc;
200 : } state;
201 : };
202 :
203 : // The hash modes. Every map starts fast and may switch to keyed, and each
204 : // growth of a keyed map tries fast again. Fast is a Fibonacci multiply for a
205 : // fixed-width key, XXH64 with a secret seed for bytes and the murmur3
206 : // finalizer for a custom result; keyed is what ccol_chmap_hash_key() gives:
207 : // hash_word_seeded() and SipHash-1-3. A long double is hashed by value with
208 : // SipHash in both modes, and key identity never depends on the mode.
209 : //
210 : // The fast hashes are cheap and spread ordinary keys well, but they're public
211 : // bijections (or, for XXH64, have collisions under every seed), so only the
212 : // writers watch: Every insert of a new key adds to the insert window, and a
213 : // window of 256 whose walks pass oa_window_bound() or sc_window_bound(), or one
214 : // insert past its cap, switches the map. A lookup never writes. The switch
215 : // rebuilds an open-addressing table into a new block and rehashes chaining
216 : // nodes in place. A failed fast attempt at growth stops early and fills the
217 : // same new table keyed, so its work is linear in the count and geometric
218 : // growth keeps it O(1) amortized per insert. A reset and a shrink keep the
219 : // mode.
220 : enum { CHMAP_HASH_FAST = 0, CHMAP_HASH_KEYED = 1 };
221 :
222 : // The window starts at 2^31 and each insert of a new key adds 2^23 plus its
223 : // walk, so 256 inserts carry out of 32 bits exactly when their walks sum to
224 : // less than 2^23, and the 32 bits then hold that sum. A fast map never holds a
225 : // walk above its cap, so its windows always end after 256 inserts.
226 : #define CHMAP_WINDOW_START 0x80000000u
227 : #define CHMAP_WINDOW_STEP 0x00800000u
228 : #define CHMAP_WINDOW_INSERTS 256u
229 :
230 : // A new separate-chaining key that meets this many nodes switches the map.
231 : #define SC_CHAIN_CAP 20u
232 :
233 : // An open-addressing insert displaced this far or more goes to
234 : // oa_note_deep_insert(). It's also the smallest probe_span of a table this
235 : // big or bigger.
236 : #define OA_DEEP_INSERT 32u
237 :
238 : // Give the map header that sits at a constant offset before a backend's state,
239 : // so a backend function can reach the hash mode and the insert window without
240 : // an extra pointer.
241 : static inline struct chashmap* chmap_of_oa(open_addr_map* map) {
242 : return (struct chashmap*)((uint8_t*)map -
243 : offsetof(struct chashmap, state.oa));
244 : }
245 :
246 : static inline struct chashmap* chmap_of_sc(sep_chain_map* map) {
247 : return (struct chashmap*)((uint8_t*)map -
248 : offsetof(struct chashmap, state.sc));
249 : }
250 :
251 : // Tell whether a backend hashes in the keyed mode; every hash and every
252 : // detection step branches on it.
253 20165369 : static inline bool oa_keyed(open_addr_map* map) {
254 20165369 : return chmap_of_oa(map)->hash_mode == CHMAP_HASH_KEYED;
255 : }
256 :
257 7676405 : static inline bool sc_keyed(sep_chain_map* map) {
258 7676405 : return chmap_of_sc(map)->hash_mode == CHMAP_HASH_KEYED;
259 : }
260 :
261 : // Adds one insert of a new key with the given walk to the window, and gives
262 : // true when that ends the window (a carry out of 32 bits).
263 9928703 : static inline bool chmap_window_add(struct chashmap* chm, size_t walk) {
264 9928703 : uint32_t sum;
265 9928703 : bool ended = __builtin_add_overflow(chm->insert_window,
266 9928703 : CHMAP_WINDOW_STEP + (uint32_t)walk, &sum);
267 9928703 : chm->insert_window = sum;
268 9928703 : return ended;
269 : }
270 :
271 : // Gives the base-2 logarithm of a power of two; oa_insert_cap() and the window
272 : // bounds need it.
273 1857306 : static inline unsigned chmap_log2_pow2(size_t capacity) {
274 : #if SIZE_MAX == UINT64_MAX
275 1857306 : return (unsigned)__builtin_ctzll((unsigned long long)capacity);
276 : #else
277 : return (unsigned)__builtin_ctz((unsigned int)capacity);
278 : #endif
279 : }
280 :
281 : // Gives count / capacity in 16.16 fixed point for a power-of-two capacity, so
282 : // the window bounds need no floating point.
283 1840814 : static inline uint64_t chmap_load_q16(size_t count, size_t capacity) {
284 1840814 : unsigned k = chmap_log2_pow2(capacity);
285 1840814 : return k >= 16 ? (uint64_t)count >> (k - 16) : (uint64_t)count << (16 - k);
286 : }
287 :
288 : // Tells whether a type is one of the types of at most 8 bytes that the integer
289 : // mixer hashes (the integers, float, double, pointers; not long double). The
290 : // backend choice at creation uses it.
291 1798157 : static inline bool is_type_integral(ccol_data_type type) {
292 1798157 : switch (type) {
293 : case ccol_char:
294 : case ccol_signed_char:
295 : case ccol_short:
296 : case ccol_int:
297 : case ccol_long:
298 : case ccol_long_long:
299 : case ccol_unsigned_char:
300 : case ccol_unsigned_short:
301 : case ccol_unsigned_int:
302 : case ccol_unsigned_long:
303 : case ccol_unsigned_long_long:
304 : case ccol_float:
305 : case ccol_double:
306 : case ccol_pointer:
307 : return true;
308 : default:
309 : return false;
310 : }
311 : }
312 :
313 : // Gives the size of the C type behind a ccol_data_type, or 8 for an unknown
314 : // type. It sizes the key and value of an open-addressing map, so a slot always
315 : // fits a pointer.
316 166840 : static inline size_t get_type_size(ccol_data_type type) {
317 166840 : switch (type) {
318 : case ccol_char:
319 : case ccol_signed_char:
320 : case ccol_unsigned_char:
321 : return sizeof(char);
322 : case ccol_short:
323 : case ccol_unsigned_short:
324 : return sizeof(short);
325 : case ccol_int:
326 : case ccol_unsigned_int:
327 : return sizeof(int);
328 : case ccol_long:
329 : case ccol_unsigned_long:
330 : return sizeof(long);
331 : case ccol_long_long:
332 : case ccol_unsigned_long_long:
333 : return sizeof(long long);
334 : case ccol_pointer:
335 : return sizeof(uintptr_t);
336 : case ccol_float:
337 : return sizeof(float);
338 : case ccol_double:
339 : return sizeof(double);
340 : case ccol_long_double:
341 : return sizeof(long double);
342 : default:
343 : return 8;
344 : }
345 : }
346 :
347 : // Tells whether a map with these key and value types uses open addressing
348 : // (both integral) instead of separate chaining; creation calls it once.
349 1756276 : static inline bool should_use_open_addressing(ccol_data_type key_type,
350 : ccol_data_type val_type) {
351 1756276 : return is_type_integral(key_type) && is_type_integral(val_type) &&
352 41716 : get_type_size(key_type) <= 8 && get_type_size(val_type) <= 8;
353 : }
354 :
355 : // Hashes a fixed-width key or a custom hash result in the keyed mode: An xor
356 : // with the secret seed, a multiply, a xorshift and a second multiply. It's
357 : // what a map switches to when its keys collide under the fast hash.
358 : // hash_index_for() reads the top bits, which the last multiply mixes best.
359 : // Every step is a bijection. The xorshift between the multiplies turns the
360 : // carries of the seeded first product into a nonlinear function of the seed,
361 : // so no key set (sequential, or varying only in some fixed bits) clusters the
362 : // same way for every seed, as it would under (k ^ s) * C. A 32-bit size_t uses
363 : // the same steps with lowbias32 constants.
364 5629791 : static inline size_t hash_word_seeded(size_t x, uint64_t seed) {
365 : #if SIZE_MAX == UINT64_MAX
366 5629791 : uint64_t r = ((uint64_t)x ^ seed) * 0xBF58476D1CE4E5B9ULL;
367 5629791 : r ^= r >> 32;
368 5629791 : return (size_t)(r * 0x94D049BB133111EBULL);
369 : #else
370 : uint32_t r = ((uint32_t)x ^ (uint32_t)seed) * 0x7FEB352DU;
371 : r ^= r >> 16;
372 : return (size_t)(r * 0x846CA68BU);
373 : #endif
374 : }
375 :
376 : // Hashes a 64-bit key (long long, double) in the keyed mode. On a 32-bit
377 : // target the 64-bit steps run at the key's width and the upper word is the
378 : // hash; folding the halves together first would make every (a << 32) | b with
379 : // the same a ^ b collide.
380 3994580 : static inline size_t hash_u64_seeded(uint64_t x, uint64_t seed) {
381 : #if SIZE_MAX == UINT64_MAX
382 3994580 : return hash_word_seeded((size_t)x, seed);
383 : #else
384 : uint64_t r = (x ^ seed) * 0xBF58476D1CE4E5B9ULL;
385 : r ^= r >> 32;
386 : return (size_t)((r * 0x94D049BB133111EBULL) >> 32);
387 : #endif
388 : }
389 :
390 : // Hashes a fixed-width key no wider than size_t in the fast mode, where every
391 : // map starts: A Fibonacci multiply, read from the top bits. Sequential keys,
392 : // scaled keys and aligned addresses spread perfectly. Nothing keys it, so
393 : // whoever controls the keys can make them collide; the detection notices and
394 : // switches the map.
395 28396796 : static inline size_t hash_word_fast(size_t x) {
396 : #if SIZE_MAX == UINT64_MAX
397 28396796 : return x * (size_t)0x9E3779B97F4A7C15ULL;
398 : #else
399 : return x * (size_t)0x9E3779B9U;
400 : #endif
401 : }
402 :
403 : // Hashes a 64-bit key in the fast mode; on a 32-bit target the hash is the
404 : // upper word of the 64-bit product.
405 11480574 : static inline size_t hash_u64_fast(uint64_t x) {
406 : #if SIZE_MAX == UINT64_MAX
407 11480574 : return hash_word_fast((size_t)x);
408 : #else
409 : return (size_t)((x * 0x9E3779B97F4A7C15ULL) >> 32);
410 : #endif
411 : }
412 :
413 : // Finalizes a custom hash result in the fast mode with murmur3 fmix. A custom
414 : // hash may keep its entropy in the low bits (an identity, a counter), and this
415 : // carries it to the top bits that the index reads.
416 35290 : static inline size_t hash_custom_fast(size_t h) {
417 : #if SIZE_MAX == UINT64_MAX
418 35290 : uint64_t x = (uint64_t)h;
419 35290 : x ^= x >> 33;
420 35290 : x *= 0xFF51AFD7ED558CCDULL;
421 35290 : x ^= x >> 33;
422 35290 : x *= 0xC4CEB9FE1A85EC53ULL;
423 35290 : x ^= x >> 33;
424 35290 : return (size_t)x;
425 : #else
426 : uint32_t x = (uint32_t)h;
427 : x ^= x >> 16;
428 : x *= 0x85EBCA6BU;
429 : x ^= x >> 13;
430 : x *= 0xC2B2AE35U;
431 : x ^= x >> 16;
432 : return (size_t)x;
433 : #endif
434 : }
435 :
436 : // Rotates a word left by b bits, for SipHash-1-3. SipHash-1-3 is the keyed
437 : // byte hash of every key with no fixed width: A pseudorandom function of its
438 : // 128-bit key, so without the key nobody finds colliding inputs better than by
439 : // chance. Rust and Python use the same variant for their hash tables.
440 25147531 : static inline uint64_t sip_rotl(uint64_t x, unsigned b) {
441 25147531 : return (x << b) | (x >> (64u - b));
442 : }
443 :
444 : // Runs one SipHash round on the four state words in place; siphash13() runs
445 : // it once per input word and three times to finalize.
446 : #define CHMAP_SIPROUND(v0, v1, v2, v3) \
447 : do { \
448 : (v0) += (v1); \
449 : (v1) = sip_rotl((v1), 13); \
450 : (v1) ^= (v0); \
451 : (v0) = sip_rotl((v0), 32); \
452 : (v2) += (v3); \
453 : (v3) = sip_rotl((v3), 16); \
454 : (v3) ^= (v2); \
455 : (v0) += (v3); \
456 : (v3) = sip_rotl((v3), 21); \
457 : (v3) ^= (v0); \
458 : (v2) += (v1); \
459 : (v1) = sip_rotl((v1), 17); \
460 : (v1) ^= (v2); \
461 : (v2) = sip_rotl((v2), 32); \
462 : } while (0)
463 :
464 : // Read 8 or 4 bytes as a little-endian word, the way SipHash defines its
465 : // input, whatever the host's byte order and the pointer's alignment.
466 3933035 : static inline uint64_t sip_load64(const unsigned char* p) {
467 3933035 : uint64_t v;
468 3933035 : memcpy(&v, p, sizeof(v));
469 : #if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
470 : v = __builtin_bswap64(v);
471 : #endif
472 3933035 : return v;
473 : }
474 :
475 5934564 : static inline uint64_t sip_load32(const unsigned char* p) {
476 5934564 : uint32_t v;
477 5934564 : memcpy(&v, p, sizeof(v));
478 : #if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
479 : v = __builtin_bswap32(v);
480 : #endif
481 598602 : return v;
482 : }
483 :
484 : // Reads the last 0 to 7 bytes of a SipHash input as a little-endian word: Two
485 : // overlapping 4-byte reads for 4 to 7 bytes, the first, middle and last byte
486 : // for 1 to 3. Bytes that two reads share are equal, so or-ing them is safe.
487 692855 : static inline uint64_t sip_load_tail(const unsigned char* p, size_t left) {
488 692855 : if (left >= 4) {
489 598602 : return sip_load32(p) | (sip_load32(p + left - 4) << (8u * (left - 4)));
490 : }
491 94253 : if (left == 0) {
492 : return 0;
493 : }
494 13023 : return (uint64_t)p[0] | ((uint64_t)p[left >> 1] << (8u * (left >> 1))) |
495 13023 : ((uint64_t)p[left - 1] << (8u * (left - 1)));
496 : }
497 :
498 : // Computes SipHash-1-3 of len bytes from the initial state sip_v, for the
499 : // keyed byte hash and the long double hash. Words are read through memcpy, so
500 : // the input needs no alignment.
501 : static inline __attribute__((always_inline)) uint64_t
502 692855 : siphash13(const uint64_t sip_v[4], const void* input, size_t len) {
503 692855 : uint64_t v0 = sip_v[0];
504 692855 : uint64_t v1 = sip_v[1];
505 692855 : uint64_t v2 = sip_v[2];
506 692855 : uint64_t v3 = sip_v[3];
507 692855 : const unsigned char* p = (const unsigned char*)input;
508 2068712 : for (size_t blocks = len >> 3; blocks != 0; blocks--) {
509 1375857 : uint64_t m = sip_load64(p);
510 1375857 : v3 ^= m;
511 1375857 : CHMAP_SIPROUND(v0, v1, v2, v3);
512 1375857 : v0 ^= m;
513 1375857 : p += 8;
514 : }
515 692855 : uint64_t b = ((uint64_t)len << 56) | sip_load_tail(p, len & 7u);
516 692855 : v3 ^= b;
517 692855 : CHMAP_SIPROUND(v0, v1, v2, v3);
518 692855 : v0 ^= b;
519 692855 : v2 ^= 0xff;
520 692855 : CHMAP_SIPROUND(v0, v1, v2, v3);
521 692855 : CHMAP_SIPROUND(v0, v1, v2, v3);
522 692855 : CHMAP_SIPROUND(v0, v1, v2, v3);
523 692855 : return v0 ^ v1 ^ v2 ^ v3;
524 : }
525 :
526 : // Hashes a buffer with SipHash-1-3 and folds the result into a size_t; a
527 : // 32-bit size_t keeps both halves.
528 659319 : static inline size_t hash_bytes_keyed(const uint64_t sip_v[4],
529 : const void* input, size_t len) {
530 659319 : uint64_t h = siphash13(sip_v, input, len);
531 : #if SIZE_MAX == UINT64_MAX
532 659319 : return (size_t)h;
533 : #else
534 : return (size_t)(h ^ (h >> 32));
535 : #endif
536 : }
537 :
538 : // XXH64, the fast byte hash, as its specification defines it, with a secret
539 : // seed so colliding keys can't be worked out offline. Some key sets collide
540 : // under every seed (a lane round maps a change of 2^63 to plus or minus 2^30,
541 : // which the next word can cancel); the detection switches such a map to
542 : // SipHash.
543 : #define XXH_P1 0x9E3779B185EBCA87ULL
544 : #define XXH_P2 0xC2B2AE3D27D4EB4FULL
545 : #define XXH_P3 0x165667B19E3779F9ULL
546 : #define XXH_P4 0x85EBCA77C2B2AE63ULL
547 : #define XXH_P5 0x27D4EB2F165667C5ULL
548 :
549 : // One XXH64 lane round: Mixes an 8-byte input word into a lane accumulator.
550 2701540 : static inline uint64_t xxh_round(uint64_t acc, uint64_t input) {
551 2701540 : acc += input * XXH_P2;
552 2701540 : acc = sip_rotl(acc, 31);
553 2701540 : return acc * XXH_P1;
554 : }
555 :
556 : // Folds a lane accumulator into the XXH64 result after the stripes.
557 144362 : static inline uint64_t xxh_merge_round(uint64_t h, uint64_t v) {
558 144362 : h ^= xxh_round(0, v);
559 144362 : return h * XXH_P1 + XXH_P4;
560 : }
561 :
562 : // Computes XXH64 of len bytes with the given seed, exactly as the
563 : // specification defines it; hash_bytes_fast() uses it as the fast byte hash.
564 6441628 : static inline uint64_t xxh64(const void* input, size_t len, uint64_t seed) {
565 6441628 : const unsigned char* p = (const unsigned char*)input;
566 6441628 : const unsigned char* const end = p + len;
567 6441628 : uint64_t h;
568 6441628 : if (len >= 32) {
569 144362 : const unsigned char* const limit = end - 32;
570 144362 : uint64_t v1 = seed + XXH_P1 + XXH_P2;
571 144362 : uint64_t v2 = seed + XXH_P2;
572 144362 : uint64_t v3 = seed;
573 144362 : uint64_t v4 = seed - XXH_P1;
574 264681 : do {
575 264681 : v1 = xxh_round(v1, sip_load64(p));
576 264681 : v2 = xxh_round(v2, sip_load64(p + 8));
577 264681 : v3 = xxh_round(v3, sip_load64(p + 16));
578 264681 : v4 = xxh_round(v4, sip_load64(p + 24));
579 264681 : p += 32;
580 264681 : } while (p <= limit);
581 144362 : h = sip_rotl(v1, 1) + sip_rotl(v2, 7) + sip_rotl(v3, 12) + sip_rotl(v4, 18);
582 144362 : h = xxh_merge_round(h, v1);
583 144362 : h = xxh_merge_round(h, v2);
584 144362 : h = xxh_merge_round(h, v3);
585 144362 : h = xxh_merge_round(h, v4);
586 : } else {
587 6297266 : h = seed + XXH_P5;
588 : }
589 6441628 : h += (uint64_t)len;
590 6441628 : size_t left = (size_t)(end - p);
591 8734125 : for (; left >= 8; left -= 8, p += 8) {
592 2292497 : h ^= xxh_round(0, sip_load64(p));
593 2292497 : h = sip_rotl(h, 27) * XXH_P1 + XXH_P4;
594 : }
595 6441628 : if (left >= 4) {
596 5335962 : h ^= sip_load32(p) * XXH_P1;
597 5335962 : h = sip_rotl(h, 23) * XXH_P2 + XXH_P3;
598 5335962 : p += 4;
599 5335962 : left -= 4;
600 : }
601 21482945 : for (; left != 0; left--, p++) {
602 15041317 : h ^= (uint64_t)*p * XXH_P5;
603 15041317 : h = sip_rotl(h, 11) * XXH_P1;
604 : }
605 6441628 : h ^= h >> 33;
606 6441628 : h *= XXH_P2;
607 6441628 : h ^= h >> 29;
608 6441628 : h *= XXH_P3;
609 6441628 : h ^= h >> 32;
610 6441628 : return h;
611 : }
612 :
613 : // Reduces a hash to an index into a power-of-two table by taking its HIGH
614 : // bits, the bits every hash here mixes best; every reduction goes through
615 : // here. The shift is the leading-zero count of capacity plus one, so only the
616 : // builtin names the width. capacity must be a power of two of at least 2: 1
617 : // makes the shift as wide as the type and 0 reaches __builtin_clz, both
618 : // undefined, and such a shift folds to 0 and puts every key in slot 0.
619 40788114 : static inline size_t hash_index_for(size_t hash_val, size_t capacity) {
620 : #if SIZE_MAX == UINT64_MAX
621 40788114 : return hash_val >>
622 40788114 : ((unsigned)__builtin_clzll((unsigned long long)capacity) + 1u);
623 : #else
624 : return hash_val >> ((unsigned)__builtin_clz((unsigned int)capacity) + 1u);
625 : #endif
626 : }
627 :
628 : // Hashes a long double key by its VALUE, in both modes. A long double's
629 : // padding bits are unspecified (often never written) and differ between two
630 : // copies of one number, so a byte hash would miss equal keys. frexpl() takes
631 : // the value apart, and {scaled mantissa, exponent} goes through SipHash-1-3.
632 : // NaN, +-0.0 and +-infinity never reach frexpl(): Each class is the pair
633 : // {0, class}, which no number produces. Every NaN is one key, because reading
634 : // a NaN's padding is a read of uninitialized memory (long_double_keys_equal()
635 : // matches); +-0.0 is merged up front, since frexpl() needn't keep the sign of
636 : // zero; and infinities can't be converted to an integer.
637 : static __attribute__((noinline)) size_t
638 4137 : hash_long_double_value(long double v, const uint64_t sip_v[4]) {
639 4137 : uint64_t parts[2] = {0, 0};
640 4137 : if (isnan(v)) {
641 6 : parts[1] = 3;
642 4131 : } else if (v == 0.0L) {
643 : parts[1] = 0;
644 4126 : } else if (isinf(v)) {
645 6 : parts[1] = v > 0.0L ? 1 : 2;
646 : } else {
647 4122 : int exp = 0;
648 4122 : long double mantissa = frexpl(v, &exp);
649 4122 : int64_t scaled_mantissa = (int64_t)(mantissa * 4611686018427387904.0L);
650 4122 : parts[0] = (uint64_t)scaled_mantissa;
651 4122 : parts[1] = (uint64_t)(int64_t)exp;
652 : }
653 4137 : return hash_bytes_keyed(sip_v, parts, sizeof(parts));
654 : }
655 :
656 : // The process secret and its once flag. It's picked on the first map creation
657 : // or ccol_chmap_hash_key() call, never in a constructor, so a map that another
658 : // object's constructor creates still gets the final secret, and it never
659 : // changes. Map operations read it directly; whatever hands a map to another
660 : // thread orders the creation, and so the pick, before the use.
661 : static chmap_hash_secret g_chmap_hash_secret;
662 : static ccol__once_flag g_chmap_hash_secret_once = CCOL__ONCE_INIT;
663 :
664 : // Mixes a word with one splitmix64 step, which spreads every input bit over
665 : // every output bit, so chmap_fallback_hash_key() can combine sources of uneven
666 : // quality.
667 4 : static uint64_t chmap_seed_mix(uint64_t x) {
668 4 : x += 0x9E3779B97F4A7C15ULL;
669 4 : x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ULL;
670 4 : x = (x ^ (x >> 27)) * 0x94D049BB133111EBULL;
671 4 : return x ^ (x >> 31);
672 : }
673 :
674 : // Derives the four key words of the secret when getrandom(2) can't answer
675 : // without blocking (no syscall, a seccomp policy, early boot): A mix of both
676 : // clocks, the pid and three addresses that ASLR places. Weaker than the
677 : // kernel, much stronger than a constant, and it never fails.
678 2 : static void chmap_fallback_hash_key(uint64_t out[4]) {
679 2 : struct timespec rt = {0, 0};
680 2 : struct timespec mt = {0, 0};
681 2 : (void)clock_gettime(CLOCK_REALTIME, &rt);
682 2 : (void)clock_gettime(CLOCK_MONOTONIC, &mt);
683 2 : uint64_t x = chmap_seed_mix((uint64_t)rt.tv_sec * 1000000000ULL +
684 2 : (uint64_t)rt.tv_nsec);
685 2 : x = chmap_seed_mix(
686 2 : x ^ ((uint64_t)mt.tv_sec * 1000000000ULL + (uint64_t)mt.tv_nsec));
687 2 : x = chmap_seed_mix(x ^ (uint64_t)getpid());
688 2 : x = chmap_seed_mix(x ^ (uint64_t)(uintptr_t)&x);
689 2 : x = chmap_seed_mix(x ^ (uint64_t)(uintptr_t)&g_chmap_hash_secret);
690 2 : x = chmap_seed_mix(x ^ (uint64_t)(uintptr_t)&clock_gettime);
691 2 : out[0] = x;
692 2 : out[1] = chmap_seed_mix(out[0]);
693 2 : out[2] = chmap_seed_mix(out[1]);
694 2 : out[3] = chmap_seed_mix(out[2]);
695 2 : }
696 :
697 : // Fills the SipHash state sip_v from the key (k0, k1), so a hash doesn't redo
698 : // the four xors.
699 2132 : static void chmap_sip_state_from_key(uint64_t k0, uint64_t k1,
700 : uint64_t sip_v[4]) {
701 2132 : sip_v[0] = k0 ^ 0x736F6D6570736575ULL;
702 2132 : sip_v[1] = k1 ^ 0x646F72616E646F6DULL;
703 2132 : sip_v[2] = k0 ^ 0x6C7967656E657261ULL;
704 2132 : sip_v[3] = k1 ^ 0x7465646279746573ULL;
705 : }
706 :
707 : // Picks the process secret and writes it to g_chmap_hash_secret: 32 random
708 : // bytes (or the fallback) give k0, k1, int_seed and byte_seed. It runs once,
709 : // through g_chmap_hash_secret_once.
710 66 : static void chmap_init_process_hash_secret(void) {
711 66 : uint64_t key[4] = {0, 0, 0, 0};
712 66 : if (!ccol_random_bytes(key, sizeof(key))) {
713 0 : chmap_fallback_hash_key(key);
714 : }
715 66 : chmap_sip_state_from_key(key[0], key[1], g_chmap_hash_secret.sip_v);
716 66 : g_chmap_hash_secret.int_seed = key[2];
717 66 : g_chmap_hash_secret.byte_seed = key[3];
718 66 : }
719 :
720 : // Gives the process secret, picking it on the first call through the once
721 : // flag. Only the creation path and ccol_chmap_hash_key() call it, never an
722 : // insert or a lookup, which read g_chmap_hash_secret directly.
723 1800609 : static const chmap_hash_secret* chmap_process_hash_secret(void) {
724 1800609 : ccol__call_once(g_chmap_hash_secret_once, chmap_init_process_hash_secret);
725 1800609 : return &g_chmap_hash_secret;
726 : }
727 :
728 : // Hashes a buffer in the fast mode with XXH64 seeded with byte_seed and gives
729 : // a size_t; a 32-bit size_t keeps both halves.
730 5151388 : static inline size_t hash_bytes_fast(const void* input, size_t len) {
731 5151388 : uint64_t h = xxh64(input, len, g_chmap_hash_secret.byte_seed);
732 : #if SIZE_MAX == UINT64_MAX
733 5151388 : return (size_t)h;
734 : #else
735 : return (size_t)(h ^ (h >> 32));
736 : #endif
737 : }
738 :
739 : // Hashes a buffer with the keyed SipHash, out of line, so the fast byte hash
740 : // stays inline in the functions that hash both ways.
741 69936 : static __attribute__((noinline)) size_t hash_bytes_keyed_ool(const void* input,
742 : size_t len) {
743 69936 : return hash_bytes_keyed(g_chmap_hash_secret.sip_v, input, len);
744 : }
745 :
746 : // Hash a fixed-width key no wider than size_t, or a 64-bit key, in the mode
747 : // that keyed names; hash_key_data() picks between them.
748 : static inline __attribute__((always_inline)) size_t
749 18406162 : hash_word_mode(size_t x, bool keyed, uint64_t int_seed) {
750 17372384 : return keyed ? hash_word_seeded(x, int_seed) : hash_word_fast(x);
751 : }
752 :
753 : static inline __attribute__((always_inline)) size_t
754 15475154 : hash_u64_mode(uint64_t x, bool keyed, uint64_t int_seed) {
755 12921248 : return keyed ? hash_u64_seeded(x, int_seed) : hash_u64_fast(x);
756 : }
757 :
758 : // Hashes a key with the function for its type and the mode: Integers, float,
759 : // double and pointers through hash_word_mode() or hash_u64_mode(), long double
760 : // through hash_long_double_value() in both modes, anything else through
761 : // hash_bytes_fast() or hash_bytes_keyed_ool(). A custom proc's result goes
762 : // through hash_custom_fast() or hash_word_seeded(). Only separate chaining
763 : // reaches the long double and byte cases. Multi-byte reads go through memcpy
764 : // of a constant size, because key_ptr can come from a caller's cmap_pair with
765 : // no alignment. The callers pass int_seed so loops that write through a byte
766 : // pointer keep it in a register.
767 : static inline __attribute__((always_inline)) size_t
768 39287338 : hash_key_data(const void* key_ptr, size_t key_size, ccol_data_type key_type,
769 : ccol_hashing_proc custom_proc, bool keyed, uint64_t int_seed) {
770 39287338 : if (custom_proc) {
771 180561 : size_t h = (size_t)custom_proc(key_ptr, key_size);
772 180561 : return keyed ? hash_word_seeded(h, int_seed) : hash_custom_fast(h);
773 : }
774 :
775 36186922 : switch (key_type) {
776 26 : case ccol_char:
777 : case ccol_signed_char:
778 : case ccol_unsigned_char:
779 26 : return hash_word_mode((size_t)*(const uint8_t*)key_ptr, keyed, int_seed);
780 : case ccol_short:
781 : case ccol_unsigned_short: {
782 9 : uint16_t bits;
783 9 : memcpy(&bits, key_ptr, sizeof(bits));
784 9 : return hash_word_mode((size_t)bits, keyed, int_seed);
785 : }
786 : case ccol_int:
787 : case ccol_unsigned_int: {
788 844497 : uint32_t bits;
789 818630 : memcpy(&bits, key_ptr, sizeof(bits));
790 844497 : return hash_word_mode((size_t)bits, keyed, int_seed);
791 : }
792 : case ccol_long:
793 : case ccol_unsigned_long: {
794 : #if SIZE_MAX == UINT64_MAX
795 17561598 : uint64_t bits;
796 16570359 : memcpy(&bits, key_ptr, sizeof(bits));
797 17561598 : return hash_word_mode((size_t)bits, keyed, int_seed);
798 : #else
799 : uint32_t bits;
800 : memcpy(&bits, key_ptr, sizeof(bits));
801 : return hash_word_mode((size_t)bits, keyed, int_seed);
802 : #endif
803 : }
804 : case ccol_long_long:
805 : case ccol_unsigned_long_long: {
806 15382995 : uint64_t bits;
807 13531990 : memcpy(&bits, key_ptr, sizeof(bits));
808 15382995 : return hash_u64_mode(bits, keyed, int_seed);
809 : }
810 : case ccol_float: {
811 19 : uint32_t bits;
812 18 : memcpy(&bits, key_ptr, 4);
813 19 : return hash_word_mode((size_t)bits, keyed, int_seed);
814 : }
815 : case ccol_double: {
816 92159 : uint64_t bits;
817 84783 : memcpy(&bits, key_ptr, 8);
818 92159 : return hash_u64_mode(bits, keyed, int_seed);
819 : }
820 : case ccol_pointer: {
821 13 : uintptr_t bits;
822 13 : memcpy(&bits, key_ptr, sizeof(uintptr_t));
823 13 : return hash_word_mode((size_t)bits, keyed, int_seed);
824 : }
825 : case ccol_long_double: {
826 4137 : long double v;
827 4137 : memcpy(&v, key_ptr, sizeof(v));
828 4137 : return hash_long_double_value(v, g_chmap_hash_secret.sip_v);
829 : }
830 5220609 : default:
831 69936 : return keyed ? hash_bytes_keyed_ool(key_ptr, key_size)
832 5220609 : : hash_bytes_fast(key_ptr, key_size);
833 : }
834 : }
835 :
836 : // True when [a, a + a_size) and [b, b + b_size) overlap. An update uses it to
837 : // catch a value pointer that aliases the storage it's about to change.
838 14411 : static inline bool ranges_overlap(const void* a, size_t a_size, const void* b,
839 : size_t b_size) {
840 14411 : if (a_size == 0 || b_size == 0) return false;
841 14411 : uintptr_t a_start = (uintptr_t)a;
842 14411 : uintptr_t a_end = a_start + a_size;
843 14411 : uintptr_t b_start = (uintptr_t)b;
844 14411 : uintptr_t b_end = b_start + b_size;
845 14411 : return a_start < b_end && b_start < a_end;
846 : }
847 :
848 : // White-box work counters and their accessors for the tests: Probe steps,
849 : // rehashes, shift moves and steps, chain node visits, and the fast attempts of
850 : // keyed growths. They let a test assert on work instead of time. Each is
851 : // atomic with relaxed ordering, because the probe loops run on many threads
852 : // that share a map, and the tests read them only after joining those threads.
853 : // The COUNT macros and CHMAP_NOTE_RETRY() add to them (the latter calls
854 : // chmap_note_retry()), and CHMAP_RETRY_WORK() adds n to an attempt's local
855 : // work count; in a normal build they all expand to nothing.
856 : #ifdef RUNNING_UNIT_TESTS
857 : static _Atomic unsigned long long g_oa_probe_steps_for_tests = 0;
858 : // Gives the probe step count.
859 4045 : unsigned long long chashmap_oa_probe_steps_for_tests(void) {
860 4045 : return atomic_load_explicit(&g_oa_probe_steps_for_tests,
861 : memory_order_relaxed);
862 : }
863 : // Sets the probe step count to 0.
864 4047 : void chashmap_reset_oa_probe_steps_for_tests(void) {
865 4047 : atomic_store_explicit(&g_oa_probe_steps_for_tests, 0, memory_order_relaxed);
866 4047 : }
867 : #define OA_COUNT_PROBE() \
868 : (atomic_fetch_add_explicit(&g_oa_probe_steps_for_tests, 1ull, \
869 : memory_order_relaxed))
870 : static _Atomic unsigned long long g_oa_rehashes_for_tests = 0;
871 : // Gives the count of successful open-addressing rehashes.
872 16 : unsigned long long chashmap_oa_rehashes_for_tests(void) {
873 16 : return atomic_load_explicit(&g_oa_rehashes_for_tests, memory_order_relaxed);
874 : }
875 : #define OA_COUNT_REHASH() \
876 : (atomic_fetch_add_explicit(&g_oa_rehashes_for_tests, 1ull, \
877 : memory_order_relaxed))
878 : static _Atomic unsigned long long g_oa_shift_moves_for_tests = 0;
879 : // Gives how many entries backward-shift deletion moved.
880 3 : unsigned long long chashmap_oa_shift_moves_for_tests(void) {
881 3 : return atomic_load_explicit(&g_oa_shift_moves_for_tests,
882 : memory_order_relaxed);
883 : }
884 : #define OA_COUNT_SHIFT_MOVE() \
885 : (atomic_fetch_add_explicit(&g_oa_shift_moves_for_tests, 1ull, \
886 : memory_order_relaxed))
887 : static _Atomic unsigned long long g_oa_shift_steps_for_tests = 0;
888 : // Gives how many slots the backward-shift walks looked at.
889 2 : unsigned long long chashmap_oa_shift_steps_for_tests(void) {
890 2 : return atomic_load_explicit(&g_oa_shift_steps_for_tests,
891 : memory_order_relaxed);
892 : }
893 : #define OA_COUNT_SHIFT_STEP() \
894 : (atomic_fetch_add_explicit(&g_oa_shift_steps_for_tests, 1ull, \
895 : memory_order_relaxed))
896 : static _Atomic unsigned long long g_sc_node_visits_for_tests = 0;
897 : // Gives how many chain nodes the chaining searches visited.
898 10 : unsigned long long chashmap_sc_node_visits_for_tests(void) {
899 10 : return atomic_load_explicit(&g_sc_node_visits_for_tests,
900 : memory_order_relaxed);
901 : }
902 : // Sets the chain node count to 0.
903 12 : void chashmap_reset_sc_node_visits_for_tests(void) {
904 12 : atomic_store_explicit(&g_sc_node_visits_for_tests, 0, memory_order_relaxed);
905 12 : }
906 : #define SC_COUNT_NODE_VISIT() \
907 : (atomic_fetch_add_explicit(&g_sc_node_visits_for_tests, 1ull, \
908 : memory_order_relaxed))
909 : static _Atomic unsigned long long g_retries_for_tests = 0;
910 : static _Atomic unsigned long long g_retry_failures_for_tests = 0;
911 : static _Atomic unsigned long long g_retry_failed_work_for_tests = 0;
912 : static _Atomic size_t g_retry_last_work_for_tests = 0;
913 : static _Atomic size_t g_retry_last_count_for_tests = 0;
914 : static _Atomic size_t g_retry_last_capacity_for_tests = 0;
915 : // Gives how many fast attempts keyed growths made.
916 22 : unsigned long long chashmap_retries_for_tests(void) {
917 22 : return atomic_load_explicit(&g_retries_for_tests, memory_order_relaxed);
918 : }
919 : // Gives how many of those attempts failed.
920 166597 : unsigned long long chashmap_retry_failures_for_tests(void) {
921 166597 : return atomic_load_explicit(&g_retry_failures_for_tests,
922 : memory_order_relaxed);
923 : }
924 : // Gives the total work of the failed attempts.
925 16 : unsigned long long chashmap_retry_failed_work_for_tests(void) {
926 16 : return atomic_load_explicit(&g_retry_failed_work_for_tests,
927 : memory_order_relaxed);
928 : }
929 : // Gives the work, count and capacity of the last failed attempt.
930 29 : void chashmap_last_failed_retry_for_tests(size_t* work, size_t* count,
931 : size_t* capacity) {
932 29 : *work =
933 29 : atomic_load_explicit(&g_retry_last_work_for_tests, memory_order_relaxed);
934 29 : *count =
935 29 : atomic_load_explicit(&g_retry_last_count_for_tests, memory_order_relaxed);
936 29 : *capacity = atomic_load_explicit(&g_retry_last_capacity_for_tests,
937 : memory_order_relaxed);
938 29 : }
939 : // Records one fast attempt of a keyed growth for the test counters, and its
940 : // work, count and capacity when it failed.
941 301 : static void chmap_note_retry(bool failed, size_t work, size_t count,
942 : size_t capacity) {
943 301 : atomic_fetch_add_explicit(&g_retries_for_tests, 1ull, memory_order_relaxed);
944 301 : if (!failed) return;
945 146 : atomic_fetch_add_explicit(&g_retry_failures_for_tests, 1ull,
946 : memory_order_relaxed);
947 146 : atomic_fetch_add_explicit(&g_retry_failed_work_for_tests,
948 : (unsigned long long)work, memory_order_relaxed);
949 146 : atomic_store_explicit(&g_retry_last_work_for_tests, work,
950 : memory_order_relaxed);
951 146 : atomic_store_explicit(&g_retry_last_count_for_tests, count,
952 : memory_order_relaxed);
953 146 : atomic_store_explicit(&g_retry_last_capacity_for_tests, capacity,
954 : memory_order_relaxed);
955 : }
956 : #define CHMAP_NOTE_RETRY(failed, work, count, capacity) \
957 : chmap_note_retry((failed), (work), (count), (capacity))
958 : #define CHMAP_RETRY_WORK(var, n) ((var) += (n))
959 : #else
960 : #define CHMAP_NOTE_RETRY(failed, work, count, capacity) ((void)0)
961 : #define CHMAP_RETRY_WORK(var, n) ((void)0)
962 : #define OA_COUNT_SHIFT_MOVE() ((void)0)
963 : #define OA_COUNT_SHIFT_STEP() ((void)0)
964 : #define OA_COUNT_PROBE() ((void)0)
965 : #define OA_COUNT_REHASH() ((void)0)
966 : #define SC_COUNT_NODE_VISIT() ((void)0)
967 : #endif
968 :
969 : // Widens a key to the 64-bit form a slot stores (zeroed, then key_size bytes
970 : // copied), so a probe compares integers instead of calling memcmp. The switch
971 : // gives each copy a constant size. Every entry point checks the size against
972 : // the type first; the default case clamps anyway, since the target is one
973 : // 8-byte object.
974 16989474 : static inline uint64_t oa_widen_key(const void* key_ptr, size_t key_size) {
975 16989474 : uint64_t k = 0;
976 16989474 : switch (key_size) {
977 : case 1:
978 26 : memcpy(&k, key_ptr, 1);
979 26 : break;
980 : case 2:
981 9 : memcpy(&k, key_ptr, 2);
982 9 : break;
983 : case 4:
984 774917 : memcpy(&k, key_ptr, 4);
985 774917 : break;
986 : case 8:
987 16214522 : memcpy(&k, key_ptr, 8);
988 16214522 : break;
989 0 : default:
990 0 : memcpy(&k, key_ptr, key_size > sizeof(k) ? sizeof(k) : key_size);
991 0 : break;
992 : }
993 16989474 : return k;
994 : }
995 :
996 : // Compares a slot's key with a key that oa_widen_key() widened outside the
997 : // probe loop.
998 69090062 : static inline bool oa_keys_equal(const oa_slot* slot, uint64_t probe_key) {
999 69090062 : return slot->key_data == probe_key;
1000 : }
1001 :
1002 : // Fills out with {&slots[index].val_data, val_size}, the value pair that every
1003 : // open-addressing lookup reports.
1004 6109786 : static inline void oa_fill_val_pair(const open_addr_map* map, size_t index,
1005 : cmap_pair* out) {
1006 6109786 : out->ptr = &map->slots[index].val_data;
1007 6109786 : out->size = map->val_size;
1008 8001 : }
1009 :
1010 : // A table block holds the slots and then one metadata byte per slot, and
1011 : // nothing else, so a growth faults in only 17 bytes per slot.
1012 : #define OA_BLOCK_BYTES_PER_SLOT (sizeof(oa_slot) + 1)
1013 :
1014 : // Allocates a zeroed block of capacity slots plus their metadata bytes and
1015 : // reports where the metadata starts. It checks the multiplication itself,
1016 : // because a product that wraps would give a small block that the probes then
1017 : // walk past.
1018 43727 : static oa_slot* oa_alloc_block(ccol_memmgmt_procs* m_procs, size_t capacity,
1019 : uint8_t** metadata_out) {
1020 43727 : if (capacity == 0 || capacity > SIZE_MAX / OA_BLOCK_BYTES_PER_SLOT) {
1021 : return NULL;
1022 : }
1023 43727 : oa_slot* slots = (oa_slot*)ccol__mem_calloc(
1024 : m_procs, 1, capacity * OA_BLOCK_BYTES_PER_SLOT);
1025 43727 : if (!slots) return NULL;
1026 43694 : *metadata_out = (uint8_t*)(slots + capacity);
1027 43694 : return slots;
1028 : }
1029 :
1030 : // Gives the smallest probe_span of a table: OA_DEEP_INSERT, or the whole
1031 : // table when smaller.
1032 61674 : static inline size_t oa_min_probe_span(size_t capacity) {
1033 61674 : return capacity < OA_DEEP_INSERT ? capacity : OA_DEEP_INSERT;
1034 : }
1035 :
1036 : // Sets up the open-addressing state in the map's block and allocates a zeroed
1037 : // table. Gives false with nothing allocated on failure.
1038 41704 : static bool oa_init(open_addr_map* map, size_t capacity,
1039 : ccol_data_type key_type, ccol_data_type val_type,
1040 : size_t key_size, size_t val_size,
1041 : ccol_memmgmt_procs* m_procs,
1042 : ccol_hashing_proc custom_hashing_proc) {
1043 83408 : map->slots = oa_alloc_block(m_procs, capacity, &map->metadata);
1044 41704 : if (!map->slots) return false;
1045 :
1046 41692 : map->capacity = capacity;
1047 41692 : map->probe_span = oa_min_probe_span(capacity);
1048 41692 : map->count = 0;
1049 41692 : map->custom_hashing_proc = custom_hashing_proc;
1050 41692 : map->key_type = key_type;
1051 41692 : map->val_type = val_type;
1052 41692 : map->key_size = key_size;
1053 41692 : map->val_size = val_size;
1054 41692 : map->m_procs = m_procs;
1055 41692 : return true;
1056 : }
1057 :
1058 : // The parameters of oa_insert_cap(): Slots per doubling, and the log2 size
1059 : // from which the cap stays fixed.
1060 : #define OA_CAP_PER_DOUBLING 24u
1061 : #define OA_CAP_LOG2_CEILING 12u
1062 : // Gives the cap on the displacement of one insert into a fast table of
1063 : // capacity slots: 24 slots per doubling up to 4096 slots, then 288. An insert
1064 : // past it switches the map at once. The cap sits above what a random function
1065 : // produces (at load 0.70 one insert in 1.4e9 passes 288), so ordinary keys
1066 : // never trigger it.
1067 16492 : static inline size_t oa_insert_cap(size_t capacity) {
1068 16492 : unsigned k = chmap_log2_pow2(capacity);
1069 16492 : return (size_t)OA_CAP_PER_DOUBLING *
1070 16492 : (k < OA_CAP_LOG2_CEILING ? k : OA_CAP_LOG2_CEILING);
1071 : }
1072 :
1073 : // Gives the largest count a table holds after an insert that didn't grow it,
1074 : // which caps the load a window bound assumes.
1075 87290 : static inline size_t oa_max_count(size_t capacity) {
1076 87290 : return (capacity / 10) * 7 + ((capacity % 10) * 7) / 10 + 1;
1077 : }
1078 :
1079 : // The bound on the displacement sum of a window's 256 inserts: 256 *
1080 : // (5 * E(a) + 0.5) for 4096 slots or more, 6 * E(a) for smaller tables, with
1081 : // E(a) = (1 / (1 - a)^2 - 1) / 2 the mean displacement under a random function.
1082 : // a is the highest load the window can reach (start count plus 256, capped
1083 : // where the table grows), never the load at its end, which a bulk delete can
1084 : // pull down. Computed in integers in 16.16 fixed point, within 1 percent.
1085 87290 : static uint16_t oa_window_bound(size_t start_count, size_t capacity) {
1086 87290 : size_t limit = oa_max_count(capacity);
1087 174580 : size_t judged =
1088 87290 : start_count < limit && limit - start_count > CHMAP_WINDOW_INSERTS
1089 : ? start_count + CHMAP_WINDOW_INSERTS
1090 123681 : : limit;
1091 87290 : uint64_t a = chmap_load_q16(judged, capacity);
1092 87290 : if (a > 65535u) a = 65535u;
1093 87290 : uint64_t d = 65536u - a;
1094 87290 : uint64_t d2 = d * d;
1095 87290 : uint64_t mul = capacity >= 4096 ? 640u : 768u;
1096 87290 : uint64_t bound = mul * ((1ULL << 32) - d2) / d2 + 128u;
1097 87290 : return bound > UINT16_MAX ? UINT16_MAX : (uint16_t)bound;
1098 : }
1099 :
1100 : // Starts a new insert window of an open-addressing map and computes its
1101 : // bound; a keyed table skips the division, since it's never judged.
1102 65796 : static inline void oa_window_restart(open_addr_map* map) {
1103 65796 : struct chashmap* chm = chmap_of_oa(map);
1104 65796 : chm->insert_window = CHMAP_WINDOW_START;
1105 131592 : chm->window_bound = chm->hash_mode == CHMAP_HASH_KEYED
1106 : ? UINT16_MAX
1107 60262 : : oa_window_bound(map->count, map->capacity);
1108 41692 : }
1109 :
1110 : // Places every live entry of the old table into the zeroed new_slots with the
1111 : // hash of the mode keyed names, for oa_rebuild(), and gives the largest
1112 : // displacement, which sets probe_span. The table stores no hash, so each one
1113 : // is computed again.
1114 1979 : static size_t oa_place_all(const open_addr_map* map, oa_slot* new_slots,
1115 : uint8_t* new_metadata, size_t new_capacity,
1116 : const oa_slot* old_slots,
1117 : const uint8_t* old_metadata, size_t old_capacity,
1118 : bool keyed) {
1119 1979 : const size_t mask = new_capacity - 1;
1120 1979 : const uint64_t int_seed = g_chmap_hash_secret.int_seed;
1121 1979 : size_t largest = 0;
1122 19834107 : for (size_t i = 0; i < old_capacity; i++) {
1123 19832128 : if (!(old_metadata[i] & SLOT_OCCUPIED)) continue;
1124 8684663 : size_t hash_val =
1125 17369326 : hash_key_data(&old_slots[i].key_data, map->key_size, map->key_type,
1126 8684663 : map->custom_hashing_proc, keyed, int_seed);
1127 8684663 : size_t home = hash_index_for(hash_val, new_capacity);
1128 8684663 : size_t index = home;
1129 :
1130 8684663 : __builtin_prefetch(&new_slots[(index + 1) & mask], 1, 1);
1131 :
1132 14533535 : while (new_metadata[index] & SLOT_OCCUPIED) {
1133 5848872 : index = (index + 1) & mask;
1134 5848872 : __builtin_prefetch(&new_slots[(index + 1) & mask], 1, 1);
1135 : }
1136 :
1137 8684663 : new_slots[index] = old_slots[i];
1138 8684663 : new_metadata[index] = SLOT_OCCUPIED;
1139 8684663 : size_t displacement = (index - home) & mask;
1140 28497254 : if (displacement > largest) largest = displacement;
1141 : }
1142 1979 : return largest;
1143 : }
1144 :
1145 : // The slack in a fast attempt's displacement budget.
1146 : #define OA_ATTEMPT_SLACK 64u
1147 :
1148 : // Fills the new table with the fast hash when a keyed table grows, so a map
1149 : // whose keys spread again under the cheap hash goes back to it. It works like
1150 : // oa_place_all(), but gives SIZE_MAX as soon as an entry lands more than
1151 : // oa_insert_cap() from home or the displacements pass count +
1152 : // OA_ATTEMPT_SLACK; random keys never hit either limit. The abort keeps a
1153 : // failed attempt under 2 * count + cap + 65 slots, where keys made to collide
1154 : // would otherwise cost quadratic time.
1155 : static __attribute__((noinline)) size_t
1156 118 : oa_place_all_fast_attempt(const open_addr_map* map, oa_slot* new_slots,
1157 : uint8_t* new_metadata, size_t new_capacity) {
1158 118 : const size_t mask = new_capacity - 1;
1159 118 : const size_t cap = oa_insert_cap(new_capacity);
1160 118 : const size_t budget = map->count + OA_ATTEMPT_SLACK;
1161 118 : const oa_slot* old_slots = map->slots;
1162 118 : const uint8_t* old_metadata = map->metadata;
1163 118 : size_t largest = 0, sum = 0, work = 0;
1164 118 : size_t result = SIZE_MAX;
1165 961035 : for (size_t i = 0; i < map->capacity; i++) {
1166 961012 : if (!(old_metadata[i] & SLOT_OCCUPIED)) continue;
1167 673576 : size_t hash_val =
1168 1347152 : hash_key_data(&old_slots[i].key_data, map->key_size, map->key_type,
1169 673576 : map->custom_hashing_proc, false, 0);
1170 673576 : size_t index = hash_index_for(hash_val, new_capacity);
1171 673576 : size_t displacement = 0;
1172 673576 : CHMAP_RETRY_WORK(work, 1);
1173 1169297 : while (new_metadata[index] & SLOT_OCCUPIED) {
1174 495722 : if (displacement == cap) goto out;
1175 495721 : index = (index + 1) & mask;
1176 495721 : displacement++;
1177 495721 : CHMAP_RETRY_WORK(work, 1);
1178 : }
1179 673575 : new_slots[index] = old_slots[i];
1180 673575 : new_metadata[index] = SLOT_OCCUPIED;
1181 673575 : if (displacement > largest) largest = displacement;
1182 673575 : sum += displacement;
1183 673575 : if (sum > budget) goto out;
1184 : }
1185 : result = largest;
1186 118 : out:
1187 118 : CHMAP_NOTE_RETRY(result == SIZE_MAX, work, map->count, new_capacity);
1188 118 : (void)work;
1189 118 : return result;
1190 : }
1191 :
1192 : // Rebuilds the table at new_capacity with the hash of the mode keyed names,
1193 : // for growth, shrink and the switch, and restarts the window. A fast rebuild
1194 : // whose largest displacement passes the new cap (a shrink can merge clusters)
1195 : // refills the same block keyed. Asking for fast on a keyed table is a growth's
1196 : // fast attempt, and a failure refills the same block keyed. Gives
1197 : // ccol_not_enough_memory with the map unchanged when the block can't be
1198 : // allocated.
1199 2021 : static ccol_retval oa_rebuild(open_addr_map* map, size_t new_capacity,
1200 : bool keyed) {
1201 2021 : uint8_t* new_metadata = NULL;
1202 2021 : oa_slot* new_slots =
1203 2021 : oa_alloc_block(map->m_procs, new_capacity, &new_metadata);
1204 2021 : if (!new_slots) {
1205 : return ccol_not_enough_memory;
1206 : }
1207 :
1208 2001 : size_t largest;
1209 2001 : if (!keyed && oa_keyed(map)) {
1210 118 : largest =
1211 118 : oa_place_all_fast_attempt(map, new_slots, new_metadata, new_capacity);
1212 : } else {
1213 1883 : largest = oa_place_all(map, new_slots, new_metadata, new_capacity,
1214 1883 : map->slots, map->metadata, map->capacity, keyed);
1215 : }
1216 2001 : if (!keyed && largest > oa_insert_cap(new_capacity)) {
1217 96 : memset(new_slots, 0, new_capacity * OA_BLOCK_BYTES_PER_SLOT);
1218 96 : keyed = true;
1219 96 : largest = oa_place_all(map, new_slots, new_metadata, new_capacity,
1220 96 : map->slots, map->metadata, map->capacity, keyed);
1221 : }
1222 :
1223 2001 : ccol__mem_free(map->m_procs, map->slots);
1224 2001 : map->slots = new_slots;
1225 2001 : map->metadata = new_metadata;
1226 2001 : map->capacity = new_capacity;
1227 2001 : size_t span = oa_min_probe_span(new_capacity);
1228 2001 : map->probe_span = largest + 1 > span ? largest + 1 : span;
1229 2001 : chmap_of_oa(map)->hash_mode = keyed ? CHMAP_HASH_KEYED : CHMAP_HASH_FAST;
1230 2001 : oa_window_restart(map);
1231 2001 : OA_COUNT_REHASH();
1232 2001 : return ccol_success;
1233 : }
1234 :
1235 : // Gives the capacity a growth rehashes to: The smallest power of two at or
1236 : // above twice the live count, at least the minimum. The load after it is
1237 : // between a quarter and a half, so a delete can't shrink it straight back and
1238 : // growth and shrink can't alternate.
1239 1259 : static size_t oa_rehash_capacity_for(size_t live_after_insert) {
1240 1259 : if (live_after_insert > ccol__max_power_of_two_size / 2) {
1241 : return ccol__max_power_of_two_size;
1242 : }
1243 1259 : size_t wanted = ccol__find_nearest_gte_power_of_two(2 * live_after_insert);
1244 1259 : return wanted < minimum_allowed_bucket_array_size
1245 : ? minimum_allowed_bucket_array_size
1246 1259 : : wanted;
1247 : }
1248 :
1249 : // Tells whether count / capacity > 0.70, the growth trigger, in integers
1250 : // (count * 10 > capacity * 7), with a division form for capacities where the
1251 : // products could overflow.
1252 5788136 : static inline bool oa_above_grow_load(size_t count, size_t capacity) {
1253 5788136 : if (__builtin_expect(capacity <= SIZE_MAX / 10, 1)) {
1254 5788136 : return count * 10 > capacity * 7;
1255 : }
1256 0 : return count > (capacity / 10) * 7 + ((capacity % 10) * 7) / 10;
1257 : }
1258 :
1259 : // Finds the first empty slot in probe order from hash_val's home, or gives
1260 : // capacity when there's none. The key must be known to be absent; the insert
1261 : // uses it after a rehash makes its earlier probe stale.
1262 1241 : static size_t oa_find_insertion_slot(const open_addr_map* map,
1263 : size_t hash_val) {
1264 1241 : size_t index = hash_index_for(hash_val, map->capacity);
1265 1241 : size_t start_index = index;
1266 :
1267 1241 : __builtin_prefetch(&map->slots[index], 0, 1);
1268 :
1269 16775 : do {
1270 16775 : OA_COUNT_PROBE();
1271 16775 : __builtin_prefetch(&map->slots[(index + 1) & (map->capacity - 1)], 0, 1);
1272 :
1273 16775 : if (!(map->metadata[index] & SLOT_OCCUPIED)) {
1274 1241 : return index;
1275 : }
1276 :
1277 15534 : index = (index + 1) & (map->capacity - 1);
1278 15534 : } while (index != start_index);
1279 :
1280 : return map->capacity;
1281 : }
1282 :
1283 : // Finds the slot of a key that's present, so a switch can tell the insert
1284 : // where its new key moved. The key buffer is as wide as any key type, because
1285 : // the compiler can't see that this backend never has a long double.
1286 71 : static size_t oa_find_stored_key(open_addr_map* map, uint64_t key) {
1287 71 : union {
1288 : uint64_t word;
1289 : long double widest;
1290 : } buf;
1291 71 : memset(&buf, 0, sizeof(buf));
1292 71 : buf.word = key;
1293 142 : size_t hash_val = hash_key_data(&buf, map->key_size, map->key_type,
1294 71 : map->custom_hashing_proc, oa_keyed(map),
1295 : g_chmap_hash_secret.int_seed);
1296 71 : size_t index = hash_index_for(hash_val, map->capacity);
1297 114 : for (size_t left = map->probe_span; left != 0; left--) {
1298 114 : OA_COUNT_PROBE();
1299 114 : if ((map->metadata[index] & SLOT_OCCUPIED) &&
1300 114 : oa_keys_equal(&map->slots[index], key)) {
1301 71 : return index;
1302 : }
1303 43 : index = (index + 1) & (map->capacity - 1);
1304 : }
1305 0 : ccol__assert(false);
1306 : return index;
1307 : }
1308 :
1309 : // Switches a fast table to keyed at the same capacity and gives the new slot
1310 : // of the key at index. When the rebuild can't allocate, nothing changes and a
1311 : // later trigger tries again.
1312 72 : static size_t oa_switch_keeping(open_addr_map* map, size_t index) {
1313 72 : uint64_t key = map->slots[index].key_data;
1314 72 : if (oa_rebuild(map, map->capacity, true) != ccol_success) {
1315 : return index;
1316 : }
1317 71 : return oa_find_stored_key(map, key);
1318 : }
1319 :
1320 : // Widens probe_span to cover a new key displaced OA_DEEP_INSERT or more, and
1321 : // switches a fast table when the key is past its cap. It's the cold path of
1322 : // the insert. Gives the key's slot, which the switch can move.
1323 : static __attribute__((noinline)) size_t
1324 16986 : oa_note_deep_insert(open_addr_map* map, size_t index, size_t displacement) {
1325 16986 : if (displacement >= map->probe_span) {
1326 8783 : map->probe_span = displacement + 1;
1327 : }
1328 16986 : if (!oa_keyed(map) && displacement > oa_insert_cap(map->capacity)) {
1329 49 : index = oa_switch_keeping(map, index);
1330 : }
1331 16986 : return index;
1332 : }
1333 :
1334 : // Judges a window that just ended and switches a fast table whose sum passes
1335 : // the bound; a cold path of the insert. Gives the key's slot, which the switch
1336 : // can move.
1337 22096 : static __attribute__((noinline)) size_t oa_window_end(open_addr_map* map,
1338 : size_t index) {
1339 22096 : struct chashmap* chm = chmap_of_oa(map);
1340 22096 : bool switch_now = chm->hash_mode == CHMAP_HASH_FAST &&
1341 16937 : chm->insert_window > chm->window_bound;
1342 22096 : oa_window_restart(map);
1343 22096 : if (switch_now) {
1344 23 : index = oa_switch_keeping(map, index);
1345 : }
1346 22096 : return index;
1347 : }
1348 :
1349 : // Grows the table and inserts a new key into it, for an insert into a table
1350 : // above its growth load (the cold path of oa_insert_impl()). Growth asks for
1351 : // the fast hash in either mode, and the displacement is reported like any
1352 : // insert's. key_pair and val_pair can point into the block the rebuild frees,
1353 : // so both sizes and both sets of bytes are copied first. When the growth
1354 : // can't allocate, the entry goes into the old table's empty slot (index) if
1355 : // found_empty says there is one, else it gives ccol_not_enough_memory; a grown
1356 : // table with no room gives ccol_container_full.
1357 1259 : static __attribute__((noinline)) ccol_retval oa_insert_with_growth(
1358 : open_addr_map* map, const cmap_pair* key_pair, const cmap_pair* val_pair,
1359 : cmap_pair* slot_out, size_t index, size_t home, bool found_empty) {
1360 1259 : union {
1361 : uint64_t word;
1362 : long double widest;
1363 : } key_copy;
1364 1259 : uint64_t val_copy = 0;
1365 1259 : memset(&key_copy, 0, sizeof(key_copy));
1366 1259 : const size_t key_size = key_pair->size;
1367 1259 : const size_t val_size = val_pair->size;
1368 1259 : memcpy(&key_copy.word, key_pair->ptr, key_size);
1369 1259 : memcpy(&val_copy, val_pair->ptr, val_size);
1370 :
1371 2518 : if (oa_rebuild(map, oa_rehash_capacity_for(map->count + 1), false) ==
1372 : ccol_success) {
1373 2482 : size_t hash_val = hash_key_data(&key_copy, key_size, map->key_type,
1374 1241 : map->custom_hashing_proc, oa_keyed(map),
1375 : g_chmap_hash_secret.int_seed);
1376 1241 : home = hash_index_for(hash_val, map->capacity);
1377 1241 : index = oa_find_insertion_slot(map, hash_val);
1378 1241 : if (index >= map->capacity) {
1379 : return ccol_container_full;
1380 : }
1381 18 : } else if (!found_empty) {
1382 : return ccol_not_enough_memory;
1383 : }
1384 :
1385 1257 : memcpy(&map->slots[index].key_data, &key_copy.word, sizeof(uint64_t));
1386 1257 : memcpy(&map->slots[index].val_data, &val_copy, sizeof(uint64_t));
1387 1257 : map->metadata[index] = SLOT_OCCUPIED;
1388 1257 : map->count++;
1389 1257 : size_t displacement = (index - home) & (map->capacity - 1);
1390 1257 : if (displacement >= OA_DEEP_INSERT) {
1391 126 : index = oa_note_deep_insert(map, index, displacement);
1392 : }
1393 1257 : if (chmap_window_add(chmap_of_oa(map), displacement)) {
1394 0 : index = oa_window_end(map, index);
1395 : }
1396 1257 : if (slot_out) {
1397 18 : oa_fill_val_pair(map, index, slot_out);
1398 : }
1399 : return ccol_success;
1400 : }
1401 :
1402 : // Inserts or updates a pair in an open-addressing map with a linear probe;
1403 : // the body of every open-addressing insert. The first empty slot both proves
1404 : // the key absent and is where it goes. The probe for the key comes before any
1405 : // thought of growth, so an update never rehashes and never invalidates
1406 : // another key's reference. A value that aliases its own slot is copied to a
1407 : // stack buffer first. A new key past the growth load goes to
1408 : // oa_insert_with_growth(); otherwise its displacement feeds the detection,
1409 : // which can move it. A full table at the largest capacity gives
1410 : // ccol_container_full. slot_out NULL overwrites an existing value; non-NULL
1411 : // leaves it and fills *slot_out with the entry's value pair. Callers pass a
1412 : // constant, so each instance keeps one arm.
1413 : static inline __attribute__((always_inline)) ccol_retval
1414 5801896 : oa_insert_impl(open_addr_map* map, const cmap_pair* key_pair,
1415 : const cmap_pair* val_pair, cmap_pair* slot_out) {
1416 11603792 : size_t hash_val = hash_key_data(key_pair->ptr, key_pair->size, map->key_type,
1417 5801896 : map->custom_hashing_proc, oa_keyed(map),
1418 : g_chmap_hash_secret.int_seed);
1419 5801896 : size_t index = hash_index_for(hash_val, map->capacity);
1420 5801897 : size_t start_index = index;
1421 5801897 : bool found_empty = false;
1422 5801897 : const uint64_t probe_key = oa_widen_key(key_pair->ptr, key_pair->size);
1423 :
1424 5801895 : __builtin_prefetch(&map->slots[index], 1, 1);
1425 :
1426 11744180 : do {
1427 11744180 : OA_COUNT_PROBE();
1428 11744180 : __builtin_prefetch(&map->slots[(index + 1) & (map->capacity - 1)], 1, 1);
1429 :
1430 11744179 : if (!(map->metadata[index] & SLOT_OCCUPIED)) {
1431 : found_empty = true;
1432 : break;
1433 : }
1434 :
1435 5956047 : if (oa_keys_equal(&map->slots[index], probe_key)) {
1436 1 : if (slot_out) {
1437 1 : oa_fill_val_pair(map, index, slot_out);
1438 1 : return ccol_key_already_present;
1439 : }
1440 13757 : const void* src = val_pair->ptr;
1441 13757 : uint64_t snapshot;
1442 13757 : if (ranges_overlap(src, val_pair->size, &map->slots[index].val_data,
1443 : map->val_size)) {
1444 1 : memcpy(&snapshot, src, val_pair->size);
1445 1 : src = &snapshot;
1446 : }
1447 13757 : memcpy(&map->slots[index].val_data, src, val_pair->size);
1448 13757 : return ccol_key_already_present;
1449 : }
1450 :
1451 5942289 : index = (index + 1) & (map->capacity - 1);
1452 5942289 : } while (index != start_index);
1453 :
1454 5788136 : if (map->count == ccol_max_elem_count) {
1455 : return ccol_container_full;
1456 : }
1457 :
1458 5788136 : if (oa_above_grow_load(map->count, map->capacity) &&
1459 1259 : map->capacity < ccol__max_power_of_two_size) {
1460 1259 : return oa_insert_with_growth(map, key_pair, val_pair, slot_out, index,
1461 : start_index, found_empty);
1462 : }
1463 :
1464 5786877 : if (found_empty) {
1465 5786877 : memset(&map->slots[index].key_data, 0, sizeof(uint64_t));
1466 5786877 : memset(&map->slots[index].val_data, 0, sizeof(uint64_t));
1467 5786877 : memcpy(&map->slots[index].key_data, key_pair->ptr, key_pair->size);
1468 5786877 : memcpy(&map->slots[index].val_data, val_pair->ptr, val_pair->size);
1469 5786877 : map->metadata[index] = SLOT_OCCUPIED;
1470 5786877 : map->count++;
1471 5786877 : size_t displacement = (index - start_index) & (map->capacity - 1);
1472 5786877 : if (__builtin_expect(displacement >= OA_DEEP_INSERT, 0)) {
1473 16860 : index = oa_note_deep_insert(map, index, displacement);
1474 : }
1475 5786877 : if (__builtin_expect(chmap_window_add(chmap_of_oa(map), displacement), 0)) {
1476 22096 : index = oa_window_end(map, index);
1477 : }
1478 7982 : if (slot_out) {
1479 7982 : oa_fill_val_pair(map, index, slot_out);
1480 : }
1481 : return ccol_success;
1482 : }
1483 :
1484 : return ccol_container_full;
1485 : }
1486 :
1487 : // Inserts or updates a pair in an open-addressing map; the backend of
1488 : // chashmap_insert_elem().
1489 5793895 : static ccol_retval oa_insert(open_addr_map* map, const cmap_pair* key_pair,
1490 : const cmap_pair* val_pair) {
1491 5793895 : return oa_insert_impl(map, key_pair, val_pair, NULL);
1492 : }
1493 :
1494 : // Inserts a key that's absent and fills *slot_out with its value pair either
1495 : // way; the open-addressing backend of ccol_chmap_insert_or_get_elem().
1496 8001 : static ccol_retval oa_insert_or_get(open_addr_map* map,
1497 : const cmap_pair* key_pair,
1498 : const cmap_pair* val_pair,
1499 : cmap_pair* slot_out) {
1500 8001 : return oa_insert_impl(map, key_pair, val_pair, slot_out);
1501 : }
1502 :
1503 : // Looks up a key in an open-addressing map, for every lookup entry point. An
1504 : // empty slot or probe_span slots end the search. A hit fills the caller's pair
1505 : // with the slot's value bytes, valid until the next change of the map; a miss
1506 : // gives {NULL, 0}.
1507 8226503 : static ccol_retval oa_get(open_addr_map* map, const cmap_pair* key_pair,
1508 : cmap_pair* val_pair) {
1509 16453006 : size_t hash_val = hash_key_data(key_pair->ptr, key_pair->size, map->key_type,
1510 8226503 : map->custom_hashing_proc, oa_keyed(map),
1511 : g_chmap_hash_secret.int_seed);
1512 8226503 : size_t index = hash_index_for(hash_val, map->capacity);
1513 8226503 : size_t left = map->probe_span;
1514 8226503 : const uint64_t probe_key = oa_widen_key(key_pair->ptr, key_pair->size);
1515 :
1516 8226501 : __builtin_prefetch(&map->slots[index], 0, 1);
1517 :
1518 61816328 : do {
1519 61816328 : OA_COUNT_PROBE();
1520 61816328 : __builtin_prefetch(&map->slots[(index + 1) & (map->capacity - 1)], 0, 1);
1521 :
1522 61816328 : if (!(map->metadata[index] & SLOT_OCCUPIED)) {
1523 : break;
1524 : }
1525 :
1526 59716488 : if (oa_keys_equal(&map->slots[index], probe_key)) {
1527 6101785 : oa_fill_val_pair(map, index, val_pair);
1528 6101785 : return ccol_success;
1529 : }
1530 :
1531 53614703 : index = (index + 1) & (map->capacity - 1);
1532 53614703 : } while (--left != 0);
1533 :
1534 2124717 : val_pair->ptr = NULL;
1535 2124717 : val_pair->size = 0;
1536 2124717 : return ccol_key_not_found;
1537 : }
1538 :
1539 : // Closes the hole a delete leaves, moving later entries of the cluster back
1540 : // (backward-shift deletion), so the table never holds a tombstone and lookups
1541 : // stop at the first empty slot. An entry at j with home h moves into the hole
1542 : // when h isn't in the cyclic range (hole, j], and its slot becomes the hole;
1543 : // masked distances handle a cluster that wraps. The walk stops at the first
1544 : // empty slot or span slots past the hole, since nothing further can move in.
1545 1029237 : static inline __attribute__((always_inline)) void oa_backward_shift_walk(
1546 : oa_slot* const slots, uint8_t* const metadata, const size_t capacity,
1547 : const size_t key_size, const ccol_data_type key_type,
1548 : const ccol_hashing_proc custom, const bool keyed, const uint64_t int_seed,
1549 : const size_t span, size_t hole) {
1550 1029237 : const size_t mask = capacity - 1;
1551 1029237 : size_t j = hole;
1552 3904656 : for (;;) {
1553 3904656 : j = (j + 1) & mask;
1554 3904656 : if (!(metadata[j] & SLOT_OCCUPIED)) {
1555 : return;
1556 : }
1557 2875555 : const size_t gap = (j - hole) & mask;
1558 2875555 : if (gap >= span) {
1559 : return;
1560 : }
1561 2875419 : OA_COUNT_SHIFT_STEP();
1562 2875419 : size_t home =
1563 2875419 : hash_index_for(hash_key_data(&slots[j].key_data, key_size, key_type,
1564 : custom, keyed, int_seed),
1565 : capacity);
1566 2875419 : if (((j - home) & mask) >= gap) {
1567 609772 : slots[hole] = slots[j];
1568 609772 : metadata[hole] = SLOT_OCCUPIED;
1569 609772 : metadata[j] = 0;
1570 609772 : OA_COUNT_SHIFT_MOVE();
1571 609772 : hole = j;
1572 : }
1573 : }
1574 : }
1575 :
1576 : // Defines the fast and the keyed backward-shift walk of one built-in key
1577 : // type, so oa_backward_shift_close_gap() can tail-call a walk whose hash is
1578 : // fixed at compile time. Each takes only what it reads, so it needs no
1579 : // frame.
1580 : #define OA_DEFINE_SHIFT_WALKS(suffix, type_enum) \
1581 : static __attribute__((noinline)) void oa_shift_walk_fast_##suffix( \
1582 : oa_slot* slots, uint8_t* metadata, size_t capacity, size_t span, \
1583 : size_t hole) { \
1584 : oa_backward_shift_walk(slots, metadata, capacity, 8, type_enum, NULL, \
1585 : false, 0, span, hole); \
1586 : } \
1587 : static __attribute__((noinline)) void oa_shift_walk_keyed_##suffix( \
1588 : oa_slot* slots, uint8_t* metadata, size_t capacity, uint64_t int_seed, \
1589 : size_t span, size_t hole) { \
1590 : oa_backward_shift_walk(slots, metadata, capacity, 8, type_enum, NULL, \
1591 : true, int_seed, span, hole); \
1592 : }
1593 0 : OA_DEFINE_SHIFT_WALKS(char, ccol_char)
1594 0 : OA_DEFINE_SHIFT_WALKS(short, ccol_short)
1595 10151 : OA_DEFINE_SHIFT_WALKS(int, ccol_int)
1596 667349 : OA_DEFINE_SHIFT_WALKS(long, ccol_long)
1597 348698 : OA_DEFINE_SHIFT_WALKS(long_long, ccol_long_long)
1598 1 : OA_DEFINE_SHIFT_WALKS(float, ccol_float)
1599 3038 : OA_DEFINE_SHIFT_WALKS(double, ccol_double)
1600 0 : OA_DEFINE_SHIFT_WALKS(pointer, ccol_pointer)
1601 : #undef OA_DEFINE_SHIFT_WALKS
1602 :
1603 : // Runs the backward-shift walk for a custom hash or a key type that the list
1604 : // doesn't name.
1605 0 : static __attribute__((noinline)) void oa_shift_walk_generic(open_addr_map* map,
1606 : size_t hole) {
1607 0 : oa_backward_shift_walk(map->slots, map->metadata, map->capacity,
1608 : map->key_size, map->key_type, map->custom_hashing_proc,
1609 0 : oa_keyed(map), g_chmap_hash_secret.int_seed,
1610 : map->probe_span, hole);
1611 0 : }
1612 :
1613 : // Closes the gap after a delete by calling the walk for the map's key type and
1614 : // mode; oa_delete() calls it only when the next slot is occupied. The fields
1615 : // go in as arguments, because the walk writes through a byte pointer that
1616 : // could alias the map. Every call is a tail call.
1617 1029237 : static __attribute__((noinline)) void oa_backward_shift_close_gap(
1618 : open_addr_map* map, size_t hole) {
1619 1029237 : oa_slot* const slots = map->slots;
1620 1029237 : uint8_t* const metadata = map->metadata;
1621 1029237 : const size_t cap = map->capacity;
1622 1029237 : const size_t span = map->probe_span;
1623 1029237 : if (map->custom_hashing_proc) {
1624 0 : oa_shift_walk_generic(map, hole);
1625 0 : return;
1626 : }
1627 1029237 : if (oa_keyed(map)) {
1628 16679 : const uint64_t seed = g_chmap_hash_secret.int_seed;
1629 16679 : switch (map->key_type) {
1630 0 : case ccol_char:
1631 : case ccol_signed_char:
1632 : case ccol_unsigned_char:
1633 0 : oa_shift_walk_keyed_char(slots, metadata, cap, seed, span, hole);
1634 0 : return;
1635 0 : case ccol_short:
1636 : case ccol_unsigned_short:
1637 0 : oa_shift_walk_keyed_short(slots, metadata, cap, seed, span, hole);
1638 0 : return;
1639 0 : case ccol_int:
1640 : case ccol_unsigned_int:
1641 0 : oa_shift_walk_keyed_int(slots, metadata, cap, seed, span, hole);
1642 0 : return;
1643 1684 : case ccol_long:
1644 : case ccol_unsigned_long:
1645 1684 : oa_shift_walk_keyed_long(slots, metadata, cap, seed, span, hole);
1646 1684 : return;
1647 11957 : case ccol_long_long:
1648 : case ccol_unsigned_long_long:
1649 11957 : oa_shift_walk_keyed_long_long(slots, metadata, cap, seed, span, hole);
1650 11957 : return;
1651 0 : case ccol_float:
1652 0 : oa_shift_walk_keyed_float(slots, metadata, cap, seed, span, hole);
1653 0 : return;
1654 3038 : case ccol_double:
1655 3038 : oa_shift_walk_keyed_double(slots, metadata, cap, seed, span, hole);
1656 3038 : return;
1657 0 : case ccol_pointer:
1658 0 : oa_shift_walk_keyed_pointer(slots, metadata, cap, seed, span, hole);
1659 0 : return;
1660 0 : default:
1661 0 : oa_shift_walk_generic(map, hole);
1662 0 : return;
1663 : }
1664 : }
1665 1012558 : switch (map->key_type) {
1666 0 : case ccol_char:
1667 : case ccol_signed_char:
1668 : case ccol_unsigned_char:
1669 0 : oa_shift_walk_fast_char(slots, metadata, cap, span, hole);
1670 0 : return;
1671 0 : case ccol_short:
1672 : case ccol_unsigned_short:
1673 0 : oa_shift_walk_fast_short(slots, metadata, cap, span, hole);
1674 0 : return;
1675 10151 : case ccol_int:
1676 : case ccol_unsigned_int:
1677 10151 : oa_shift_walk_fast_int(slots, metadata, cap, span, hole);
1678 10151 : return;
1679 665665 : case ccol_long:
1680 : case ccol_unsigned_long:
1681 665665 : oa_shift_walk_fast_long(slots, metadata, cap, span, hole);
1682 665665 : return;
1683 336741 : case ccol_long_long:
1684 : case ccol_unsigned_long_long:
1685 336741 : oa_shift_walk_fast_long_long(slots, metadata, cap, span, hole);
1686 336741 : return;
1687 1 : case ccol_float:
1688 1 : oa_shift_walk_fast_float(slots, metadata, cap, span, hole);
1689 1 : return;
1690 0 : case ccol_double:
1691 0 : oa_shift_walk_fast_double(slots, metadata, cap, span, hole);
1692 0 : return;
1693 0 : case ccol_pointer:
1694 0 : oa_shift_walk_fast_pointer(slots, metadata, cap, span, hole);
1695 0 : return;
1696 0 : default:
1697 0 : oa_shift_walk_generic(map, hole);
1698 0 : return;
1699 : }
1700 : }
1701 :
1702 : // Deletes a key from an open-addressing map with backward-shift deletion,
1703 : // searching at most probe_span slots. Later entries can move, so every
1704 : // reference into the map becomes invalid. The table halves when the count
1705 : // falls below a quarter.
1706 2961079 : static ccol_retval oa_delete(open_addr_map* map, const cmap_pair* key_pair) {
1707 5922158 : size_t hash_val = hash_key_data(key_pair->ptr, key_pair->size, map->key_type,
1708 2961079 : map->custom_hashing_proc, oa_keyed(map),
1709 : g_chmap_hash_secret.int_seed);
1710 2961079 : size_t index = hash_index_for(hash_val, map->capacity);
1711 2961079 : size_t left = map->probe_span;
1712 2961079 : const uint64_t probe_key = oa_widen_key(key_pair->ptr, key_pair->size);
1713 :
1714 3430440 : do {
1715 3430440 : OA_COUNT_PROBE();
1716 3430440 : if (!(map->metadata[index] & SLOT_OCCUPIED)) {
1717 : return ccol_key_not_found;
1718 : }
1719 :
1720 3417413 : if (oa_keys_equal(&map->slots[index], probe_key)) {
1721 2945902 : map->metadata[index] = 0;
1722 2945902 : if (map->metadata[(index + 1) & (map->capacity - 1)] & SLOT_OCCUPIED) {
1723 1029237 : oa_backward_shift_close_gap(map, index);
1724 : }
1725 2945902 : map->count--;
1726 :
1727 2945902 : if (map->count < (map->capacity >> 2) &&
1728 : map->capacity > minimum_allowed_bucket_array_size) {
1729 681 : oa_rebuild(map, map->capacity / 2, oa_keyed(map));
1730 : }
1731 :
1732 2945902 : return ccol_success;
1733 : }
1734 :
1735 471511 : index = (index + 1) & (map->capacity - 1);
1736 471511 : } while (--left != 0);
1737 :
1738 : return ccol_key_not_found;
1739 : }
1740 :
1741 : // Frees the slot table at teardown; the state itself lives in the map's block.
1742 41622 : static void oa_destroy(open_addr_map* map) {
1743 41622 : ccol__mem_free(map->m_procs, map->slots);
1744 41622 : }
1745 :
1746 : // Empties every slot without allocating, for a reset whose new table can't be
1747 : // allocated. Keys and values live in the slots, so this destroys every
1748 : // element.
1749 6 : static void oa_clear_in_place(open_addr_map* map) {
1750 6 : memset(map->slots, 0, map->capacity * OA_BLOCK_BYTES_PER_SLOT);
1751 6 : map->count = 0;
1752 6 : map->probe_span = oa_min_probe_span(map->capacity);
1753 6 : oa_window_restart(map);
1754 6 : }
1755 :
1756 : // Clears every entry of an open-addressing map, for chashmap_reset(), and
1757 : // replaces the table when new_capacity differs from the current one. When
1758 : // that allocation fails it clears in place, so every element is gone whatever
1759 : // it returns. The mode stays, the window restarts.
1760 7 : static ccol_retval oa_reset(open_addr_map* map, size_t new_capacity) {
1761 7 : if (new_capacity == 0 || new_capacity == map->capacity) {
1762 5 : oa_clear_in_place(map);
1763 5 : return ccol_success;
1764 : }
1765 :
1766 2 : uint8_t* new_metadata = NULL;
1767 2 : oa_slot* new_slots =
1768 2 : oa_alloc_block(map->m_procs, new_capacity, &new_metadata);
1769 2 : if (!new_slots) {
1770 1 : oa_clear_in_place(map);
1771 1 : return ccol_not_enough_memory;
1772 : }
1773 :
1774 1 : ccol__mem_free(map->m_procs, map->slots);
1775 1 : map->slots = new_slots;
1776 1 : map->metadata = new_metadata;
1777 :
1778 1 : map->capacity = new_capacity;
1779 1 : map->count = 0;
1780 1 : map->probe_span = oa_min_probe_span(new_capacity);
1781 1 : oa_window_restart(map);
1782 :
1783 1 : return ccol_success;
1784 : }
1785 :
1786 : // Gives the llist_node that holds the dllist_refs member tracker points at,
1787 : // so a walk of the insertion-order list can reach its entries.
1788 : #define dllistRefNodePtr2LlistNodePtr(tracker) \
1789 : (llist_node*)((uint8_t*)tracker - offsetof(llist_node, dllist_refs))
1790 :
1791 : // Puts node at the head (newest end) of the insertion-order list, when an
1792 : // insert makes it.
1793 4140569 : static void attach_node_to_dllist(dllist_root* root, dllist_ref_node* node) {
1794 4140569 : node->prev = NULL;
1795 4140569 : if (!root->head) {
1796 1688742 : node->next = NULL;
1797 1688742 : root->head = node;
1798 1688742 : root->tail = node;
1799 : } else {
1800 2451827 : node->next = root->head;
1801 2451827 : root->head->prev = node;
1802 2451827 : root->head = node;
1803 : }
1804 : }
1805 :
1806 : // Takes node off the insertion-order list without freeing it, when its entry
1807 : // is deleted.
1808 4140541 : static void detach_node_from_dllist(dllist_root* root, dllist_ref_node* node) {
1809 4140541 : if (node->next) {
1810 1131453 : node->next->prev = node->prev;
1811 : } else {
1812 3009088 : root->tail = node->prev;
1813 : }
1814 4140541 : if (node->prev) {
1815 2421568 : node->prev->next = node->next;
1816 : } else {
1817 1718973 : root->head = node->next;
1818 : }
1819 : }
1820 :
1821 : // Frees a chaining node: Its heap key and value buffers (heap exactly when the
1822 : // accessor size passes INLINE_STORAGE_THRESHOLD), its place on all_elems, and
1823 : // the node. A NULL all_elems skips the list; only the failure paths of
1824 : // sc_create_llist_node() pass it.
1825 4140555 : static void sc_destroy_llist_node(dllist_root* all_elems, llist_node* elem,
1826 : ccol_memmgmt_procs* m_procs) {
1827 4140555 : if (elem) {
1828 4140555 : if (elem->key_pair_accessor.size > INLINE_STORAGE_THRESHOLD &&
1829 279608 : elem->key_storage.ptr) {
1830 279608 : ccol__mem_free(m_procs, elem->key_storage.ptr);
1831 : }
1832 4140555 : if (elem->val_pair_accessor.size > INLINE_STORAGE_THRESHOLD &&
1833 2254 : elem->val_storage.ptr) {
1834 2254 : ccol__mem_free(m_procs, elem->val_storage.ptr);
1835 : }
1836 4140555 : if (all_elems) {
1837 4140541 : detach_node_from_dllist(all_elems, &elem->dllist_refs);
1838 : }
1839 4140555 : ccol__mem_free(m_procs, elem);
1840 : }
1841 4140555 : }
1842 :
1843 : // Makes a chaining node holding copies of the key and value, inline or on the
1844 : // heap, for an insert of a new key, and puts it at the head of the
1845 : // insertion-order list. Each accessor is set only once its storage holds the
1846 : // bytes, so a failure frees only what exists. Forced inline: As a call it
1847 : // costs each new key about 57 instructions.
1848 4140869 : static inline __attribute__((always_inline)) llist_node* sc_create_llist_node(
1849 : dllist_root* all_elems, ccol_memmgmt_procs* m_procs, size_t hash_val,
1850 : const void* key_ptr, size_t key_size, const void* val_ptr,
1851 : size_t val_size) {
1852 8281739 : llist_node* new_elem =
1853 4140869 : (llist_node*)ccol__mem_calloc(m_procs, 1, sizeof(llist_node));
1854 4140870 : if (!new_elem) return NULL;
1855 :
1856 4140583 : new_elem->hash_val = hash_val;
1857 :
1858 4140583 : if (key_size <= INLINE_STORAGE_THRESHOLD) {
1859 3860974 : memcpy(&new_elem->key_storage.inline_data, key_ptr, key_size);
1860 3860974 : new_elem->key_pair_accessor.ptr = &new_elem->key_storage.inline_data;
1861 : } else {
1862 279609 : new_elem->key_storage.ptr = ccol__mem_alloc(m_procs, key_size);
1863 279609 : if (!new_elem->key_storage.ptr) {
1864 1 : sc_destroy_llist_node(NULL, new_elem, m_procs);
1865 1 : return NULL;
1866 : }
1867 279608 : memcpy(new_elem->key_storage.ptr, key_ptr, key_size);
1868 279608 : new_elem->key_pair_accessor.ptr = new_elem->key_storage.ptr;
1869 : }
1870 4140582 : new_elem->key_pair_accessor.size = key_size;
1871 :
1872 4140582 : if (val_size <= INLINE_STORAGE_THRESHOLD) {
1873 4138314 : memcpy(&new_elem->val_storage.inline_data, val_ptr, val_size);
1874 4138314 : new_elem->val_pair_accessor.ptr = &new_elem->val_storage.inline_data;
1875 : } else {
1876 2268 : new_elem->val_storage.ptr = ccol__mem_alloc(m_procs, val_size);
1877 2268 : if (!new_elem->val_storage.ptr) {
1878 13 : sc_destroy_llist_node(NULL, new_elem, m_procs);
1879 13 : return NULL;
1880 : }
1881 2255 : memcpy(new_elem->val_storage.ptr, val_ptr, val_size);
1882 2255 : new_elem->val_pair_accessor.ptr = new_elem->val_storage.ptr;
1883 : }
1884 4140569 : new_elem->val_pair_accessor.size = val_size;
1885 :
1886 4140569 : attach_node_to_dllist(all_elems, &new_elem->dllist_refs);
1887 4140569 : new_elem->next = NULL;
1888 4140569 : return new_elem;
1889 : }
1890 :
1891 : // Compares two long double keys by value, matching hash_long_double_value():
1892 : // two NaNs are equal (no padding byte is read), otherwise ==, so -0.0L equals
1893 : // 0.0L.
1894 24 : static inline bool long_double_keys_equal(const void* a_ptr,
1895 : const void* b_ptr) {
1896 24 : long double a, b;
1897 24 : memcpy(&a, a_ptr, sizeof(a));
1898 24 : memcpy(&b, b_ptr, sizeof(b));
1899 :
1900 24 : bool a_nan = isnan(a);
1901 24 : bool b_nan = isnan(b);
1902 24 : if (a_nan || b_nan) {
1903 5 : return a_nan && b_nan;
1904 : }
1905 :
1906 19 : return a == b;
1907 : }
1908 :
1909 : // Compares a node's key with key_ptr, for every chain search: Sizes first,
1910 : // integer compares for 4 and 8 bytes, memcmp otherwise. A long double goes to
1911 : // long_double_keys_equal() before the size dispatch, because it can be 8
1912 : // bytes wide.
1913 3343769 : static inline bool sc_compare_keys(const llist_node* node, const void* key_ptr,
1914 : size_t key_size, ccol_data_type key_type) {
1915 3343769 : if (node->key_pair_accessor.size != key_size) return false;
1916 :
1917 3343769 : const void* node_key_ptr = node->key_pair_accessor.ptr;
1918 :
1919 3343769 : if (key_type == ccol_long_double) {
1920 48 : return long_double_keys_equal(node_key_ptr, key_ptr);
1921 : }
1922 :
1923 3343745 : if (key_size == sizeof(unsigned int)) {
1924 61933 : unsigned int a, b;
1925 61933 : memcpy(&a, node_key_ptr, sizeof(a));
1926 61933 : memcpy(&b, key_ptr, sizeof(b));
1927 61933 : return a == b;
1928 3281812 : } else if (key_size == sizeof(unsigned long)) {
1929 1626058 : unsigned long a, b;
1930 1626058 : memcpy(&a, node_key_ptr, sizeof(a));
1931 1626058 : memcpy(&b, key_ptr, sizeof(b));
1932 1626058 : return a == b;
1933 : } else {
1934 1655754 : return memcmp(node_key_ptr, key_ptr, key_size) == 0;
1935 : }
1936 : }
1937 :
1938 : // Searches a chain of a map with a custom key equality. It's out of line so
1939 : // the ordinary loop of sc_find_in_llist() stays as it is. The stored hash
1940 : // still rejects most nodes.
1941 19114 : static __attribute__((noinline)) llist_node* sc_find_in_llist_custom_eq(
1942 : llist_node* head, size_t hash_val, const void* key_ptr, size_t key_size,
1943 : ccol_key_equality_proc custom_eq) {
1944 28267 : for (llist_node* tracker = head; tracker; tracker = tracker->next) {
1945 21161 : SC_COUNT_NODE_VISIT();
1946 33169 : if (tracker->hash_val == hash_val &&
1947 12008 : custom_eq(tracker->key_pair_accessor.ptr,
1948 : tracker->key_pair_accessor.size, key_ptr, key_size)) {
1949 12008 : return tracker;
1950 : }
1951 : }
1952 : return NULL;
1953 : }
1954 :
1955 : // Counts the nodes of a chain, for the detection of an insert into a map with
1956 : // a custom equality.
1957 : static __attribute__((noinline)) size_t
1958 7102 : sc_chain_length(const llist_node* head) {
1959 7102 : size_t length = 0;
1960 12789 : for (; head; head = head->next) length++;
1961 7102 : return length;
1962 : }
1963 :
1964 : // Searches a chain for key_ptr and gives its node or NULL, for every chaining
1965 : // lookup and insert. It compares the full stored hash before the key. When
1966 : // walk isn't NULL and nothing matches, it gets the chain length for the
1967 : // detection. Callers pass walk as a constant.
1968 6351899 : static inline __attribute__((always_inline)) llist_node* sc_find_in_llist(
1969 : llist_node* head, size_t hash_val, const void* key_ptr, size_t key_size,
1970 : ccol_data_type key_type, ccol_key_equality_proc custom_eq, size_t* walk) {
1971 6351899 : if (custom_eq) {
1972 7104 : llist_node* found = sc_find_in_llist_custom_eq(head, hash_val, key_ptr,
1973 : key_size, custom_eq);
1974 7104 : if (!found && walk) *walk = sc_chain_length(head);
1975 12010 : return found;
1976 : }
1977 : size_t met = 0;
1978 : llist_node* tracker = head;
1979 9187509 : while (tracker) {
1980 4875139 : SC_COUNT_NODE_VISIT();
1981 6898841 : if (tracker->hash_val == hash_val &&
1982 2023700 : sc_compare_keys(tracker, key_ptr, key_size, key_type)) {
1983 : return tracker;
1984 : }
1985 2854724 : if (walk) met++;
1986 2854724 : tracker = tracker->next;
1987 : }
1988 : if (walk) *walk = met;
1989 : return NULL;
1990 : }
1991 :
1992 : // Replaces a node's value, for an update of a present key: In place for the
1993 : // same size, inline for a small value, a realloc or a new buffer for a bigger
1994 : // one. Gives false when memory runs out. val_ptr may alias the stored value
1995 : // (a chmap_get_ptr() result handed back), and every branch changes the
1996 : // storage before reading val_ptr, so an aliasing value is copied first.
1997 654 : static bool sc_reset_val_of_llist_node(llist_node* elem, const void* val_ptr,
1998 : size_t val_size,
1999 : ccol_memmgmt_procs* m_procs) {
2000 654 : void* old_ptr = elem->val_pair_accessor.ptr;
2001 654 : size_t old_size = elem->val_pair_accessor.size;
2002 654 : bool old_inline = old_size <= INLINE_STORAGE_THRESHOLD;
2003 :
2004 654 : unsigned char snapshot_buf[INLINE_STORAGE_THRESHOLD + 1];
2005 654 : void* heap_snapshot = NULL;
2006 654 : if (ranges_overlap(val_ptr, val_size, old_ptr, old_size)) {
2007 5 : if (val_size <= sizeof(snapshot_buf)) {
2008 3 : memcpy(snapshot_buf, val_ptr, val_size);
2009 3 : val_ptr = snapshot_buf;
2010 : } else {
2011 2 : heap_snapshot = ccol__mem_alloc(m_procs, val_size);
2012 2 : if (!heap_snapshot) return false;
2013 2 : memcpy(heap_snapshot, val_ptr, val_size);
2014 2 : val_ptr = heap_snapshot;
2015 : }
2016 : }
2017 :
2018 654 : bool ok = true;
2019 654 : if (val_size == old_size) {
2020 560 : memcpy(old_ptr, val_ptr, val_size);
2021 94 : } else if (val_size <= INLINE_STORAGE_THRESHOLD) {
2022 70 : if (!old_inline) {
2023 5 : ccol__mem_free(m_procs, elem->val_storage.ptr);
2024 : }
2025 70 : memcpy(&elem->val_storage.inline_data, val_ptr, val_size);
2026 70 : elem->val_pair_accessor.ptr = &elem->val_storage.inline_data;
2027 70 : elem->val_pair_accessor.size = val_size;
2028 : } else {
2029 24 : if (old_inline) {
2030 5 : void* new_ptr = ccol__mem_alloc(m_procs, val_size);
2031 5 : if (!new_ptr) {
2032 : ok = false;
2033 : } else {
2034 4 : elem->val_storage.ptr = new_ptr;
2035 : }
2036 : } else {
2037 19 : void* orig = elem->val_storage.ptr;
2038 38 : elem->val_storage.ptr =
2039 19 : ccol__mem_realloc(m_procs, elem->val_storage.ptr, val_size);
2040 19 : if (!elem->val_storage.ptr) {
2041 2 : elem->val_storage.ptr = orig;
2042 2 : ok = false;
2043 : }
2044 : }
2045 :
2046 6 : if (ok) {
2047 21 : memcpy(elem->val_storage.ptr, val_ptr, val_size);
2048 21 : elem->val_pair_accessor.ptr = elem->val_storage.ptr;
2049 21 : elem->val_pair_accessor.size = val_size;
2050 : }
2051 : }
2052 :
2053 654 : if (heap_snapshot) {
2054 2 : ccol__mem_free(m_procs, heap_snapshot);
2055 : }
2056 : return ok;
2057 : }
2058 :
2059 : // Unlinks node from its chain (previous is the node before it, or NULL),
2060 : // destroys it and gives the chain's new head; both delete searches end here.
2061 2 : static llist_node* sc_unlink_and_destroy(llist_node* head, llist_node* previous,
2062 : llist_node* node,
2063 : dllist_root* all_elems,
2064 : ccol_memmgmt_procs* m_procs) {
2065 2 : if (!previous) {
2066 2 : head = node->next;
2067 : } else {
2068 0 : previous->next = node->next;
2069 : }
2070 2 : sc_destroy_llist_node(all_elems, node, m_procs);
2071 2 : return head;
2072 : }
2073 :
2074 : // Removes the node of key_ptr from a chain of a map with a custom key
2075 : // equality, out of line like the find. Gives the new head and sets *found.
2076 2 : static __attribute__((noinline)) llist_node* sc_delete_from_llist_custom_eq(
2077 : llist_node* head, dllist_root* all_elems, ccol_memmgmt_procs* m_procs,
2078 : size_t hash_val, const void* key_ptr, size_t key_size,
2079 : ccol_key_equality_proc custom_eq, bool* found) {
2080 2 : llist_node* previous = NULL;
2081 2 : for (llist_node* tracker = head; tracker; tracker = tracker->next) {
2082 2 : SC_COUNT_NODE_VISIT();
2083 4 : if (tracker->hash_val == hash_val &&
2084 2 : custom_eq(tracker->key_pair_accessor.ptr,
2085 : tracker->key_pair_accessor.size, key_ptr, key_size)) {
2086 2 : *found = true;
2087 4 : return sc_unlink_and_destroy(head, previous, tracker, all_elems, m_procs);
2088 : }
2089 0 : previous = tracker;
2090 : }
2091 : return head;
2092 : }
2093 :
2094 : // Removes the node of key_ptr from a chain and gives the chain's new head, for
2095 : // sc_delete(). *found says whether there was one. The stored hash rejects most
2096 : // nodes with one compare.
2097 1320470 : static llist_node* sc_delete_from_llist(
2098 : llist_node* head, dllist_root* all_elems, ccol_memmgmt_procs* m_procs,
2099 : size_t hash_val, const void* key_ptr, size_t key_size,
2100 : ccol_data_type key_type, ccol_key_equality_proc custom_eq, bool* found) {
2101 1320470 : *found = false;
2102 1320470 : if (custom_eq) {
2103 2 : return sc_delete_from_llist_custom_eq(head, all_elems, m_procs, hash_val,
2104 : key_ptr, key_size, custom_eq, found);
2105 : }
2106 : llist_node* tracker = head;
2107 : llist_node* previous = NULL;
2108 :
2109 2194649 : while (tracker) {
2110 2194249 : SC_COUNT_NODE_VISIT();
2111 3514318 : if (tracker->hash_val == hash_val &&
2112 1320069 : sc_compare_keys(tracker, key_ptr, key_size, key_type)) {
2113 1320068 : *found = true;
2114 1320068 : if (!previous) {
2115 752872 : head = tracker->next;
2116 : } else {
2117 567196 : previous->next = tracker->next;
2118 : }
2119 1320068 : sc_destroy_llist_node(all_elems, tracker, m_procs);
2120 1320068 : return head;
2121 : }
2122 874181 : previous = tracker;
2123 874181 : tracker = tracker->next;
2124 : }
2125 : return head;
2126 : }
2127 :
2128 : // Destroys every node of a chain and gives NULL; reset and destroy clear each
2129 : // bucket with it.
2130 9134617 : static llist_node* sc_destroy_the_whole_llist(llist_node* head,
2131 : dllist_root* all_elems,
2132 : ccol_memmgmt_procs* m_procs) {
2133 9134617 : llist_node* tracker = head;
2134 11955088 : while (tracker) {
2135 2820471 : llist_node* node_to_be_deleted = tracker;
2136 2820471 : tracker = tracker->next;
2137 2820471 : sc_destroy_llist_node(all_elems, node_to_be_deleted, m_procs);
2138 : }
2139 9134617 : return NULL;
2140 : }
2141 :
2142 : // Sets the growth and shrink thresholds of a chaining map from its bucket
2143 : // count, exactly (n + 1) * 3 / 2 and (n + 1) / 8, written so neither
2144 : // overflows. Every resize calls it.
2145 1745555 : static void sc_set_scaling_limits(sep_chain_map* map) {
2146 1745555 : size_t base_up = map->bucket_arr_size + map->bucket_arr_size / 2;
2147 3464083 : map->elem_count_to_scale_up =
2148 3491110 : base_up + ((map->bucket_arr_size % 2 == 0) ? 1 : 2);
2149 1745555 : map->elem_count_to_scale_down = (map->bucket_arr_size + 1) / 8;
2150 : }
2151 :
2152 : // Gives the bucket array inside the map's block and its length, or NULL and
2153 : // 0, so creation, shrink and reset can use it instead of an allocation. The
2154 : // map never frees it. Comparing addresses instead would mistake a separate
2155 : // array that a headerless allocator puts right after the block for this one.
2156 3436939 : static inline llist_node** sc_inline_bucket_arr(sep_chain_map* map,
2157 : size_t* count) {
2158 3436939 : *count = map->inline_buckets;
2159 3436902 : return *count ? (llist_node**)(chmap_of_sc(map) + 1) : NULL;
2160 : }
2161 :
2162 : // Gives the bound on the nodes a window's 256 inserts meet, above which a fast
2163 : // chaining map switches: 256 * (4.5 * lambda + 0.5), lambda being entries per
2164 : // bucket at the highest load the window can reach (see oa_window_bound()). In
2165 : // integers, within 1 percent.
2166 1753524 : static uint16_t sc_window_bound(size_t start_count, size_t scale_up,
2167 : size_t bucket_count) {
2168 3507048 : size_t judged =
2169 1753489 : start_count < scale_up && scale_up - start_count > CHMAP_WINDOW_INSERTS
2170 : ? start_count + CHMAP_WINDOW_INSERTS
2171 28672 : : scale_up;
2172 1753524 : uint64_t lambda = chmap_load_q16(judged, bucket_count);
2173 1753524 : uint64_t bound = ((1152u * lambda) >> 16) + 128u;
2174 1753524 : return bound > UINT16_MAX ? UINT16_MAX : (uint16_t)bound;
2175 : }
2176 :
2177 : // Starts a new insert window of a chaining map and computes its bound; a
2178 : // keyed map skips the arithmetic.
2179 1727820 : static inline void sc_window_restart(sep_chain_map* map) {
2180 1727820 : struct chashmap* chm = chmap_of_sc(map);
2181 1727820 : chm->insert_window = CHMAP_WINDOW_START;
2182 3455640 : chm->window_bound =
2183 1727820 : chm->hash_mode == CHMAP_HASH_KEYED
2184 : ? UINT16_MAX
2185 3452994 : : sc_window_bound(map->elem_count, map->elem_count_to_scale_up,
2186 : map->bucket_arr_size);
2187 1727820 : }
2188 :
2189 : // Computes the hash a node stores for its key, in the mode keyed names.
2190 220130 : static inline size_t sc_hash_of_node(const sep_chain_map* map,
2191 : const llist_node* node, bool keyed) {
2192 440260 : return hash_key_data(
2193 220130 : node->key_pair_accessor.ptr, node->key_pair_accessor.size, map->key_type,
2194 220130 : map->custom_hashing_proc, keyed, g_chmap_hash_secret.int_seed);
2195 : }
2196 :
2197 : // Switches a fast chaining map to keyed when its keys collide: Every node gets
2198 : // its keyed hash and is linked into the same array again. Nothing moves or
2199 : // allocates, so it can't fail and every reference, the order and every
2200 : // iterator stay valid.
2201 154 : static __attribute__((noinline)) void sc_switch_to_keyed(sep_chain_map* map) {
2202 154 : chmap_of_sc(map)->hash_mode = CHMAP_HASH_KEYED;
2203 154 : llist_node** const buckets = map->bucket_arr;
2204 154 : const size_t bucket_count = map->bucket_arr_size;
2205 154 : memset(buckets, 0, bucket_count * sizeof(llist_node*));
2206 61159 : for (dllist_ref_node* t = map->all_elems.tail; t; t = t->prev) {
2207 61005 : llist_node* node = dllistRefNodePtr2LlistNodePtr(t);
2208 61005 : node->hash_val = sc_hash_of_node(map, node, true);
2209 61005 : size_t index = hash_index_for(node->hash_val, bucket_count);
2210 61005 : node->next = buckets[index];
2211 61005 : buckets[index] = node;
2212 : }
2213 154 : sc_window_restart(map);
2214 154 : }
2215 :
2216 : // Switches a fast map whose new key met SC_CHAIN_CAP nodes; a cold path of
2217 : // the insert, kept out of line so the insert stays short.
2218 13 : static __attribute__((noinline)) void sc_note_long_chain(sep_chain_map* map) {
2219 13 : if (!sc_keyed(map)) {
2220 13 : sc_switch_to_keyed(map);
2221 : }
2222 13 : }
2223 :
2224 : // Judges a window that just ended and switches a fast map whose sum passes its
2225 : // bound; a cold path of the insert.
2226 9138 : static __attribute__((noinline)) void sc_window_end(sep_chain_map* map) {
2227 9138 : struct chashmap* chm = chmap_of_sc(map);
2228 9138 : bool switch_now = chm->hash_mode == CHMAP_HASH_FAST &&
2229 8024 : chm->insert_window > chm->window_bound;
2230 9138 : sc_window_restart(map);
2231 9138 : if (switch_now) {
2232 10 : sc_switch_to_keyed(map);
2233 : }
2234 9138 : }
2235 :
2236 : // The slack in a fast attempt's walk budget.
2237 : #define SC_ATTEMPT_SLACK 64u
2238 :
2239 : // Relinks every node into new_arr with the fast hash when a keyed chaining map
2240 : // grows, so a map whose keys spread again goes back to the cheap hash. It
2241 : // stores the fast hash in each node, walks each chain first, and stops when a
2242 : // chain would reach SC_CHAIN_CAP or the walks pass elem_count +
2243 : // SC_ATTEMPT_SLACK. On failure it relinks everything keyed into the same
2244 : // array (only the nodes it reached need the keyed hash again) and gives false.
2245 : // Nothing moves or allocates, and the work stays linear in the count.
2246 183 : static __attribute__((noinline)) bool sc_relink_fast_attempt(
2247 : sep_chain_map* map, llist_node** new_arr, size_t new_size) {
2248 183 : const size_t budget = map->elem_count + SC_ATTEMPT_SLACK;
2249 183 : size_t walked = 0, work = 0;
2250 183 : dllist_ref_node* stop = NULL;
2251 147297 : for (dllist_ref_node* t = map->all_elems.tail; t; t = t->prev) {
2252 147165 : llist_node* node = dllistRefNodePtr2LlistNodePtr(t);
2253 147165 : node->hash_val = sc_hash_of_node(map, node, false);
2254 147165 : size_t index = hash_index_for(node->hash_val, new_size);
2255 147165 : size_t chain = 0;
2256 213756 : for (const llist_node* c = new_arr[index]; c; c = c->next) {
2257 66620 : if (++chain == SC_CHAIN_CAP - 1) break;
2258 : }
2259 147165 : CHMAP_RETRY_WORK(work, 1 + chain);
2260 147165 : walked += chain;
2261 147165 : if (chain == SC_CHAIN_CAP - 1 || walked > budget) {
2262 : stop = t;
2263 : break;
2264 : }
2265 147114 : node->next = new_arr[index];
2266 147114 : new_arr[index] = node;
2267 : }
2268 183 : CHMAP_NOTE_RETRY(stop != NULL, work, map->elem_count, new_size);
2269 183 : (void)work;
2270 183 : if (!stop) return true;
2271 :
2272 51 : memset(new_arr, 0, new_size * sizeof(llist_node*));
2273 51 : bool holds_fast = true;
2274 136326 : for (dllist_ref_node* t = map->all_elems.tail; t; t = t->prev) {
2275 136275 : llist_node* node = dllistRefNodePtr2LlistNodePtr(t);
2276 136275 : if (holds_fast) node->hash_val = sc_hash_of_node(map, node, true);
2277 136275 : if (t == stop) holds_fast = false;
2278 136275 : size_t index = hash_index_for(node->hash_val, new_size);
2279 136275 : node->next = new_arr[index];
2280 136275 : new_arr[index] = node;
2281 : }
2282 : return false;
2283 : }
2284 :
2285 : // Grows or shrinks the bucket array of a chaining map by scale_factor when
2286 : // the count crosses a threshold, and relinks every node by its stored hash;
2287 : // the window restarts. A shrink is clamped to the minimum, takes the in-block
2288 : // array back when its length fits, and measures the merged chains: One of
2289 : // SC_CHAIN_CAP nodes switches a fast map. Growing a keyed map makes the fast
2290 : // attempt. On a failed allocation nothing changes.
2291 4052 : static void sc_scale(sep_chain_map* map, bool up) {
2292 4052 : if (up &&
2293 4022 : (map->bucket_arr_size > ccol__max_power_of_two_size / scale_factor)) {
2294 4052 : return;
2295 : }
2296 :
2297 8074 : size_t new_size = up ? map->bucket_arr_size * scale_factor
2298 4052 : : map->bucket_arr_size / scale_factor;
2299 :
2300 4052 : if (!up && new_size < minimum_allowed_bucket_array_size) {
2301 1 : new_size = minimum_allowed_bucket_array_size;
2302 : }
2303 :
2304 4052 : size_t inline_count = 0;
2305 4052 : llist_node** new_arr = sc_inline_bucket_arr(map, &inline_count);
2306 4052 : if (new_size == inline_count) {
2307 11 : memset(new_arr, 0, new_size * sizeof(llist_node*));
2308 : } else {
2309 4041 : new_arr = (llist_node**)ccol__mem_calloc(map->m_procs, new_size,
2310 : sizeof(llist_node*));
2311 4041 : if (!new_arr) return;
2312 : }
2313 :
2314 4049 : const size_t ratio_mask = up ? 0 : map->bucket_arr_size / new_size - 1;
2315 4049 : size_t merged = 0;
2316 4049 : size_t longest_merged = 0;
2317 4049 : if (up && sc_keyed(map)) {
2318 183 : if (sc_relink_fast_attempt(map, new_arr, new_size)) {
2319 132 : chmap_of_sc(map)->hash_mode = CHMAP_HASH_FAST;
2320 : }
2321 : } else {
2322 2239334 : for (size_t i = 0; i < map->bucket_arr_size; i++) {
2323 2235468 : if ((i & ratio_mask) == 0) merged = 0;
2324 2235468 : llist_node* tracker = map->bucket_arr[i];
2325 3655127 : while (tracker) {
2326 1419659 : llist_node* next = tracker->next;
2327 1419659 : size_t new_index = hash_index_for(tracker->hash_val, new_size);
2328 1419659 : tracker->next = new_arr[new_index];
2329 1419659 : new_arr[new_index] = tracker;
2330 1419659 : tracker = next;
2331 1419659 : merged++;
2332 : }
2333 2235468 : if (merged > longest_merged) longest_merged = merged;
2334 : }
2335 : }
2336 :
2337 8089 : if (map->bucket_arr != sc_inline_bucket_arr(map, &inline_count)) {
2338 1267 : ccol__mem_free(map->m_procs, map->bucket_arr);
2339 : }
2340 4049 : map->bucket_arr = new_arr;
2341 4049 : map->bucket_arr_size = new_size;
2342 4049 : sc_set_scaling_limits(map);
2343 4049 : sc_window_restart(map);
2344 4049 : if (!up && longest_merged >= SC_CHAIN_CAP && !sc_keyed(map)) {
2345 1 : sc_switch_to_keyed(map);
2346 : }
2347 : }
2348 :
2349 : // Sets up the chaining state in the map's block at creation; the first bucket
2350 : // array is the zeroed in-block one when the block has it, else a calloc.
2351 : // Gives false with nothing allocated on failure.
2352 1714464 : static bool sc_init(sep_chain_map* map, size_t bucket_arr_size,
2353 : ccol_data_type key_type, ccol_data_type val_type,
2354 : ccol_memmgmt_procs* m_procs,
2355 : ccol_hashing_proc custom_hashing_proc,
2356 : ccol_key_equality_proc custom_key_equality_proc) {
2357 1714464 : size_t inline_count = 0;
2358 1714464 : llist_node** inline_arr = sc_inline_bucket_arr(map, &inline_count);
2359 1714464 : if (bucket_arr_size == inline_count) {
2360 1714455 : map->bucket_arr = inline_arr;
2361 : } else {
2362 9 : map->bucket_arr = (llist_node**)ccol__mem_calloc(m_procs, bucket_arr_size,
2363 : sizeof(llist_node*));
2364 10 : if (!map->bucket_arr) return false;
2365 : }
2366 :
2367 1714465 : map->bucket_arr_size = bucket_arr_size;
2368 1714465 : map->elem_count = 0;
2369 1714465 : map->key_type = key_type;
2370 1714465 : map->val_type = val_type;
2371 1714465 : map->all_elems.head = NULL;
2372 1714465 : map->all_elems.tail = NULL;
2373 1714465 : map->m_procs = m_procs;
2374 1714465 : map->custom_hashing_proc = custom_hashing_proc;
2375 1714465 : map->custom_key_equality_proc = custom_key_equality_proc;
2376 1714465 : sc_set_scaling_limits(map);
2377 1714465 : sc_window_restart(map);
2378 1714465 : return true;
2379 : }
2380 :
2381 : // Inserts or updates a pair in a chaining map; the body of every chaining
2382 : // insert. The lookup comes before the ccol_max_elem_count check, so a full map
2383 : // still accepts an update. A new node goes to the front of its chain, its
2384 : // chain length feeds the detection (a switch rehashes in place), and the
2385 : // array grows at elem_count_to_scale_up; neither moves the node. slot_out
2386 : // means what it means for oa_insert_impl(), and key_slot_out gets the key
2387 : // accessor where slot_out gets the value.
2388 4157164 : static inline __attribute__((always_inline)) ccol_retval sc_insert_impl(
2389 : sep_chain_map* map, const cmap_pair* key_pair, const cmap_pair* val_pair,
2390 : const cmap_pair** slot_out, const cmap_pair** key_slot_out) {
2391 8314328 : const size_t hash_val = hash_key_data(
2392 4157164 : key_pair->ptr, key_pair->size, map->key_type, map->custom_hashing_proc,
2393 4157164 : sc_keyed(map), g_chmap_hash_secret.int_seed);
2394 :
2395 4157164 : size_t index = hash_index_for(hash_val, map->bucket_arr_size);
2396 :
2397 4157161 : size_t walk = 0;
2398 8330616 : llist_node* existing = sc_find_in_llist(
2399 4157161 : map->bucket_arr[index], hash_val, key_pair->ptr, key_pair->size,
2400 4157161 : map->key_type, map->custom_key_equality_proc, &walk);
2401 4157161 : if (existing) {
2402 9302 : if (slot_out) {
2403 15640 : *slot_out = &existing->val_pair_accessor;
2404 9302 : if (key_slot_out) {
2405 9302 : *key_slot_out = &existing->key_pair_accessor;
2406 : }
2407 6338 : return ccol_key_already_present;
2408 : }
2409 654 : return sc_reset_val_of_llist_node(existing, val_pair->ptr, val_pair->size,
2410 : map->m_procs)
2411 : ? ccol_key_already_present
2412 654 : : ccol_not_enough_memory;
2413 : }
2414 :
2415 4140869 : if (map->elem_count == ccol_max_elem_count) {
2416 : return ccol_container_full;
2417 : }
2418 :
2419 12438602 : llist_node* new_node = sc_create_llist_node(
2420 4140869 : &map->all_elems, map->m_procs, hash_val, key_pair->ptr, key_pair->size,
2421 4140869 : val_pair->ptr, val_pair->size);
2422 4140569 : if (!new_node) {
2423 : return ccol_not_enough_memory;
2424 : }
2425 :
2426 4140569 : new_node->next = map->bucket_arr[index];
2427 4140569 : map->bucket_arr[index] = new_node;
2428 4140569 : ++map->elem_count;
2429 :
2430 4140569 : if (__builtin_expect(walk >= SC_CHAIN_CAP, 0)) {
2431 13 : sc_note_long_chain(map);
2432 : }
2433 4140569 : if (__builtin_expect(chmap_window_add(chmap_of_sc(map), walk), 0)) {
2434 9138 : sc_window_end(map);
2435 : }
2436 :
2437 4140569 : if (map->elem_count >= map->elem_count_to_scale_up) {
2438 4022 : sc_scale(map, true);
2439 : }
2440 :
2441 9302 : if (slot_out) {
2442 1741021 : *slot_out = &new_node->val_pair_accessor;
2443 9302 : if (key_slot_out) {
2444 9302 : *key_slot_out = &new_node->key_pair_accessor;
2445 : }
2446 : }
2447 : return ccol_success;
2448 : }
2449 :
2450 : // Inserts or updates a pair in a chaining map; the backend of
2451 : // chashmap_insert_elem().
2452 2400397 : static ccol_retval sc_insert(sep_chain_map* map, const cmap_pair* key_pair,
2453 : const cmap_pair* val_pair) {
2454 2400397 : return sc_insert_impl(map, key_pair, val_pair, NULL, NULL);
2455 : }
2456 :
2457 : // Inserts a key that's absent and copies its value accessor to *slot_out
2458 : // either way; the chaining backend of ccol_chmap_insert_or_get_elem().
2459 1738163 : static ccol_retval sc_insert_or_get(sep_chain_map* map,
2460 : const cmap_pair* key_pair,
2461 : const cmap_pair* val_pair,
2462 : cmap_pair* slot_out) {
2463 1738163 : const cmap_pair* accessor = NULL;
2464 1738163 : ccol_retval ret = sc_insert_impl(map, key_pair, val_pair, &accessor, NULL);
2465 1738057 : if (accessor) {
2466 1738057 : *slot_out = *accessor;
2467 : }
2468 1738163 : return ret;
2469 : }
2470 :
2471 : // Inserts a key that's absent and hands out the key and value accessors of its
2472 : // node either way; the backend of ccol_chmap_insert_or_get_entry().
2473 18604 : static ccol_retval sc_insert_or_get_entry(sep_chain_map* map,
2474 : const cmap_pair* key_pair,
2475 : const cmap_pair* val_pair,
2476 : const cmap_pair** slot_out,
2477 : const cmap_pair** key_slot_out) {
2478 18604 : return sc_insert_impl(map, key_pair, val_pair, slot_out, key_slot_out);
2479 : }
2480 :
2481 : // Finds a key and points *val_pair at its node's value accessor, which stays
2482 : // put until the key is deleted; sc_get() and chashmap__get_val_accessor() use
2483 : // it. Forced inline into both; a call costs a string lookup about 15
2484 : // percent.
2485 2194738 : static inline __attribute__((always_inline)) ccol_retval sc_find_accessor(
2486 : sep_chain_map* map, const cmap_pair* key_pair, const cmap_pair** val_pair) {
2487 4389476 : size_t hash_val = hash_key_data(key_pair->ptr, key_pair->size, map->key_type,
2488 2194738 : map->custom_hashing_proc, sc_keyed(map),
2489 : g_chmap_hash_secret.int_seed);
2490 2194725 : size_t index = hash_index_for(hash_val, map->bucket_arr_size);
2491 :
2492 4389476 : llist_node* node = sc_find_in_llist(
2493 2194738 : map->bucket_arr[index], hash_val, key_pair->ptr, key_pair->size,
2494 2194738 : map->key_type, map->custom_key_equality_proc, NULL);
2495 2194738 : if (node) {
2496 2016131 : *val_pair = &node->val_pair_accessor;
2497 2016131 : return ccol_success;
2498 : }
2499 : return ccol_key_not_found;
2500 : }
2501 :
2502 : // Looks up a key in a chaining map and copies its value accessor into the
2503 : // caller's pair, or {NULL, 0}.
2504 2194725 : static ccol_retval sc_get(sep_chain_map* map, const cmap_pair* key_pair,
2505 : cmap_pair* val_pair) {
2506 2194725 : const cmap_pair* accessor;
2507 2194725 : if (sc_find_accessor(map, key_pair, &accessor) == ccol_success) {
2508 2016120 : *val_pair = *accessor;
2509 2016120 : return ccol_success;
2510 : }
2511 178605 : val_pair->ptr = NULL;
2512 178605 : val_pair->size = 0;
2513 178605 : return ccol_key_not_found;
2514 : }
2515 :
2516 : // Deletes a key from a chaining map; the array shrinks once the count drops
2517 : // below elem_count_to_scale_down.
2518 1320470 : static ccol_retval sc_delete(sep_chain_map* map, const cmap_pair* key_pair) {
2519 2640940 : size_t hash_val = hash_key_data(key_pair->ptr, key_pair->size, map->key_type,
2520 1320470 : map->custom_hashing_proc, sc_keyed(map),
2521 : g_chmap_hash_secret.int_seed);
2522 1320470 : size_t index = hash_index_for(hash_val, map->bucket_arr_size);
2523 :
2524 1320470 : bool found = false;
2525 2640940 : map->bucket_arr[index] = sc_delete_from_llist(
2526 1320470 : map->bucket_arr[index], &map->all_elems, map->m_procs, hash_val,
2527 1320470 : key_pair->ptr, key_pair->size, map->key_type,
2528 : map->custom_key_equality_proc, &found);
2529 :
2530 1320470 : if (found) {
2531 1320070 : if (--map->elem_count < map->elem_count_to_scale_down &&
2532 1107 : map->bucket_arr_size > minimum_allowed_bucket_array_size) {
2533 30 : sc_scale(map, false);
2534 : }
2535 1320070 : return ccol_success;
2536 : }
2537 : return ccol_key_not_found;
2538 : }
2539 :
2540 : // Frees every node of a chaining map at teardown, detaching each from
2541 : // all_elems first, and frees the bucket array unless it's the in-block one.
2542 1714368 : static void sc_destroy(sep_chain_map* map) {
2543 1714368 : llist_node** const buckets = map->bucket_arr;
2544 1714368 : const size_t bucket_count = map->bucket_arr_size;
2545 1714368 : ccol_memmgmt_procs* const m_procs = map->m_procs;
2546 10847465 : for (size_t i = 0; i < bucket_count; i++) {
2547 18266194 : sc_destroy_the_whole_llist(buckets[i], &map->all_elems, m_procs);
2548 : }
2549 1714368 : size_t inline_count = 0;
2550 3428727 : if (buckets != sc_inline_bucket_arr(map, &inline_count)) {
2551 2781 : ccol__mem_free(m_procs, buckets);
2552 : }
2553 1714368 : }
2554 :
2555 : // Clears every entry of a chaining map, for chashmap_reset(), and resizes the
2556 : // array unless new_bucket_array_size is 0. It checks the byte count itself,
2557 : // because a product that wraps to 0 could make realloc free the array. Every
2558 : // element is gone whatever it returns, and the in-block array is taken back
2559 : // or replaced, never reallocated.
2560 14 : static ccol_retval sc_reset(sep_chain_map* map, size_t new_bucket_array_size) {
2561 : {
2562 14 : llist_node** const buckets = map->bucket_arr;
2563 14 : const size_t bucket_count = map->bucket_arr_size;
2564 14 : ccol_memmgmt_procs* const m_procs = map->m_procs;
2565 1534 : for (size_t i = 0; i < bucket_count; i++) {
2566 3040 : buckets[i] =
2567 3040 : sc_destroy_the_whole_llist(buckets[i], &map->all_elems, m_procs);
2568 : }
2569 : }
2570 :
2571 14 : if (new_bucket_array_size > 0 &&
2572 8 : new_bucket_array_size != map->bucket_arr_size) {
2573 7 : if (new_bucket_array_size > SIZE_MAX / sizeof(llist_node*)) {
2574 1 : memset(map->bucket_arr, 0, map->bucket_arr_size * sizeof(llist_node*));
2575 1 : map->elem_count = 0;
2576 1 : sc_set_scaling_limits(map);
2577 1 : sc_window_restart(map);
2578 1 : return ccol_not_enough_memory;
2579 : }
2580 6 : size_t inline_count = 0;
2581 6 : llist_node** inline_arr = sc_inline_bucket_arr(map, &inline_count);
2582 6 : llist_node** orig = map->bucket_arr;
2583 6 : if (new_bucket_array_size == inline_count) {
2584 1 : ccol__mem_free(map->m_procs, orig);
2585 1 : map->bucket_arr = inline_arr;
2586 5 : } else if (orig == inline_arr) {
2587 3 : map->bucket_arr = ccol__mem_alloc(
2588 : map->m_procs, new_bucket_array_size * sizeof(llist_node*));
2589 : } else {
2590 2 : map->bucket_arr =
2591 2 : ccol__mem_realloc(map->m_procs, map->bucket_arr,
2592 : new_bucket_array_size * sizeof(llist_node*));
2593 : }
2594 6 : if (!map->bucket_arr) {
2595 1 : map->bucket_arr = orig;
2596 1 : memset(map->bucket_arr, 0, map->bucket_arr_size * sizeof(llist_node*));
2597 1 : map->elem_count = 0;
2598 1 : sc_set_scaling_limits(map);
2599 1 : sc_window_restart(map);
2600 1 : return ccol_not_enough_memory;
2601 : }
2602 5 : map->bucket_arr_size = new_bucket_array_size;
2603 : }
2604 :
2605 12 : memset(map->bucket_arr, 0, map->bucket_arr_size * sizeof(llist_node*));
2606 12 : map->elem_count = 0;
2607 12 : sc_set_scaling_limits(map);
2608 12 : sc_window_restart(map);
2609 :
2610 12 : return ccol_success;
2611 : }
2612 :
2613 : // The iterator behind a cmap_iterator of a map. free_fn is copied from the
2614 : // map, because a scoped iterator can be freed after the map and its procs are
2615 : // gone.
2616 : typedef struct chmap_cmap_iterator {
2617 : chmap parent_map;
2618 : ccol_free free_fn;
2619 : union {
2620 : dllist_ref_node* sc_tracker;
2621 : size_t oa_index;
2622 : } iter;
2623 : cmap_pair oa_key_pair;
2624 : cmap_pair oa_val_pair;
2625 : cmap_iterator user_iter;
2626 : } chmap_cmap_iterator;
2627 :
2628 : // Gives the chmap_cmap_iterator that holds the cmap_iterator u_iter points
2629 : // at, so the next and free functions reach their state from the caller's
2630 : // pointer.
2631 : #define cmapIter2ChmapIter(u_iter) \
2632 : (chmap_cmap_iterator*)((uint8_t*)u_iter - \
2633 : offsetof(chmap_cmap_iterator, user_iter))
2634 :
2635 : // Creates a map in one block (see struct chashmap) and picks the backend; the
2636 : // body of every constructor. A custom equality without a custom hash is
2637 : // refused, and it forces separate chaining so the open-addressing probe stays
2638 : // free of an indirect call. An interned procs pointer is kept, any other is
2639 : // copied into the block. The process secret is picked here, before any hash.
2640 : // sc_min_buckets is the smallest first chaining array: The public minimum, or
2641 : // compact_bucket_array_size. Gives NULL with *err set on failure.
2642 1756291 : static chmap chmap_create_impl(size_t initial_bucket_array_size,
2643 : ccol_data_type key_type, ccol_data_type val_type,
2644 : ccol_memmgmt_procs* mmgmt_procs,
2645 : ccol_hashing_proc custom_hashing_proc,
2646 : ccol_key_equality_proc custom_key_equality_proc,
2647 : size_t sc_min_buckets, char** err) {
2648 1756291 : if (initial_bucket_array_size == 0) {
2649 1 : if (err) *err = CCOL__ERR_STR("initial_bucket_array_size is zero");
2650 1 : return NULL;
2651 : }
2652 :
2653 1756290 : if (custom_key_equality_proc && !custom_hashing_proc) {
2654 1 : if (err) {
2655 1 : *err = CCOL__ERR_STR(
2656 : "custom_key_equality_proc needs a custom_hashing_proc that agrees "
2657 : "with it");
2658 : }
2659 1 : return NULL;
2660 : }
2661 :
2662 1756289 : if (!ccol__verify_memmgmt_procs(mmgmt_procs, err)) {
2663 4 : return NULL;
2664 : }
2665 :
2666 1756285 : bool open_addressing = !custom_key_equality_proc &&
2667 1756280 : should_use_open_addressing(key_type, val_type);
2668 1756285 : size_t floor =
2669 : open_addressing ? minimum_allowed_bucket_array_size : sc_min_buckets;
2670 :
2671 1756285 : if (initial_bucket_array_size <= floor) {
2672 : initial_bucket_array_size = floor;
2673 : } else {
2674 41 : initial_bucket_array_size =
2675 41 : ccol__find_nearest_gte_power_of_two(initial_bucket_array_size);
2676 41 : if (initial_bucket_array_size > ccol_max_elem_count) {
2677 0 : if (err) {
2678 0 : *err = CCOL__ERR_STR("Initial bucket array size is too big");
2679 : }
2680 0 : return NULL;
2681 : }
2682 : }
2683 :
2684 3512570 : size_t inline_buckets =
2685 1756285 : (!open_addressing &&
2686 1756285 : initial_bucket_array_size <= minimum_allowed_bucket_array_size)
2687 : ? initial_bucket_array_size
2688 1756285 : : 0;
2689 1756285 : bool copy_procs = mmgmt_procs && !ccol_procs_is_interned(mmgmt_procs);
2690 1756285 : size_t procs_offset =
2691 1756285 : sizeof(struct chashmap) + inline_buckets * sizeof(llist_node*);
2692 3512570 : size_t block_bytes =
2693 1756285 : procs_offset + (copy_procs ? sizeof(ccol_memmgmt_procs) : 0);
2694 :
2695 1756285 : chmap chm = (chmap)ccol__mem_alloc(mmgmt_procs, block_bytes);
2696 1756285 : if (!chm) {
2697 112 : if (err) *err = CCOL__ERR_STR("Failed to allocate chashmap");
2698 112 : return NULL;
2699 : }
2700 1756173 : chm->hash_mode = CHMAP_HASH_FAST;
2701 1756173 : chm->insert_window = CHMAP_WINDOW_START;
2702 1756173 : chm->window_bound = UINT16_MAX;
2703 1756173 : memset(chm + 1, 0, inline_buckets * sizeof(llist_node*));
2704 :
2705 1756173 : ccol_memmgmt_procs* m_procs = mmgmt_procs;
2706 1756173 : if (copy_procs) {
2707 3238 : m_procs = (ccol_memmgmt_procs*)((uint8_t*)chm + procs_offset);
2708 3238 : memcpy(m_procs, mmgmt_procs, sizeof(ccol_memmgmt_procs));
2709 : }
2710 :
2711 1756173 : (void)chmap_process_hash_secret();
2712 :
2713 1756173 : if (open_addressing) {
2714 41704 : chm->impl_type = IMPL_OPEN_ADDRESSING;
2715 41704 : chm->impl.oa = &chm->state.oa;
2716 125112 : if (!oa_init(chm->impl.oa, initial_bucket_array_size, key_type, val_type,
2717 : get_type_size(key_type), get_type_size(val_type), m_procs,
2718 : custom_hashing_proc)) {
2719 12 : if (err) *err = CCOL__ERR_STR("Failed to create open addressing map");
2720 12 : ccol__mem_free(mmgmt_procs, chm);
2721 12 : return NULL;
2722 : }
2723 83384 : oa_window_restart(chm->impl.oa);
2724 : } else {
2725 1714469 : chm->impl_type = IMPL_SEPARATE_CHAINING;
2726 1714469 : chm->impl.sc = &chm->state.sc;
2727 1714469 : chm->state.sc.inline_buckets = (uint8_t)inline_buckets;
2728 1714469 : if (!sc_init(chm->impl.sc, initial_bucket_array_size, key_type, val_type,
2729 : m_procs, custom_hashing_proc, custom_key_equality_proc)) {
2730 0 : if (err) *err = CCOL__ERR_STR("Failed to create separate chaining map");
2731 0 : ccol__mem_free(mmgmt_procs, chm);
2732 0 : return NULL;
2733 : }
2734 : }
2735 :
2736 1756155 : if (err) *err = NULL;
2737 : return chm;
2738 : }
2739 :
2740 : // Creates a map with every option; the constructor behind chashmap_create()
2741 : // and the chmap_construct macros. It applies the public minimum bucket count;
2742 : // the rest is chmap_create_impl().
2743 65899 : chmap chashmap_create_full(size_t initial_bucket_array_size,
2744 : ccol_data_type key_type, ccol_data_type val_type,
2745 : ccol_memmgmt_procs* mmgmt_procs,
2746 : ccol_hashing_proc custom_hashing_proc,
2747 : ccol_key_equality_proc custom_key_equality_proc,
2748 : char** err) {
2749 65899 : return chmap_create_impl(initial_bucket_array_size, key_type, val_type,
2750 : mmgmt_procs, custom_hashing_proc,
2751 : custom_key_equality_proc,
2752 : minimum_allowed_bucket_array_size, err);
2753 : }
2754 :
2755 : // Creates a map whose chaining bucket array starts at
2756 : // compact_bucket_array_size inside its block, for the JSON and YAML parsers,
2757 : // which make many small dictionaries. Gives NULL with *err set on failure.
2758 1690392 : chmap ccol_chmap_create_compact(ccol_data_type key_type,
2759 : ccol_data_type val_type,
2760 : ccol_memmgmt_procs* mmgmt_procs, char** err) {
2761 1690392 : return chmap_create_impl(compact_bucket_array_size, key_type, val_type,
2762 : mmgmt_procs, NULL, NULL, compact_bucket_array_size,
2763 : err);
2764 : }
2765 :
2766 : // Give the key type and the value type a map was made with, whatever the
2767 : // backend, for the size checks of the public entry points.
2768 24661865 : static inline ccol_data_type chmap_key_type(chmap chm) {
2769 41651348 : return chm->impl_type == IMPL_OPEN_ADDRESSING ? chm->impl.oa->key_type
2770 24643248 : : chm->impl.sc->key_type;
2771 : }
2772 :
2773 9959062 : static inline ccol_data_type chmap_val_type(chmap chm) {
2774 15760960 : return chm->impl_type == IMPL_OPEN_ADDRESSING ? chm->impl.oa->val_type
2775 9940458 : : chm->impl.sc->val_type;
2776 : }
2777 :
2778 : // Gives the canonical form of a key for hashing and comparing: For a float or
2779 : // double key a copy in out_canon_* with -0.0 turned into 0.0, so the bitwise
2780 : // key equality agrees with ==. Every other key, and every NaN payload, comes
2781 : // back as it is.
2782 24706277 : static inline const cmap_pair* canonicalize_key_pair_if_needed(
2783 : const cmap_pair* key_pair, ccol_data_type key_type, uint64_t* out_canon_buf,
2784 : cmap_pair* out_canon_pair) {
2785 24706277 : if ((key_type != ccol_float && key_type != ccol_double) ||
2786 40416 : key_pair->size > sizeof(*out_canon_buf)) {
2787 : return key_pair;
2788 : }
2789 :
2790 40416 : *out_canon_buf = 0;
2791 40416 : memcpy(out_canon_buf, key_pair->ptr, key_pair->size);
2792 :
2793 40416 : if (key_type == ccol_float) {
2794 18 : uint32_t bits;
2795 18 : memcpy(&bits, out_canon_buf, sizeof(bits));
2796 18 : if (bits == 0x80000000u) {
2797 2 : memset(out_canon_buf, 0, sizeof(bits));
2798 : }
2799 40398 : } else if (*out_canon_buf == 0x8000000000000000ULL) {
2800 8 : *out_canon_buf = 0;
2801 : }
2802 :
2803 40416 : out_canon_pair->ptr = out_canon_buf;
2804 40416 : out_canon_pair->size = key_pair->size;
2805 40416 : return out_canon_pair;
2806 : }
2807 :
2808 : // Gives the keyed hash of the canonical form of a key, so clrucache and other
2809 : // modules agree with the map about key identity; see chashkey.h.
2810 44436 : size_t ccol_chmap_hash_key(const void* key_ptr, size_t key_size,
2811 : ccol_data_type key_type) {
2812 44436 : cmap_pair given = {.ptr = (void*)key_ptr, .size = key_size};
2813 44436 : uint64_t canon_buf = 0;
2814 44436 : cmap_pair canon_pair = {.ptr = NULL, .size = 0};
2815 44436 : const cmap_pair* key = canonicalize_key_pair_if_needed(
2816 : &given, key_type, &canon_buf, &canon_pair);
2817 44436 : const chmap_hash_secret* secret = chmap_process_hash_secret();
2818 88872 : return hash_key_data(key->ptr, key->size, key_type, NULL, true,
2819 44436 : secret->int_seed);
2820 : }
2821 :
2822 : // Tells whether a value fits an open-addressing slot exactly. The insert
2823 : // copies without a bound, so a different size would overwrite the next
2824 : // slot.
2825 5801896 : static inline bool oa_val_size_matches(const open_addr_map* map,
2826 : size_t val_size) {
2827 5801896 : return val_size == map->val_size;
2828 : }
2829 :
2830 : // Tells whether key_size is right for the key type, checked by every entry
2831 : // point on both backends: For a fixed-width type
2832 : // (ccol_fixed_width_data_type_size(), shared with cbstmap) it must be that
2833 : // width, because the hash, the canonical form and the long double compare read
2834 : // that many bytes. Keys with no fixed width always pass.
2835 24661865 : static inline bool key_size_matches_type_if_fixed_width(ccol_data_type key_type,
2836 : size_t key_size) {
2837 49323730 : size_t fixed_width = ccol_fixed_width_data_type_size(key_type);
2838 24661865 : return fixed_width == 0 || key_size == fixed_width;
2839 : }
2840 :
2841 : // Tells whether val_size is right for a fixed-width value type. Separate
2842 : // chaining would store a wrong size safely, but the first chmap_get() would
2843 : // then stop the program at a call site that did nothing wrong. Only the raw
2844 : // layer can get here with a wrong size.
2845 9959062 : static inline bool val_size_matches_type_if_fixed_width(ccol_data_type val_type,
2846 : size_t val_size) {
2847 19918124 : size_t fixed_width = ccol_fixed_width_data_type_size(val_type);
2848 9959062 : return fixed_width == 0 || val_size == fixed_width;
2849 : }
2850 :
2851 : // Checks the inputs of an insert and calls the backend; the body of the three
2852 : // public inserts. slot_out is as in oa_insert_impl(); entry_val_out and
2853 : // key_slot_out are sc_insert_impl()'s and come together, only for a chaining
2854 : // map.
2855 9959076 : static inline __attribute__((always_inline)) ccol_retval chmap_insert_elem_impl(
2856 : chmap chm, const cmap_pair* key_pair, const cmap_pair* val_pair,
2857 : cmap_pair* slot_out, const cmap_pair** entry_val_out,
2858 : const cmap_pair** key_slot_out) {
2859 9959075 : if (!chm || !key_pair || !val_pair || !key_pair->ptr || !val_pair->ptr ||
2860 9959069 : key_pair->size == 0 || val_pair->size == 0) {
2861 : return ccol_invalid_args;
2862 : }
2863 :
2864 9940463 : ccol_data_type key_type = chmap_key_type(chm);
2865 19918133 : if (!key_size_matches_type_if_fixed_width(key_type, key_pair->size)) {
2866 : return ccol_invalid_args;
2867 : }
2868 :
2869 29858582 : if (!val_size_matches_type_if_fixed_width(chmap_val_type(chm),
2870 : val_pair->size)) {
2871 : return ccol_invalid_args;
2872 : }
2873 :
2874 9940455 : if (chm->impl_type == IMPL_OPEN_ADDRESSING &&
2875 5801896 : !oa_val_size_matches(chm->impl.oa, val_pair->size)) {
2876 : return ccol_invalid_args;
2877 : }
2878 :
2879 9959059 : uint64_t canon_buf;
2880 9959059 : cmap_pair canon_pair;
2881 9959059 : key_pair = canonicalize_key_pair_if_needed(key_pair, key_type, &canon_buf,
2882 : &canon_pair);
2883 :
2884 9959057 : if (key_slot_out) {
2885 18604 : return sc_insert_or_get_entry(chm->impl.sc, key_pair, val_pair,
2886 : entry_val_out, key_slot_out);
2887 : }
2888 9940453 : if (slot_out) {
2889 1746164 : if (chm->impl_type == IMPL_OPEN_ADDRESSING) {
2890 8001 : return oa_insert_or_get(chm->impl.oa, key_pair, val_pair, slot_out);
2891 : }
2892 1738163 : return sc_insert_or_get(chm->impl.sc, key_pair, val_pair, slot_out);
2893 : }
2894 :
2895 8194289 : if (chm->impl_type == IMPL_OPEN_ADDRESSING) {
2896 5793892 : return oa_insert(chm->impl.oa, key_pair, val_pair);
2897 : } else {
2898 2400397 : return sc_insert(chm->impl.sc, key_pair, val_pair);
2899 : }
2900 : }
2901 :
2902 : // Inserts a pair or replaces the value of a present key; the raw entry point
2903 : // behind chmap_insert(). Gives ccol_success, ccol_key_already_present or the
2904 : // error of the checks and the backend.
2905 8194308 : ccol_retval chashmap_insert_elem(chmap chm, const cmap_pair* key_pair,
2906 : const cmap_pair* val_pair) {
2907 8194308 : return chmap_insert_elem_impl(chm, key_pair, val_pair, NULL, NULL, NULL);
2908 : }
2909 :
2910 : // Inserts a key that's absent and fills *val_slot with its value pair either
2911 : // way, in one hash and one probe, so a parser can replace an owning value
2912 : // without a second lookup. *val_slot is {NULL, 0} on failure.
2913 1746165 : ccol_retval ccol_chmap_insert_or_get_elem(chmap chm, const cmap_pair* key_pair,
2914 : const cmap_pair* val_pair,
2915 : cmap_pair* val_slot) {
2916 1746165 : if (!val_slot) {
2917 : return ccol_invalid_args;
2918 : }
2919 1746164 : val_slot->ptr = NULL;
2920 1746164 : val_slot->size = 0;
2921 3492330 : return chmap_insert_elem_impl(chm, key_pair, val_pair, val_slot, NULL, NULL);
2922 : }
2923 :
2924 : // Gives the oldest entry of a chaining map (the list's tail), the start of the
2925 : // ordered walk of chashinsert.h, or NULL. An entry reference is the address of
2926 : // a node's dllist_refs, so a step allocates nothing.
2927 91986 : const ccol_chmap_entry_ref* ccol_chmap_oldest_entry(chmap chm) {
2928 60439 : if (!chm || chm->impl_type != IMPL_SEPARATE_CHAINING) {
2929 : return NULL;
2930 : }
2931 60437 : return (const ccol_chmap_entry_ref*)chm->impl.sc->all_elems.tail;
2932 : }
2933 :
2934 : // Gives the key and value accessors of an entry and the next newer entry (its
2935 : // prev link), or NULL at the newest.
2936 106610 : const ccol_chmap_entry_ref* ccol_chmap_entry_read(
2937 : const ccol_chmap_entry_ref* entry, const cmap_pair** key,
2938 : const cmap_pair** val) {
2939 106610 : dllist_ref_node* tracker = (dllist_ref_node*)entry;
2940 106610 : llist_node* host = dllistRefNodePtr2LlistNodePtr(tracker);
2941 106610 : *key = &host->key_pair_accessor;
2942 106610 : *val = &host->val_pair_accessor;
2943 106610 : return (const ccol_chmap_entry_ref*)tracker->prev;
2944 : }
2945 :
2946 : // Gives the next live entry of a walk over either backend, so a teardown can
2947 : // reach every value without allocating: Chaining maps follow the ordered
2948 : // cursor, open-addressing maps the slots. Gives false at the end or for a NULL
2949 : // chm.
2950 120816 : bool ccol_chmap_walk_next(chmap chm, ccol_chmap_walk* walk, const void** key,
2951 : const void** val) {
2952 120816 : if (!chm) {
2953 : return false;
2954 : }
2955 120815 : if (chm->impl_type == IMPL_SEPARATE_CHAINING) {
2956 40915 : if (!walk->started) {
2957 31974 : walk->started = true;
2958 31974 : walk->next_entry = ccol_chmap_oldest_entry(chm);
2959 : }
2960 40915 : if (!walk->next_entry) {
2961 : return false;
2962 : }
2963 13251 : const cmap_pair* k;
2964 13251 : const cmap_pair* v;
2965 13251 : walk->next_entry = ccol_chmap_entry_read(walk->next_entry, &k, &v);
2966 13251 : *key = k->ptr;
2967 13251 : *val = v->ptr;
2968 13251 : return true;
2969 : }
2970 79900 : open_addr_map* map = chm->impl.oa;
2971 79900 : size_t i = walk->next_slot;
2972 696751 : while (i < map->capacity && !(map->metadata[i] & SLOT_OCCUPIED)) {
2973 616851 : i++;
2974 : }
2975 79900 : if (i >= map->capacity) {
2976 40927 : walk->next_slot = i;
2977 40927 : return false;
2978 : }
2979 38973 : walk->next_slot = i + 1;
2980 38973 : *key = &map->slots[i].key_data;
2981 38973 : *val = &map->slots[i].val_data;
2982 38973 : return true;
2983 : }
2984 :
2985 : // ccol_chmap_insert_or_get_elem() that also hands out the stored key's
2986 : // accessor. Only a chaining node has one, so an open-addressing map gives
2987 : // ccol_invalid_args; both out parameters are NULL on failure.
2988 18607 : ccol_retval ccol_chmap_insert_or_get_entry(chmap chm, const cmap_pair* key_pair,
2989 : const cmap_pair* val_pair,
2990 : const cmap_pair** key_slot,
2991 : const cmap_pair** val_slot) {
2992 18607 : if (!key_slot || !val_slot) {
2993 : return ccol_invalid_args;
2994 : }
2995 18606 : *key_slot = NULL;
2996 18606 : *val_slot = NULL;
2997 18606 : if (!chm || chm->impl_type != IMPL_SEPARATE_CHAINING) {
2998 : return ccol_invalid_args;
2999 : }
3000 37208 : return chmap_insert_elem_impl(chm, key_pair, val_pair, NULL, val_slot,
3001 : key_slot);
3002 : }
3003 :
3004 : // Fills *val_pair with the location and size of the stored value of a key;
3005 : // the lookup behind chmap_get() and chmap_get_ptr(). Every failure sets it to
3006 : // {NULL, 0}.
3007 10421243 : ccol_retval chashmap_get_elem_ref(chmap chm, const cmap_pair* key_pair,
3008 : cmap_pair* val_pair) {
3009 10421243 : if (!val_pair) {
3010 : return ccol_invalid_args;
3011 : }
3012 10421242 : if (!chm || !key_pair || !key_pair->ptr || key_pair->size == 0) {
3013 10 : val_pair->ptr = NULL;
3014 10 : val_pair->size = 0;
3015 10 : return ccol_invalid_args;
3016 : }
3017 :
3018 10421232 : ccol_data_type key_type = chmap_key_type(chm);
3019 20842463 : if (!key_size_matches_type_if_fixed_width(key_type, key_pair->size)) {
3020 5 : val_pair->ptr = NULL;
3021 5 : val_pair->size = 0;
3022 5 : return ccol_invalid_args;
3023 : }
3024 :
3025 10421227 : uint64_t canon_buf;
3026 10421227 : cmap_pair canon_pair;
3027 10421227 : key_pair = canonicalize_key_pair_if_needed(key_pair, key_type, &canon_buf,
3028 : &canon_pair);
3029 :
3030 10421228 : if (chm->impl_type == IMPL_OPEN_ADDRESSING) {
3031 8226503 : return oa_get(chm->impl.oa, key_pair, val_pair);
3032 : } else {
3033 2194725 : return sc_get(chm->impl.sc, key_pair, val_pair);
3034 : }
3035 : }
3036 :
3037 : // Gives the node's value accessor of a key, whose ptr field is the stored
3038 : // char * that the string arm of chmap_get_ptr() hands out. An
3039 : // open-addressing map never holds a string and gives ccol_invalid_args; every
3040 : // failure sets *val_accessor to NULL.
3041 15 : ccol_retval chashmap__get_val_accessor(chmap chm, const cmap_pair* key_pair,
3042 : const cmap_pair** val_accessor) {
3043 15 : if (!val_accessor) {
3044 : return ccol_invalid_args;
3045 : }
3046 15 : *val_accessor = NULL;
3047 15 : if (!chm || !key_pair || !key_pair->ptr || key_pair->size == 0 ||
3048 14 : chm->impl_type != IMPL_SEPARATE_CHAINING) {
3049 : return ccol_invalid_args;
3050 : }
3051 :
3052 13 : ccol_data_type key_type = chmap_key_type(chm);
3053 26 : if (!key_size_matches_type_if_fixed_width(key_type, key_pair->size)) {
3054 : return ccol_invalid_args;
3055 : }
3056 :
3057 13 : uint64_t canon_buf;
3058 13 : cmap_pair canon_pair;
3059 13 : key_pair = canonicalize_key_pair_if_needed(key_pair, key_type, &canon_buf,
3060 : &canon_pair);
3061 13 : ccol_retval ret = sc_find_accessor(chm->impl.sc, key_pair, val_accessor);
3062 11 : if (ret != ccol_success) {
3063 2 : *val_accessor = NULL;
3064 : }
3065 : return ret;
3066 : }
3067 :
3068 : // Copies up to target_buf_size bytes of the value of a key into target_buf and
3069 : // zeroes the rest, for a caller that wants its own copy.
3070 92 : ccol_retval chashmap_get_elem_copy(chmap chm, const cmap_pair* key_pair,
3071 : void* target_buf, size_t target_buf_size) {
3072 92 : if (!target_buf || target_buf_size == 0) {
3073 : return ccol_invalid_args;
3074 : }
3075 90 : cmap_pair val_pair;
3076 90 : ccol_retval ret = chashmap_get_elem_ref(chm, key_pair, &val_pair);
3077 90 : if (ret == ccol_success) {
3078 83 : size_t copy_size =
3079 83 : val_pair.size < target_buf_size ? val_pair.size : target_buf_size;
3080 83 : memcpy(target_buf, val_pair.ptr, copy_size);
3081 83 : if (val_pair.size < target_buf_size) {
3082 2 : memset((uint8_t*)target_buf + val_pair.size, 0,
3083 : target_buf_size - val_pair.size);
3084 : }
3085 : }
3086 : return ret;
3087 : }
3088 :
3089 : // Deletes a key and its value; the raw entry point behind chmap_remove(). It
3090 : // checks the inputs and calls the backend's delete.
3091 4281559 : ccol_retval chashmap_remove_elem(chmap chm, const cmap_pair* key_pair) {
3092 4281559 : if (!chm || !key_pair || !key_pair->ptr || key_pair->size == 0) {
3093 : return ccol_invalid_args;
3094 : }
3095 :
3096 4281553 : ccol_data_type key_type = chmap_key_type(chm);
3097 8563106 : if (!key_size_matches_type_if_fixed_width(key_type, key_pair->size)) {
3098 : return ccol_invalid_args;
3099 : }
3100 :
3101 4281549 : uint64_t canon_buf;
3102 4281549 : cmap_pair canon_pair;
3103 4281549 : key_pair = canonicalize_key_pair_if_needed(key_pair, key_type, &canon_buf,
3104 : &canon_pair);
3105 :
3106 4281549 : if (chm->impl_type == IMPL_OPEN_ADDRESSING) {
3107 2961079 : return oa_delete(chm->impl.oa, key_pair);
3108 : } else {
3109 1320470 : return sc_delete(chm->impl.sc, key_pair);
3110 : }
3111 : }
3112 :
3113 : // Gives the number of live entries of either backend. Asserts on a NULL chm.
3114 163139 : size_t chashmap_size(chmap chm) {
3115 163139 : if (!chm) {
3116 0 : ccol__assert(false);
3117 : }
3118 :
3119 163139 : if (chm->impl_type == IMPL_OPEN_ADDRESSING) {
3120 49146 : return chm->impl.oa->count;
3121 : } else {
3122 113993 : return chm->impl.sc->elem_count;
3123 : }
3124 : }
3125 :
3126 : // Removes every entry and resizes the array when new_bucket_array_size isn't
3127 : // 0, rounded up to a power of two (at least the minimum). A size too big to
3128 : // round falls back to 0, so the reset still destroys every element.
3129 21 : ccol_retval chashmap_reset(chmap chm, size_t new_bucket_array_size) {
3130 21 : if (!chm) {
3131 0 : ccol__assert(false);
3132 : }
3133 :
3134 21 : bool requested_size_too_big = false;
3135 21 : if (new_bucket_array_size > 0 &&
3136 : new_bucket_array_size < minimum_allowed_bucket_array_size) {
3137 : new_bucket_array_size = minimum_allowed_bucket_array_size;
3138 20 : } else if (new_bucket_array_size > 0) {
3139 12 : new_bucket_array_size =
3140 12 : ccol__find_nearest_gte_power_of_two(new_bucket_array_size);
3141 12 : if (new_bucket_array_size > ccol_max_elem_count) {
3142 2 : new_bucket_array_size = 0;
3143 2 : requested_size_too_big = true;
3144 : }
3145 : }
3146 :
3147 21 : ccol_retval r;
3148 21 : if (chm->impl_type == IMPL_OPEN_ADDRESSING) {
3149 7 : r = oa_reset(chm->impl.oa, new_bucket_array_size);
3150 : } else {
3151 14 : r = sc_reset(chm->impl.sc, new_bucket_array_size);
3152 : }
3153 :
3154 21 : if (requested_size_too_big) {
3155 2 : return ccol_not_enough_memory;
3156 : }
3157 : return r;
3158 : }
3159 :
3160 : static cmap_iterator* chmap_iter_next(cmap_iterator* iter);
3161 :
3162 : // The net count of iterators that chashmap_begin_iter() allocated and nothing
3163 : // freed, which a test destructor checks. valgrind reports a live iterator as
3164 : // possibly lost (an interior pointer), so it can't guard this.
3165 : #ifdef RUNNING_UNIT_TESTS
3166 : static long g_chmap_iter_outstanding_for_tests = 0;
3167 : // Gives the net count of live chashmap iterators.
3168 2 : long chashmap_iter_outstanding_count_for_tests(void) {
3169 2 : return __atomic_load_n(&g_chmap_iter_outstanding_for_tests, __ATOMIC_SEQ_CST);
3170 : }
3171 : #endif
3172 :
3173 : // Creates an iterator at the newest entry of a chaining map or the first
3174 : // occupied slot; the begin function behind ccol_begin(). Gives NULL with no
3175 : // error for an empty or NULL map, and NULL with *err set when the allocation
3176 : // fails.
3177 6034 : cmap_iterator* chashmap_begin_iter(chmap chm, char** err) {
3178 6034 : if (err) {
3179 5783 : *err = NULL;
3180 : }
3181 :
3182 6034 : if (!chm) {
3183 : return NULL;
3184 : }
3185 :
3186 6031 : if (chm->impl_type == IMPL_SEPARATE_CHAINING) {
3187 2048 : if (!chm->impl.sc->all_elems.head) {
3188 : return NULL;
3189 : }
3190 :
3191 2012 : ccol_memmgmt_procs* m_procs = chm->impl.sc->m_procs;
3192 2012 : chmap_cmap_iterator* real_iter =
3193 2012 : ccol__mem_calloc(m_procs, 1, sizeof(chmap_cmap_iterator));
3194 2012 : if (!real_iter) {
3195 2 : if (err) {
3196 2 : *err = CCOL__ERR_STR("Failed to allocate iterator");
3197 : }
3198 2 : return NULL;
3199 : }
3200 :
3201 : #ifdef RUNNING_UNIT_TESTS
3202 2010 : __atomic_fetch_add(&g_chmap_iter_outstanding_for_tests, 1,
3203 : __ATOMIC_SEQ_CST);
3204 : #endif
3205 2010 : dllist_ref_node* tracker = chm->impl.sc->all_elems.head;
3206 2010 : real_iter->parent_map = chm;
3207 2010 : real_iter->free_fn = m_procs ? m_procs->free : NULL;
3208 2010 : real_iter->iter.sc_tracker = tracker;
3209 2010 : llist_node* host = dllistRefNodePtr2LlistNodePtr(tracker);
3210 2010 : real_iter->user_iter.key_pair = &(host->key_pair_accessor);
3211 2010 : real_iter->user_iter.val_pair = &(host->val_pair_accessor);
3212 2010 : real_iter->user_iter.ccol__next_fn = chmap_iter_next;
3213 2010 : real_iter->user_iter.ccol__free_fn = chashmap__iterator_destroy;
3214 2010 : real_iter->user_iter.ccol__direct_ptr = false;
3215 :
3216 2010 : return &(real_iter->user_iter);
3217 : } else {
3218 3983 : open_addr_map* map = chm->impl.oa;
3219 :
3220 3983 : size_t i = 0;
3221 4265 : while (i < map->capacity && !(map->metadata[i] & SLOT_OCCUPIED)) {
3222 282 : i++;
3223 : }
3224 :
3225 3983 : if (i >= map->capacity) {
3226 : return NULL;
3227 : }
3228 :
3229 7962 : chmap_cmap_iterator* real_iter =
3230 3981 : ccol__mem_calloc(map->m_procs, 1, sizeof(chmap_cmap_iterator));
3231 3981 : if (!real_iter) {
3232 0 : if (err) {
3233 0 : *err = CCOL__ERR_STR("Failed to allocate iterator");
3234 : }
3235 0 : return NULL;
3236 : }
3237 :
3238 : #ifdef RUNNING_UNIT_TESTS
3239 3981 : __atomic_fetch_add(&g_chmap_iter_outstanding_for_tests, 1,
3240 : __ATOMIC_SEQ_CST);
3241 : #endif
3242 3981 : real_iter->parent_map = chm;
3243 3981 : real_iter->free_fn = map->m_procs ? map->m_procs->free : NULL;
3244 3981 : real_iter->iter.oa_index = i;
3245 :
3246 3981 : real_iter->oa_key_pair.ptr = &map->slots[i].key_data;
3247 3981 : real_iter->oa_key_pair.size = map->key_size;
3248 3981 : real_iter->oa_val_pair.ptr = &map->slots[i].val_data;
3249 3981 : real_iter->oa_val_pair.size = map->val_size;
3250 :
3251 3981 : real_iter->user_iter.key_pair = &real_iter->oa_key_pair;
3252 3981 : real_iter->user_iter.val_pair = &real_iter->oa_val_pair;
3253 3981 : real_iter->user_iter.ccol__next_fn = chmap_iter_next;
3254 3981 : real_iter->user_iter.ccol__free_fn = chashmap__iterator_destroy;
3255 3981 : real_iter->user_iter.ccol__direct_ptr = false;
3256 :
3257 3981 : return &(real_iter->user_iter);
3258 : }
3259 : }
3260 :
3261 : // Frees an iterator with its own free_fn, the free function every map
3262 : // iterator carries. It reads nothing of the map, which may be gone already.
3263 5991 : void chashmap__iterator_destroy(cmap_iterator* iter) {
3264 5991 : if (iter) {
3265 5991 : chmap_cmap_iterator* real_iter = cmapIter2ChmapIter(iter);
3266 : #ifdef RUNNING_UNIT_TESTS
3267 5991 : __atomic_fetch_sub(&g_chmap_iter_outstanding_for_tests, 1,
3268 : __ATOMIC_SEQ_CST);
3269 : #endif
3270 5991 : ccol_free free_fn = real_iter->free_fn;
3271 5991 : if (free_fn) {
3272 9 : free_fn(real_iter);
3273 : } else {
3274 5982 : ccol__default_mem_free(real_iter);
3275 : }
3276 : }
3277 5991 : }
3278 :
3279 : // Moves an iterator to the next entry (next link, or next occupied slot); the
3280 : // next function of every map iterator. At the end it frees the iterator and
3281 : // gives NULL.
3282 448292 : static cmap_iterator* chmap_iter_next(cmap_iterator* iter) {
3283 448292 : chmap_cmap_iterator* real_iter = cmapIter2ChmapIter(iter);
3284 :
3285 448292 : if (real_iter->parent_map->impl_type == IMPL_SEPARATE_CHAINING) {
3286 141556 : real_iter->iter.sc_tracker = real_iter->iter.sc_tracker->next;
3287 :
3288 141556 : if (real_iter->iter.sc_tracker) {
3289 139559 : dllist_ref_node* tracker = real_iter->iter.sc_tracker;
3290 139559 : llist_node* host = dllistRefNodePtr2LlistNodePtr(tracker);
3291 139559 : iter->key_pair = &(host->key_pair_accessor);
3292 139559 : iter->val_pair = &(host->val_pair_accessor);
3293 : } else {
3294 1997 : chashmap__iterator_destroy(iter);
3295 1997 : iter = NULL;
3296 : }
3297 : } else {
3298 306736 : open_addr_map* map = real_iter->parent_map->impl.oa;
3299 306736 : size_t i = real_iter->iter.oa_index + 1;
3300 :
3301 665834 : while (i < map->capacity && !(map->metadata[i] & SLOT_OCCUPIED)) {
3302 359098 : i++;
3303 : }
3304 :
3305 306736 : if (i >= map->capacity) {
3306 3979 : chashmap__iterator_destroy(iter);
3307 3979 : iter = NULL;
3308 : } else {
3309 302757 : real_iter->iter.oa_index = i;
3310 :
3311 302757 : real_iter->oa_key_pair.ptr = &map->slots[i].key_data;
3312 302757 : real_iter->oa_key_pair.size = map->key_size;
3313 302757 : real_iter->oa_val_pair.ptr = &map->slots[i].val_data;
3314 302757 : real_iter->oa_val_pair.size = map->val_size;
3315 :
3316 302757 : iter->key_pair = &real_iter->oa_key_pair;
3317 302757 : iter->val_pair = &real_iter->oa_val_pair;
3318 : }
3319 : }
3320 :
3321 448292 : return iter;
3322 : }
3323 :
3324 : // Frees every entry, the backend's arrays and the map's block; the body of
3325 : // chashmap_destroy(). The free function is read first, because the procs can
3326 : // be part of the block.
3327 1755995 : void chashmap__destroy(chmap chm) {
3328 1755995 : if (chm) {
3329 1755995 : ccol_memmgmt_procs* procs;
3330 1755995 : if (chm->impl_type == IMPL_OPEN_ADDRESSING) {
3331 41622 : procs = chm->impl.oa->m_procs;
3332 41622 : oa_destroy(chm->impl.oa);
3333 : } else {
3334 1714373 : procs = chm->impl.sc->m_procs;
3335 1714373 : sc_destroy(chm->impl.sc);
3336 : }
3337 1755994 : if (procs) {
3338 73146 : ccol_free free_func = procs->free;
3339 73146 : free_func(chm);
3340 73146 : return;
3341 : }
3342 1682848 : ccol__default_mem_free(chm);
3343 : }
3344 : }
3345 :
3346 : // Destroys the map and calls val_dtor on every value right before its entry
3347 : // is freed, allocating nothing, for maps of owned pointers. The walks are
3348 : // duplicates of the backend teardowns on purpose, to keep the destructor's
3349 : // cost off the plain destroy.
3350 1703904 : void chashmap_destroy_with_dtor(chmap chm,
3351 : void (*val_dtor)(const cmap_pair* val_pair,
3352 : void* dtor_ctx),
3353 : void* dtor_ctx) {
3354 1703904 : if (!chm) return;
3355 1688265 : if (!val_dtor) {
3356 1 : chashmap__destroy(chm);
3357 1 : return;
3358 : }
3359 :
3360 1688264 : if (chm->impl_type == IMPL_OPEN_ADDRESSING) {
3361 2 : open_addr_map* map = chm->impl.oa;
3362 34 : for (size_t i = 0; i < map->capacity; i++) {
3363 32 : if (map->metadata[i] & SLOT_OCCUPIED) {
3364 15 : cmap_pair vp = {.ptr = &map->slots[i].val_data, .size = map->val_size};
3365 15 : val_dtor(&vp, dtor_ctx);
3366 : }
3367 : }
3368 : } else {
3369 1688262 : sep_chain_map* map = chm->impl.sc;
3370 8456848 : for (size_t i = 0; i < map->bucket_arr_size; i++) {
3371 8480691 : for (llist_node* tracker = map->bucket_arr[i]; tracker;
3372 1712105 : tracker = tracker->next) {
3373 1712105 : val_dtor(&tracker->val_pair_accessor, dtor_ctx);
3374 : }
3375 : }
3376 : }
3377 :
3378 1688264 : chashmap__destroy(chm);
3379 : }
3380 :
3381 : // The test hooks that read internal state, so the tests can assert on work
3382 : // and structure instead of time. test_helpers/chashmap.h declares them.
3383 : #ifdef RUNNING_UNIT_TESTS
3384 : // Gives the size of the bucket array or the slot array.
3385 1128371 : size_t chmap_get_bucket_arr_size(chmap chm) {
3386 1128371 : if (!chm) return 0;
3387 :
3388 1128371 : if (chm->impl_type == IMPL_OPEN_ADDRESSING) {
3389 1007976 : return chm->impl.oa->capacity;
3390 : } else {
3391 120395 : return chm->impl.sc->bucket_arr_size;
3392 : }
3393 : }
3394 :
3395 : // Gives the count at which the next growth starts.
3396 3006 : size_t chmap_get_elem_count_to_scale_up(chmap chm) {
3397 3006 : if (!chm) return 0;
3398 :
3399 3006 : if (chm->impl_type == IMPL_OPEN_ADDRESSING) {
3400 3000 : size_t cap = chm->impl.oa->capacity;
3401 3000 : return (cap / 10) * 7 + ((cap % 10) * 7) / 10;
3402 : } else {
3403 6 : return chm->impl.sc->elem_count_to_scale_up;
3404 : }
3405 : }
3406 :
3407 : // Gives the count at which the next shrink starts.
3408 6 : size_t chmap_get_elem_count_to_scale_down(chmap chm) {
3409 6 : if (!chm) return 0;
3410 :
3411 6 : if (chm->impl_type == IMPL_OPEN_ADDRESSING) {
3412 0 : return chm->impl.oa->capacity / 4;
3413 : } else {
3414 6 : return chm->impl.sc->elem_count_to_scale_down;
3415 : }
3416 : }
3417 :
3418 : // Computes the SipHash state of the key (k0, k1), as a map keeps it.
3419 2066 : void chashmap_sip_state_for_tests(uint64_t k0, uint64_t k1, uint64_t sip_v[4]) {
3420 2066 : chmap_sip_state_from_key(k0, k1, sip_v);
3421 2066 : }
3422 :
3423 : // Runs SipHash-1-3 from an explicit state, to compare with a reference.
3424 33536 : uint64_t chashmap_siphash13_for_tests(const uint64_t sip_v[4],
3425 : const void* key_ptr, size_t key_size) {
3426 33536 : return siphash13(sip_v, key_ptr, key_size);
3427 : }
3428 :
3429 : // Runs the keyed byte hash from an explicit state, to build colliding keys.
3430 585246 : size_t chashmap_byte_hash_for_tests(const uint64_t sip_v[4],
3431 : const void* key_ptr, size_t key_size) {
3432 585246 : return hash_bytes_keyed(sip_v, key_ptr, key_size);
3433 : }
3434 :
3435 : // Gives the secret a map hashes with: sip_v, int_seed, byte_seed. An
3436 : // open-addressing map reads no byte hash and gives 0 for those parts.
3437 5 : void chashmap_hash_secret_for_tests(chmap chm, uint64_t out[6]) {
3438 5 : memset(out, 0, 6 * sizeof(uint64_t));
3439 5 : if (!chm) return;
3440 5 : out[4] = g_chmap_hash_secret.int_seed;
3441 5 : if (chm->impl_type == IMPL_OPEN_ADDRESSING) {
3442 : return;
3443 : }
3444 4 : memcpy(out, g_chmap_hash_secret.sip_v, 4 * sizeof(uint64_t));
3445 4 : out[5] = g_chmap_hash_secret.byte_seed;
3446 : }
3447 :
3448 : // Gives the key words that the fallback derives when getrandom(2) can't
3449 : // answer.
3450 2 : void chashmap_fallback_hash_key_for_tests(uint64_t out[4]) {
3451 2 : chmap_fallback_hash_key(out);
3452 2 : }
3453 :
3454 : // Runs XXH64 with an explicit seed, to compare with the published vectors.
3455 1290241 : uint64_t chashmap_xxh64_for_tests(const void* key_ptr, size_t key_size,
3456 : uint64_t seed) {
3457 1290241 : return xxh64(key_ptr, key_size, seed);
3458 : }
3459 :
3460 : // Tells whether a map hashes in the keyed mode.
3461 872811 : bool chashmap_is_keyed_for_tests(chmap chm) {
3462 872811 : return chm && chm->hash_mode == CHMAP_HASH_KEYED;
3463 : }
3464 :
3465 : // Switches a map to keyed through the detection's own function; gives
3466 : // ccol_not_enough_memory, the map staying fast, when the rebuild fails.
3467 139 : ccol_retval chashmap_switch_to_keyed_for_tests(chmap chm) {
3468 139 : if (!chm) return ccol_invalid_args;
3469 139 : if (chm->hash_mode == CHMAP_HASH_KEYED) return ccol_success;
3470 139 : if (chm->impl_type == IMPL_SEPARATE_CHAINING) {
3471 130 : sc_switch_to_keyed(chm->impl.sc);
3472 130 : return ccol_success;
3473 : }
3474 9 : open_addr_map* map = chm->impl.oa;
3475 9 : return oa_rebuild(map, map->capacity, true);
3476 : }
3477 :
3478 : // Gives the probe_span of an open-addressing map, or 0.
3479 7 : size_t chashmap_oa_probe_span_for_tests(chmap chm) {
3480 7 : if (!chm || chm->impl_type != IMPL_OPEN_ADDRESSING) return 0;
3481 7 : return chm->impl.oa->probe_span;
3482 : }
3483 :
3484 : // Gives oa_insert_cap() of a capacity.
3485 8 : size_t chashmap_oa_insert_cap_for_tests(size_t capacity) {
3486 8 : return oa_insert_cap(capacity);
3487 : }
3488 :
3489 : // Gives oa_window_bound() of a window start and a capacity.
3490 27028 : uint32_t chashmap_oa_window_bound_for_tests(size_t start_count,
3491 : size_t capacity) {
3492 27028 : return oa_window_bound(start_count, capacity);
3493 : }
3494 :
3495 : // Gives sc_window_bound() of a window start and a bucket count.
3496 27027 : uint32_t chashmap_sc_window_bound_for_tests(size_t start_count,
3497 : size_t bucket_count) {
3498 27027 : sep_chain_map probe;
3499 27027 : memset(&probe, 0, sizeof(probe));
3500 27027 : probe.bucket_arr_size = bucket_count;
3501 27027 : sc_set_scaling_limits(&probe);
3502 27027 : return sc_window_bound(start_count, probe.elem_count_to_scale_up,
3503 : bucket_count);
3504 : }
3505 :
3506 : // Gives the bound of a map's current window.
3507 0 : uint32_t chashmap_window_bound_of_for_tests(chmap chm) {
3508 0 : return chm ? chm->window_bound : 0;
3509 : }
3510 :
3511 : // Gives the running sum of a map's current window.
3512 540 : uint32_t chashmap_insert_window_for_tests(chmap chm) {
3513 540 : return chm ? chm->insert_window : 0;
3514 : }
3515 :
3516 : // Gives the longest chain of a chaining map, or 0.
3517 9 : size_t chashmap_sc_longest_chain_for_tests(chmap chm) {
3518 9 : if (!chm || chm->impl_type != IMPL_SEPARATE_CHAINING) return 0;
3519 9 : sep_chain_map* map = chm->impl.sc;
3520 9 : size_t longest = 0;
3521 69705 : for (size_t i = 0; i < map->bucket_arr_size; i++) {
3522 69696 : size_t len = 0;
3523 121422 : for (llist_node* n = map->bucket_arr[i]; n; n = n->next) len++;
3524 69696 : if (len > longest) longest = len;
3525 : }
3526 : return longest;
3527 : }
3528 :
3529 : // Gives the hash a chaining map stored for a key, or 0.
3530 10 : size_t chashmap_sc_stored_hash_for_tests(chmap chm, const void* key_ptr,
3531 : size_t key_size) {
3532 10 : if (!chm || chm->impl_type != IMPL_SEPARATE_CHAINING) return 0;
3533 12 : for (dllist_ref_node* t = chm->impl.sc->all_elems.head; t; t = t->next) {
3534 12 : llist_node* n = dllistRefNodePtr2LlistNodePtr(t);
3535 12 : if (n->key_pair_accessor.size == key_size &&
3536 12 : memcmp(n->key_pair_accessor.ptr, key_ptr, key_size) == 0) {
3537 10 : return n->hash_val;
3538 : }
3539 : }
3540 : return 0;
3541 : }
3542 :
3543 : // Gives a key's home slot in an open-addressing map, or SIZE_MAX.
3544 15947 : size_t chashmap_oa_home_slot_for_tests(chmap chm, const void* key_ptr,
3545 : size_t key_size) {
3546 15947 : if (!chm || chm->impl_type != IMPL_OPEN_ADDRESSING) return SIZE_MAX;
3547 15946 : open_addr_map* map = chm->impl.oa;
3548 15946 : return hash_index_for(
3549 : hash_key_data(key_ptr, key_size, map->key_type, map->custom_hashing_proc,
3550 15946 : oa_keyed(map), g_chmap_hash_secret.int_seed),
3551 : map->capacity);
3552 : }
3553 :
3554 : // Checks that every occupied slot is reachable from its home through occupied
3555 : // slots within probe_span, and that exactly count slots are occupied. Gives
3556 : // true for a chaining map.
3557 17974 : bool chashmap_oa_check_invariants_for_tests(chmap chm) {
3558 17974 : if (!chm || chm->impl_type != IMPL_OPEN_ADDRESSING) return true;
3559 17974 : open_addr_map* map = chm->impl.oa;
3560 17974 : size_t mask = map->capacity - 1;
3561 17974 : size_t occupied = 0;
3562 4763510 : for (size_t j = 0; j < map->capacity; j++) {
3563 4745536 : if (!(map->metadata[j] & SLOT_OCCUPIED)) {
3564 2635530 : if (map->metadata[j] != 0) return false;
3565 2635530 : continue;
3566 : }
3567 2110006 : occupied++;
3568 4220012 : size_t home = hash_index_for(
3569 2110006 : hash_key_data(&map->slots[j].key_data, map->key_size, map->key_type,
3570 2110006 : map->custom_hashing_proc, oa_keyed(map),
3571 : g_chmap_hash_secret.int_seed),
3572 : map->capacity);
3573 9594532 : for (size_t k = home; k != j; k = (k + 1) & mask) {
3574 7484526 : if (!(map->metadata[k] & SLOT_OCCUPIED)) return false;
3575 : }
3576 2110006 : if (((j - home) & mask) >= map->probe_span) return false;
3577 : }
3578 35948 : return occupied == map->count && map->probe_span <= map->capacity &&
3579 17974 : map->probe_span >= oa_min_probe_span(map->capacity);
3580 : }
3581 : #endif
|