Debian Codegraph @

include/lib/verstable-2.2.1.h

raw
1 /*------------------------------------------------- VERSTABLE v2.2.1 ---------------------------------------------------
2
3 Verstable is a C99-compatible, open-addressing hash table using quadratic probing and the following additions:
4
5 * All keys that hash (i.e. "belong") to the same bucket (their "home bucket") are linked together by an 11-bit integer
6 specifying the quadratic displacement, relative to that bucket, of the next key in the chain.
7
8 * If a chain of keys exists for a given bucket, then it always begins at that bucket. To maintain this policy, a 1-bit
9 flag is used to mark whether the key occupying a bucket belongs there. When inserting a new key, if the bucket it
10 belongs to is occupied by a key that does not belong there, then the occupying key is evicted and the new key takes
11 the bucket.
12
13 * A 4-bit fragment of each key's hash code is also stored.
14
15 * The aforementioned metadata associated with each bucket (the 4-bit hash fragment, the 1-bit flag, and the 11-bit link
16 to the next key in the chain) are stored together in a uint16_t array rather than in the bucket alongside the key and
17 (optionally) the value.
18
19 One way to conceptualize this scheme is as a chained hash table in which overflowing keys are stored not in separate
20 memory allocations but in otherwise unused buckets. In this regard, it shares similarities with Malte Skarupke's Bytell
21 hash table (https://www.youtube.com/watch?v=M2fKMP47slQ) and traditional "coalesced hashing".
22
23 Advantages of this scheme include:
24
25 * Fast lookups impervious to load factor: If the table contains any key belonging to the lookup key's home bucket, then
26 that bucket contains the first in a traversable chain of all keys belonging to it. Hence, only the home bucket and
27 other buckets containing keys belonging to it are ever probed. Moreover, the stored hash fragments allow skipping most
28 non-matching keys in the chain without accessing the actual buckets array or calling the (potentially expensive) key
29 comparison function.
30
31 * Fast insertions: Insertions are faster than they are in other schemes that move keys around (e.g. Robin Hood) because
32 they only move, at most, one existing key.
33
34 * Fast, tombstone-free deletions: Deletions, which usually require tombstones in quadratic-probing hash tables, are
35 tombstone-free and only move, at most, one existing key.
36
37 * Fast iteration: The separate metadata array allows keys in sparsely populated tables to be found without incurring the
38 frequent cache misses that would result from traversing the buckets array.
39
40 Usage example:
41
42 +---------------------------------------------------------+----------------------------------------------------------+
43 | Using the generic macro API (C11 and later): | Using the prefixed functions API (C99 and later): |
44 +---------------------------------------------------------+----------------------------------------------------------+
45 | #include <stdio.h> | #include <stdio.h> |
46 | | |
47 | // Instantiating a set template. | // Instantiating a set template. |
48 | #define NAME int_set | #define NAME int_set |
49 | #define KEY_TY int | #define KEY_TY int |
50 | #include "verstable.h" | #define HASH_FN vt_hash_integer |
51 | | #define CMPR_FN vt_cmpr_integer |
52 | // Instantiating a map template. | #include "verstable.h" |
53 | #define NAME int_int_map | |
54 | #define KEY_TY int | // Instantiating a map template. |
55 | #define VAL_TY int | #define NAME int_int_map |
56 | #include "verstable.h" | #define KEY_TY int |
57 | | #define VAL_TY int |
58 | int main( void ) | #define HASH_FN vt_hash_integer |
59 | { | #define CMPR_FN vt_cmpr_integer |
60 | // Set. | #include "verstable.h" |
61 | | |
62 | int_set our_set; | int main( void ) |
63 | vt_init( &our_set ); | { |
64 | | // Set. |
65 | // Inserting keys. | |
66 | for( int i = 0; i < 10; ++i ) | int_set our_set; |
67 | { | int_set_init( &our_set ); |
68 | int_set_itr itr = vt_insert( &our_set, i ); | |
69 | if( vt_is_end( itr ) ) | // Inserting keys. |
70 | { | for( int i = 0; i < 10; ++i ) |
71 | // Out of memory, so abort. | { |
72 | vt_cleanup( &our_set ); | int_set_itr itr = |
73 | return 1; | int_set_insert( &our_set, i ); |
74 | } | if( int_set_is_end( itr ) ) |
75 | } | { |
76 | | // Out of memory, so abort. |
77 | // Erasing keys. | int_set_cleanup( &our_set ); |
78 | for( int i = 0; i < 10; i += 3 ) | return 1; |
79 | vt_erase( &our_set, i ); | } |
80 | | } |
81 | // Retrieving keys. | |
82 | for( int i = 0; i < 10; ++i ) | // Erasing keys. |
83 | { | for( int i = 0; i < 10; i += 3 ) |
84 | int_set_itr itr = vt_get( &our_set, i ); | int_set_erase( &our_set, i ); |
85 | if( !vt_is_end( itr ) ) | |
86 | printf( "%d ", itr.data->key ); | // Retrieving keys. |
87 | } | for( int i = 0; i < 10; ++i ) |
88 | // Printed: 1 2 4 5 7 8 | { |
89 | | int_set_itr itr = int_set_get( &our_set, i ); |
90 | // Iteration. | if( !int_set_is_end( itr ) ) |
91 | for( | printf( "%d ", itr.data->key ); |
92 | int_set_itr itr = vt_first( &our_set ); | } |
93 | !vt_is_end( itr ); | // Printed: 1 2 4 5 7 8 |
94 | itr = vt_next( itr ) | |
95 | ) | // Iteration. |
96 | printf( "%d ", itr.data->key ); | for( |
97 | // Printed: 2 4 7 1 5 8 | int_set_itr itr = |
98 | | int_set_first( &our_set ); |
99 | vt_cleanup( &our_set ); | !int_set_is_end( itr ); |
100 | | itr = int_set_next( itr ) |
101 | // Map. | ) |
102 | | printf( "%d ", itr.data->key ); |
103 | int_int_map our_map; | // Printed: 2 4 7 1 5 8 |
104 | vt_init( &our_map ); | |
105 | | int_set_cleanup( &our_set ); |
106 | // Inserting keys and values. | |
107 | for( int i = 0; i < 10; ++i ) | // Map. |
108 | { | |
109 | int_int_map_itr itr = | int_int_map our_map; |
110 | vt_insert( &our_map, i, i + 1 ); | int_int_map_init( &our_map ); |
111 | if( vt_is_end( itr ) ) | |
112 | { | // Inserting keys and values. |
113 | // Out of memory, so abort. | for( int i = 0; i < 10; ++i ) |
114 | vt_cleanup( &our_map ); | { |
115 | return 1; | int_int_map_itr itr = |
116 | } | int_int_map_insert( &our_map, i, i + 1 ); |
117 | } | if( int_int_map_is_end( itr ) ) |
118 | | { |
119 | // Erasing keys and values. | // Out of memory, so abort. |
120 | for( int i = 0; i < 10; i += 3 ) | int_int_map_cleanup( &our_map ); |
121 | vt_erase( &our_map, i ); | return 1; |
122 | | } |
123 | // Retrieving keys and values. | } |
124 | for( int i = 0; i < 10; ++i ) | |
125 | { | // Erasing keys and values. |
126 | int_int_map_itr itr = vt_get( &our_map, i ); | for( int i = 0; i < 10; i += 3 ) |
127 | if( !vt_is_end( itr ) ) | int_int_map_erase( &our_map, i ); |
128 | printf( | |
129 | "%d:%d ", | // Retrieving keys and values. |
130 | itr.data->key, | for( int i = 0; i < 10; ++i ) |
131 | itr.data->val | { |
132 | ); | int_int_map_itr itr = |
133 | } | int_int_map_get( &our_map, i ); |
134 | // Printed: 1:2 2:3 4:5 5:6 7:8 8:9 | if( !int_int_map_is_end( itr ) ) |
135 | | printf( |
136 | // Iteration. | "%d:%d ", |
137 | for( | itr.data->key, |
138 | int_int_map_itr itr = vt_first( &our_map ); | itr.data->val |
139 | !vt_is_end( itr ); | ); |
140 | itr = vt_next( itr ) | } |
141 | ) | // Printed: 1:2 2:3 4:5 5:6 7:8 8:9 |
142 | printf( | |
143 | "%d:%d ", | // Iteration. |
144 | itr.data->key, | for( |
145 | itr.data->val | int_int_map_itr itr = |
146 | ); | int_int_map_first( &our_map ); |
147 | // Printed: 2:3 4:5 7:8 1:2 5:6 8:9 | !int_int_map_is_end( itr ); |
148 | | itr = int_int_map_next( itr ) |
149 | vt_cleanup( &our_map ); | ) |
150 | } | printf( |
151 | | "%d:%d ", |
152 | | itr.data->key, |
153 | | itr.data->val |
154 | | ); |
155 | | // Printed: 2:3 4:5 7:8 1:2 5:6 8:9 |
156 | | |
157 | | int_int_map_cleanup( &our_map ); |
158 | | } |
159 | | |
160 +---------------------------------------------------------+----------------------------------------------------------+
161
162 API:
163
164 Instantiating a hash table template:
165
166 Create a new hash table type in the following manner:
167
168 #define NAME <your chosen type name>
169 #define KEY_TY <type>
170 #include "verstable.h"
171
172 The NAME macro specifies the name of hash table type that the library will declare, the prefix for the functions
173 associated with it, and the prefix for the associated iterator type.
174
175 The KEY_TY macro specifies the key type.
176
177 In C99, it is also always necessary to define HASH_FN and CMPR_FN (see below) before including the header.
178
179 The following macros may also be defined before including the header:
180
181 #define VAL_TY <type>
182
183 The type of the value associated with each key.
184 If this macro is defined, the hash table acts as a map associating keys with values.
185 Otherwise, it acts as a set containing only keys.
186
187 #define HASH_FN <function name>
188
189 The name of the existing function used to hash each key.
190 The function should have the signature uint64_t ( KEY_TY key ) and return a 64-bit hash code.
191 For best performance, the hash function should provide a high level of entropy across all bits.
192 There are two default hash functions: vt_hash_integer for all integer types up to 64 bits in size, and
193 vt_hash_string for NULL-terminated strings (i.e. char *).
194 When KEY_TY is one of such types and the compiler is in C11 mode or later, HASH_FN may be left undefined, in
195 which case the appropriate default function is inferred from KEY_TY.
196 Otherwise, HASH_FN must be defined.
197
198 #define CMPR_FN <function name>
199
200 The name of the existing function used to compare two keys.
201 The function should have the signature bool ( KEY_TY key_1, KEY_TY key_2 ) and return true if the two keys are
202 equal.
203 There are two default comparison functions: vt_cmpr_integer for all integer types up to 64 bits in size, and
204 vt_cmpr_string for NULL-terminated strings (i.e. char *).
205 As with the default hash functions, in C11 or later the appropriate default comparison function is inferred if
206 KEY_TY is one of such types and CMPR_FN is left undefined.
207 Otherwise, CMPR_FN must be defined.
208
209 #define MAX_LOAD <floating point value>
210
211 The floating-point load factor at which the hash table automatically doubles the size of its internal buckets
212 array.
213 The default is 0.9, i.e. 90%.
214
215 #define KEY_DTOR_FN <function name>
216
217 The name of the existing destructor function, with the signature void ( KEY_TY key ), called on a key when it is
218 erased from the table or replaced by a newly inserted key.
219 The API functions that may call the key destructor are NAME_insert, NAME_erase, NAME_erase_itr, NAME_clear,
220 and NAME_cleanup.
221
222 #define VAL_DTOR_FN <function name>
223
224 The name of the existing destructor function, with the signature void ( VAL_TY val ), called on a value when it
225 is erased from the table or replaced by a newly inserted value.
226 The API functions that may call the value destructor are NAME_insert, NAME_erase, NAME_erase_itr, NAME_clear,
227 and NAME_cleanup.
228
229 #define CTX_TY <type>
230
231 The type of the hash table type's ctx (context) member.
232 This member only exists if CTX_TY was defined.
233 It is intended to be used in conjunction with MALLOC_FN and FREE_FN (see below).
234
235 #define MALLOC_FN <function name>
236
237 The name of the existing function used to allocate memory.
238 If CTX_TY was defined, the signature should be void *( size_t size, CTX_TY *ctx ), where size is the number of
239 bytes to allocate and ctx points to the table's ctx member.
240 Otherwise, the signature should be void *( size_t size ).
241 The default wraps stdlib.h's malloc.
242
243 #define FREE_FN <function name>
244
245 The name of the existing function used to free memory.
246 If CTX_TY was defined, the signature should be void ( void *ptr, size_t size, CTX_TY *ctx ), where ptr points to
247 the memory to free, size is the number of bytes that were allocated, and ctx points to the table's ctx member.
248 Otherwise, the signature should be void ( void *ptr, size_t size ).
249 The default wraps stdlib.h's free.
250
251 #define HEADER_MODE
252 #define IMPLEMENTATION_MODE
253
254 By default, all hash table functions are defined as static inline functions, the intent being that a given hash
255 table template should be instantiated once per translation unit; for best performance, this is the recommended
256 way to use the library.
257 However, it is also possible to separate the struct definitions and function declarations from the function
258 definitions such that one implementation can be shared across all translation units (as in a traditional header
259 and source file pair).
260 In that case, instantiate a template wherever it is needed by defining HEADER_MODE, along with only NAME,
261 KEY_TY, and (optionally) VAL_TY, CTX_TY, and header guards, and including the library, e.g.:
262
263 #ifndef INT_INT_MAP_H
264 #define INT_INT_MAP_H
265 #define NAME int_int_map
266 #define KEY_TY int
267 #define VAL_TY int
268 #define HEADER_MODE
269 #include "verstable.h"
270 #endif
271
272 In one source file, define IMPLEMENTATION_MODE, along with NAME, KEY_TY, and any of the aforementioned optional
273 macros, and include the library, e.g.:
274
275 #define NAME int_int_map
276 #define KEY_TY int
277 #define VAL_TY int
278 #define HASH_FN vt_hash_integer // C99.
279 #define CMPR_FN vt_cmpr_integer // C99.
280 #define MAX_LOAD 0.8
281 #define IMPLEMENTATION_MODE
282 #include "verstable.h"
283
284 Including the library automatically undefines all the aforementioned macros after they have been used to instantiate
285 the template.
286
287 Functions:
288
289 The functions associated with a hash table type are all prefixed with the name the user supplied via the NAME macro.
290 In C11 and later, the generic "vt_"-prefixed macros may be used to automatically select the correct version of the
291 specified function based on the arguments.
292
293 void NAME_init( NAME *table )
294 void NAME_init( NAME *table, CTX_TY ctx )
295 // C11 generic macro: vt_init.
296
297 Initializes the table for use.
298 If CTX_TY was defined, ctx sets the table's ctx member.
299
300 bool NAME_init_clone( NAME *table, NAME *source )
301 bool NAME_init_clone( NAME *table, NAME *source, CTX_TY ctx )
302 // C11 generic macro: vt_init_clone.
303
304 Initializes the table as a shallow copy of the specified source table.
305 If CTX_TY was defined, ctx sets the table's ctx member.
306 Returns false in the case of memory allocation failure.
307
308 size_t NAME_size( NAME *table ) // C11 generic macro: vt_size.
309
310 Returns the number of keys currently in the table.
311
312 size_t NAME_bucket_count( NAME *table ) // C11 generic macro: vt_bucket_count.
313
314 Returns the table's current bucket count.
315
316 NAME_itr NAME_insert( NAME *table, KEY_TY key )
317 NAME_itr NAME_insert( NAME *table, KEY_TY key, VAL_TY val )
318 // C11 generic macro: vt_insert.
319
320 Inserts the specified key (and value, if VAL_TY was defined) into the hash table.
321 If the same key already exists, then the new key (and value) replaces the existing key (and value).
322 Returns an iterator to the new key, or an end iterator in the case of memory allocation failure.
323
324 NAME_itr NAME_get_or_insert( NAME *table, KEY_TY key )
325 NAME_itr NAME_get_or_insert( NAME *table, KEY_TY key, VAL_TY val )
326 // C11 generic macro: vt_get_or_insert.
327
328 Inserts the specified key (and value, if VAL_TY was defined) if it does not already exist in the table.
329 Returns an iterator to the new key if it was inserted, or an iterator to the existing key, or an end iterator if
330 the key did not exist but the new key could not be inserted because of memory allocation failure.
331 Determine whether the key was inserted by comparing the table's size before and after the call.
332
333 NAME_itr NAME_get( NAME *table, KEY_TY key ) // C11 generic macro: vt_get.
334
335 Returns a iterator to the specified key, or an end iterator if no such key exists.
336
337 bool NAME_erase( NAME *table, KEY_TY key ) // C11 generic macro: vt_erase.
338
339 Erases the specified key (and associated value, if VAL_TY was defined), if it exists.
340 Returns true if a key was erased.
341
342 NAME_itr NAME_erase_itr( NAME *table, NAME_itr itr ) // C11 generic macro: vt_erase_itr.
343
344 Erases the key (and associated value, if VAL_TY was defined) pointed to by the specified iterator.
345 Returns an iterator to the next key in the table, or an end iterator if the erased key was the last one.
346
347 bool NAME_reserve( NAME *table, size_t size ) // C11 generic macro: vt_reserve.
348
349 Ensures that the bucket count is large enough to support the specified key count (i.e. size) without rehashing.
350 Returns false if unsuccessful due to memory allocation failure.
351
352 bool NAME_shrink( NAME *table ) // C11 generic macro: vt_shrink.
353
354 Shrinks the bucket count to best accommodate the current size.
355 Returns false if unsuccessful due to memory allocation failure.
356
357 NAME_itr NAME_first( NAME *table ) // C11 generic macro: vt_first.
358
359 Returns an iterator to the first key in the table, or an end iterator if the table is empty.
360
361 bool NAME_is_end( NAME_itr itr ) // C11 generic macro: vt_is_end.
362
363 Returns true if the iterator is an end iterator.
364
365 NAME_itr NAME_next( NAME_itr itr ) // C11 generic macro: vt_next.
366
367 Returns an iterator to the key after the one pointed to by the specified iterator, or an end iterator if the
368 specified iterator points to the last key in the table.
369
370 void NAME_clear( NAME *table ) // C11 generic macro: vt_clear.
371
372 Erases all keys (and values, if VAL_TY was defined) in the table.
373
374 void NAME_cleanup( NAME *table ) // C11 generic macro: vt_cleanup.
375
376 Erases all keys (and values, if VAL_TY was defined) in the table, frees all memory associated with it, and
377 initializes it for reuse.
378
379 Iterators:
380
381 Access the key (and value, if VAL_TY was defined) that an iterator points to using the NAME_itr struct's data
382 member:
383
384 itr.data->key
385 itr.data->val
386
387 Functions that may insert new keys (NAME_insert and NAME_get_or_insert), erase keys (NAME_erase and NAME_erase_itr),
388 or reallocate the internal bucket array (NAME_reserve and NAME_shrink) invalidate all existing iterators.
389 To delete keys during iteration and resume iterating, use the return value of NAME_erase_itr.
390
391 Version history:
392
393 06/05/2025 2.2.1: Fixed incorrect signature of NAME_is_end in documentation.
394 18/04/2025 2.2.0: Added const qualifier to the table parameter of NAME_size, NAME_bucket_count, NAME_get, and
395 NAME_first and to the source parameter of NAME_init_clone.
396 Added default support for const char * strings.
397 Added support for -Wextra.
398 Replaced FNV-1a with Wyhash as the default string hash function.
399 18/06/2024 2.1.1: Fixed a bug affecting iteration on big-endian platforms under MSVC.
400 27/05/2024 2.1.0: Replaced the Murmur3 mixer with the fast-hash mixer as the default integer hash function.
401 Fixed a bug that could theoretically cause a crash on rehash (triggerable in testing using
402 NAME_shrink with a maximum load factor significantly higher than 1.0).
403 06/02/2024 2.0.0: Improved custom allocator support by introducing the CTX_TY option and allowing user-supplied free
404 functions to receive the allocation size.
405 Improved documentation.
406 Introduced various optimizations, including storing the buckets-array size mask instead of the
407 bucket count, eliminating empty-table checks, combining the buckets memory and metadata memory into
408 one allocation, and adding branch prediction macros.
409 Fixed a bug that caused a key to be used after destruction during erasure.
410 12/12/2023 1.0.0: Initial release.
411
412 License (MIT):
413
414 Copyright (c) 2023-2025 Jackson L. Allan
415
416 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
417 documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
418 rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
419 persons to whom the Software is furnished to do so, subject to the following conditions:
420
421 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
422 Software.
423
424 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
425 WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
426 COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
427 OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
428
429 */
430
431 /*--------------------------------------------------------------------------------------------------------------------*/
432 /* Common header section */
433 /*--------------------------------------------------------------------------------------------------------------------*/
434
435 #ifndef VERSTABLE_H
436 #define VERSTABLE_H
437
438 #include <limits.h>
439 #include <stddef.h>
440 #include <stdint.h>
441 #include <stdlib.h>
442 #include <stdbool.h>
443 #include <string.h>
444
445 // Two-way concatenation macro.
446 #define VT_CAT_( a, b ) a##b
447 #define VT_CAT( a, b ) VT_CAT_( a, b )
448
449 // Branch optimization macros.
450 #ifdef __GNUC__
451 #define VT_LIKELY( expression ) __builtin_expect( (bool)( expression ), true )
452 #define VT_UNLIKELY( expression ) __builtin_expect( (bool)( expression ), false )
453 #else
454 #define VT_LIKELY( expression ) ( expression )
455 #define VT_UNLIKELY( expression ) ( expression )
456 #endif
457
458 // Masks for manipulating and extracting data from a bucket's uint16_t metadatum.
459 #define VT_EMPTY 0x0000
460 #define VT_HASH_FRAG_MASK 0xF000 // 0b1111000000000000.
461 #define VT_IN_HOME_BUCKET_MASK 0x0800 // 0b0000100000000000.
462 #define VT_DISPLACEMENT_MASK 0x07FF // 0b0000011111111111, also denotes the displacement limit. Set to VT_LOAD to 1.0
463 // to test proper handling of encroachment on the displacement limit during
464 // inserts.
465
466 // Extracts a hash fragment from a uint64_t hash code.
467 // We take the highest four bits so that keys that map (via modulo) to the same bucket have distinct hash fragments.
468 static inline uint16_t vt_hashfrag( uint64_t hash )
469 {
470 return ( hash >> 48 ) & VT_HASH_FRAG_MASK;
471 }
472
473 // Standard quadratic probing formula that guarantees that all buckets are visited when the bucket count is a power of
474 // two (at least in theory, because the displacement limit could terminate the search early when the bucket count is
475 // high).
476 static inline size_t vt_quadratic( uint16_t displacement )
477 {
478 return ( (size_t)displacement * displacement + displacement ) / 2;
479 }
480
481 #define VT_MIN_NONZERO_BUCKET_COUNT 8 // Must be a power of two.
482
483 // Function to find the left-most non-zero uint16_t in a uint64_t.
484 // This function is used when we scan four buckets at a time while iterating and relies on compiler intrinsics wherever
485 // possible.
486
487 #if defined( __GNUC__ ) && ULLONG_MAX == 0xFFFFFFFFFFFFFFFF
488
489 static inline int vt_first_nonzero_uint16( uint64_t val )
490 {
491 const uint16_t endian_checker = 0x0001;
492 if( *(const char *)&endian_checker ) // Little-endian (the compiler will optimize away the check at -O1 and above).
493 return __builtin_ctzll( val ) / 16;
494
495 return __builtin_clzll( val ) / 16;
496 }
497
498 #elif defined( _MSC_VER ) && ( defined( _M_X64 ) || defined( _M_ARM64 ) )
499
500 #include <intrin.h>
501 #pragma intrinsic(_BitScanForward64)
502 #pragma intrinsic(_BitScanReverse64)
503
504 static inline int vt_first_nonzero_uint16( uint64_t val )
505 {
506 unsigned long result;
507
508 const uint16_t endian_checker = 0x0001;
509 if( *(const char *)&endian_checker )
510 _BitScanForward64( &result, val );
511 else
512 {
513 _BitScanReverse64( &result, val );
514 result = 63 - result;
515 }
516
517 return result / 16;
518 }
519
520 #else
521
522 static inline int vt_first_nonzero_uint16( uint64_t val )
523 {
524 int result = 0;
525
526 uint32_t half;
527 memcpy( &half, &val, sizeof( uint32_t ) );
528 if( !half )
529 result += 2;
530
531 uint16_t quarter;
532 memcpy( &quarter, (char *)&val + result * sizeof( uint16_t ), sizeof( uint16_t ) );
533 if( !quarter )
534 result += 1;
535
536 return result;
537 }
538
539 #endif
540
541 // When the bucket count is zero, setting the metadata pointer to point to a VT_EMPTY placeholder, rather than NULL,
542 // allows us to avoid checking for a zero bucket count during insertion and lookup.
543 static const uint16_t vt_empty_placeholder_metadatum = VT_EMPTY;
544
545 // Default hash and comparison functions.
546
547 // Fast-hash, as described by https://jonkagstrom.com/bit-mixer-construction and
548 // https://code.google.com/archive/p/fast-hash.
549 // In testing, this hash function provided slightly better performance than the Murmur3 mixer.
550 static inline uint64_t vt_hash_integer( uint64_t key )
551 {
552 key ^= key >> 23;
553 key *= 0x2127599bf4325c37ull;
554 key ^= key >> 47;
555 return key;
556 }
557
558 // For hashing strings, we use the public-domain Wyhash
559 // (https://github.com/wangyi-fudan/wyhash) with the following modifications:
560 // * We use a fixed seed and secret (the defaults suggested in the Wyhash repository).
561 // * We do not handle endianness, so the result will differ depending on the platform.
562 // * We omit the code optimized for 32-bit platforms.
563
564 static inline void vt_wymum( uint64_t *a, uint64_t *b )
565 {
566 #if defined( __SIZEOF_INT128__ )
567 __uint128_t r = *a;
568 r *= *b;
569 *a = (uint64_t)r;
570 *b = (uint64_t)( r >> 64 );
571 #elif defined( _MSC_VER ) && defined( _M_X64 )
572 *a = _umul128( *a, *b, b );
573 #else
574 uint64_t ha = *a >> 32;
575 uint64_t hb = *b >> 32;
576 uint64_t la = (uint32_t)*a;
577 uint64_t lb = (uint32_t)*b;
578 uint64_t rh = ha * hb;
579 uint64_t rm0 = ha * lb;
580 uint64_t rm1 = hb * la;
581 uint64_t rl = la * lb;
582 uint64_t t = rl + ( rm0 << 32 );
583 uint64_t c = t < rl;
584 uint64_t lo = t + ( rm1 << 32 );
585 c += lo < t;
586 uint64_t hi = rh + ( rm0 >> 32 ) + ( rm1 >> 32 ) + c;
587 *a = lo;
588 *b = hi;
589 #endif
590 }
591
592 static inline uint64_t vt_wymix( uint64_t a, uint64_t b )
593 {
594 vt_wymum( &a, &b );
595 return a ^ b;
596 }
597
598 static inline uint64_t vt_wyr8( const unsigned char *p )
599 {
600 uint64_t v;
601 memcpy( &v, p, 8 );
602 return v;
603 }
604
605 static inline uint64_t vt_wyr4( const unsigned char *p )
606 {
607 uint32_t v;
608 memcpy( &v, p, 4 );
609 return v;
610 }
611
612 static inline uint64_t vt_wyr3( const unsigned char *p, size_t k )
613 {
614 return ( ( (uint64_t)p[ 0 ] ) << 16 ) | ( ( (uint64_t)p[ k >> 1 ] ) << 8 ) | p[ k - 1 ];
615 }
616
617 static inline size_t vt_wyhash( const void *key, size_t len )
618 {
619 const unsigned char *p = (const unsigned char *)key;
620 uint64_t seed = 0xca813bf4c7abf0a9ull;
621 uint64_t a;
622 uint64_t b;
623 if( VT_LIKELY( len <= 16 ) )
624 {
625 if( VT_LIKELY( len >= 4 ) )
626 {
627 a = ( vt_wyr4( p ) << 32 ) | vt_wyr4( p + ( ( len >> 3 ) << 2 ) );
628 b = ( vt_wyr4( p + len - 4 ) << 32 ) | vt_wyr4( p + len - 4 - ( ( len >> 3 ) << 2 ) );
629 }
630 else if( VT_LIKELY( len > 0 ) )
631 {
632 a = vt_wyr3( p, len );
633 b = 0;
634 }
635 else
636 {
637 a = 0;
638 b = 0;
639 }
640 }
641 else
642 {
643 size_t i = len;
644 if( VT_UNLIKELY( i >= 48 ) )
645 {
646 uint64_t see1 = seed;
647 uint64_t see2 = seed;
648 do{
649 seed = vt_wymix( vt_wyr8( p ) ^ 0x8bb84b93962eacc9ull, vt_wyr8( p + 8 ) ^ seed );
650 see1 = vt_wymix( vt_wyr8( p + 16 ) ^ 0x4b33a62ed433d4a3ull, vt_wyr8( p + 24 ) ^ see1 );
651 see2 = vt_wymix( vt_wyr8( p + 32 ) ^ 0x4d5a2da51de1aa47ull, vt_wyr8( p + 40 ) ^ see2 );
652 p += 48;
653 i -= 48;
654 }
655 while( VT_LIKELY( i >= 48 ) );
656 seed ^= see1 ^ see2;
657 }
658
659 while( VT_UNLIKELY( i > 16 ) )
660 {
661 seed = vt_wymix( vt_wyr8( p ) ^ 0x8bb84b93962eacc9ull, vt_wyr8( p + 8 ) ^ seed );
662 i -= 16;
663 p += 16;
664 }
665
666 a = vt_wyr8( p + i - 16 );
667 b = vt_wyr8( p + i - 8 );
668 }
669
670 a ^= 0x8bb84b93962eacc9ull;
671 b ^= seed;
672 vt_wymum( &a, &b );
673 return (size_t)vt_wymix( a ^ 0x2d358dccaa6c78a5ull ^ len, b ^ 0x8bb84b93962eacc9ull );
674 }
675
676 static inline uint64_t vt_hash_string( const char *key )
677 {
678 return vt_wyhash( key, strlen( key ) );
679 }
680
681 static inline bool vt_cmpr_integer( uint64_t key_1, uint64_t key_2 )
682 {
683 return key_1 == key_2;
684 }
685
686 static inline bool vt_cmpr_string( const char *key_1, const char *key_2 )
687 {
688 return strcmp( key_1, key_2 ) == 0;
689 }
690
691 // Default allocation and free functions.
692
693 static inline void *vt_malloc( size_t size )
694 {
695 return malloc( size );
696 }
697
698 static inline void vt_free( void *ptr, size_t size )
699 {
700 (void)size;
701 free( ptr );
702 }
703
704 static inline void *vt_malloc_with_ctx( size_t size, void *ctx )
705 {
706 (void)ctx;
707 return malloc( size );
708 }
709
710 static inline void vt_free_with_ctx( void *ptr, size_t size, void *ctx )
711 {
712 (void)size;
713 (void)ctx;
714 free( ptr );
715 }
716
717 // The rest of the common header section pertains to the C11 generic macro API.
718 // This interface is based on the extendible-_Generic mechanism documented in detail at
719 // https://github.com/JacksonAllan/CC/blob/main/articles/Better_C_Generics_Part_1_The_Extendible_Generic.md.
720 // In summary, instantiating a template also defines wrappers for the template's types and functions with names in the
721 // pattern of vt_table_NNNN and vt_init_NNNN, where NNNN is an automatically generated integer unique to the template
722 // instance in the current translation unit.
723 // These wrappers plug into _Generic-based API macros, which use preprocessor magic to automatically generate _Generic
724 // slots for every existing template instance.
725 #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined( VT_NO_C11_GENERIC_API )
726
727 // Octal counter that supports up to 511 hash table templates.
728 #define VT_TEMPLATE_COUNT_D1 0 // Digit 1, i.e. least significant digit.
729 #define VT_TEMPLATE_COUNT_D2 0
730 #define VT_TEMPLATE_COUNT_D3 0
731
732 // Four-way concatenation macro.
733 #define VT_CAT_4_( a, b, c, d ) a##b##c##d
734 #define VT_CAT_4( a, b, c, d ) VT_CAT_4_( a, b, c, d )
735
736 // Provides the current value of the counter as a three-digit octal number preceded by 0.
737 #define VT_TEMPLATE_COUNT VT_CAT_4( 0, VT_TEMPLATE_COUNT_D3, VT_TEMPLATE_COUNT_D2, VT_TEMPLATE_COUNT_D1 )
738
739 // _Generic-slot generation macros.
740
741 #define VT_GENERIC_SLOT( ty, fn, n ) , VT_CAT( ty, n ): VT_CAT( fn, n )
742 #define VT_R1_0( ty, fn, d3, d2 )
743 #define VT_R1_1( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 0 ) )
744 #define VT_R1_2( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 1 ) ) VT_R1_1( ty, fn, d3, d2 )
745 #define VT_R1_3( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 2 ) ) VT_R1_2( ty, fn, d3, d2 )
746 #define VT_R1_4( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 3 ) ) VT_R1_3( ty, fn, d3, d2 )
747 #define VT_R1_5( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 4 ) ) VT_R1_4( ty, fn, d3, d2 )
748 #define VT_R1_6( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 5 ) ) VT_R1_5( ty, fn, d3, d2 )
749 #define VT_R1_7( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 6 ) ) VT_R1_6( ty, fn, d3, d2 )
750 #define VT_R1_8( ty, fn, d3, d2 ) VT_GENERIC_SLOT( ty, fn, VT_CAT_4( 0, d3, d2, 7 ) ) VT_R1_7( ty, fn, d3, d2 )
751 #define VT_R2_0( ty, fn, d3 )
752 #define VT_R2_1( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 0 )
753 #define VT_R2_2( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 1 ) VT_R2_1( ty, fn, d3 )
754 #define VT_R2_3( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 2 ) VT_R2_2( ty, fn, d3 )
755 #define VT_R2_4( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 3 ) VT_R2_3( ty, fn, d3 )
756 #define VT_R2_5( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 4 ) VT_R2_4( ty, fn, d3 )
757 #define VT_R2_6( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 5 ) VT_R2_5( ty, fn, d3 )
758 #define VT_R2_7( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 6 ) VT_R2_6( ty, fn, d3 )
759 #define VT_R2_8( ty, fn, d3 ) VT_R1_8( ty, fn, d3, 7 ) VT_R2_7( ty, fn, d3 )
760 #define VT_R3_0( ty, fn )
761 #define VT_R3_1( ty, fn ) VT_R2_8( ty, fn, 0 )
762 #define VT_R3_2( ty, fn ) VT_R2_8( ty, fn, 1 ) VT_R3_1( ty, fn )
763 #define VT_R3_3( ty, fn ) VT_R2_8( ty, fn, 2 ) VT_R3_2( ty, fn )
764 #define VT_R3_4( ty, fn ) VT_R2_8( ty, fn, 3 ) VT_R3_3( ty, fn )
765 #define VT_R3_5( ty, fn ) VT_R2_8( ty, fn, 4 ) VT_R3_4( ty, fn )
766 #define VT_R3_6( ty, fn ) VT_R2_8( ty, fn, 5 ) VT_R3_5( ty, fn )
767 #define VT_R3_7( ty, fn ) VT_R2_8( ty, fn, 6 ) VT_R3_6( ty, fn )
768
769 #define VT_GENERIC_SLOTS( ty, fn ) \
770 VT_CAT( VT_R1_, VT_TEMPLATE_COUNT_D1 )( ty, fn, VT_TEMPLATE_COUNT_D3, VT_TEMPLATE_COUNT_D2 ) \
771 VT_CAT( VT_R2_, VT_TEMPLATE_COUNT_D2 )( ty, fn, VT_TEMPLATE_COUNT_D3 ) \
772 VT_CAT( VT_R3_, VT_TEMPLATE_COUNT_D3 )( ty, fn ) \
773
774 // Actual generic API macros.
775
776 // vt_init must be handled as a special case because it could take one or two arguments, depending on whether CTX_TY
777 // was defined.
778 #define VT_ARG_3( _1, _2, _3, ... ) _3
779 #define vt_init( ... ) VT_ARG_3( __VA_ARGS__, vt_init_with_ctx, vt_init_without_ctx, )( __VA_ARGS__ )
780 #define vt_init_without_ctx( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_init_ ) )( table )
781 #define vt_init_with_ctx( table, ... ) _Generic( *( table ) \
782 VT_GENERIC_SLOTS( vt_table_, vt_init_ ) \
783 )( table, __VA_ARGS__ ) \
784
785 #define vt_init_clone( table, ... ) _Generic( *( table ) \
786 VT_GENERIC_SLOTS( vt_table_, vt_init_clone_ ) \
787 )( table, __VA_ARGS__ ) \
788
789 #define vt_size( table )_Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_size_ ) )( table )
790
791 #define vt_bucket_count( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_bucket_count_ ) )( table )
792
793 #define vt_is_end( itr ) _Generic( itr VT_GENERIC_SLOTS( vt_table_itr_, vt_is_end_ ) )( itr )
794
795 #define vt_insert( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_insert_ ) )( table, __VA_ARGS__ )
796
797 #define vt_get_or_insert( table, ... ) _Generic( *( table ) \
798 VT_GENERIC_SLOTS( vt_table_, vt_get_or_insert_ ) \
799 )( table, __VA_ARGS__ ) \
800
801 #define vt_get( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_get_ ) )( table, __VA_ARGS__ )
802
803 #define vt_erase( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_erase_ ) )( table, __VA_ARGS__ )
804
805 #define vt_next( itr ) _Generic( itr VT_GENERIC_SLOTS( vt_table_itr_, vt_next_ ) )( itr )
806
807 #define vt_erase_itr( table, ... ) _Generic( *( table ) \
808 VT_GENERIC_SLOTS( vt_table_, vt_erase_itr_ ) \
809 )( table, __VA_ARGS__ ) \
810
811 #define vt_reserve( table, ... ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_reserve_ ) )( table, __VA_ARGS__ )
812
813 #define vt_shrink( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_shrink_ ) )( table )
814
815 #define vt_first( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_first_ ) )( table )
816
817 #define vt_clear( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_clear_ ) )( table )
818
819 #define vt_cleanup( table ) _Generic( *( table ) VT_GENERIC_SLOTS( vt_table_, vt_cleanup_ ) )( table )
820
821 #endif
822
823 #endif
824
825 /*--------------------------------------------------------------------------------------------------------------------*/
826 /* Prefixed structs */
827 /*--------------------------------------------------------------------------------------------------------------------*/
828
829 #ifndef IMPLEMENTATION_MODE
830
831 typedef struct
832 {
833 KEY_TY key;
834 #ifdef VAL_TY
835 VAL_TY val;
836 #endif
837 } VT_CAT( NAME, _bucket );
838
839 typedef struct
840 {
841 VT_CAT( NAME, _bucket ) *data;
842 uint16_t *metadatum;
843 uint16_t *metadata_end; // Iterators carry an internal end pointer so that NAME_is_end does not need the table to be
844 // passed in as an argument.
845 // This also allows for the zero-bucket-count check to occur once in NAME_first, rather than
846 // repeatedly in NAME_is_end.
847 size_t home_bucket; // SIZE_MAX if home bucket is unknown.
848 } VT_CAT( NAME, _itr );
849
850 typedef struct
851 {
852 size_t key_count;
853 size_t buckets_mask; // Rather than storing the bucket count directly, we store the bit mask used to reduce a hash
854 // code or displacement-derived bucket index to the buckets array, i.e. the bucket count minus
855 // one.
856 // Consequently, a zero bucket count (i.e. when .metadata points to the placeholder) constitutes
857 // a special case, represented by all bits unset (i.e. zero).
858 VT_CAT( NAME, _bucket ) *buckets;
859 uint16_t *metadata; // As described above, each metadatum consists of a 4-bit hash-code fragment (X), a 1-bit flag
860 // indicating whether the key in this bucket begins a chain associated with the bucket (Y), and
861 // an 11-bit value indicating the quadratic displacement of the next key in the chain (Z):
862 // XXXXYZZZZZZZZZZZ.
863 #ifdef CTX_TY
864 CTX_TY ctx;
865 #endif
866 } NAME;
867
868 #endif
869
870 /*--------------------------------------------------------------------------------------------------------------------*/
871 /* Function prototypes */
872 /*--------------------------------------------------------------------------------------------------------------------*/
873
874 #if defined( HEADER_MODE ) || defined( IMPLEMENTATION_MODE )
875 #define VT_API_FN_QUALIFIERS
876 #else
877 #define VT_API_FN_QUALIFIERS static inline
878 #endif
879
880 #ifndef IMPLEMENTATION_MODE
881
882 VT_API_FN_QUALIFIERS void VT_CAT( NAME, _init )(
883 NAME *
884 #ifdef CTX_TY
885 , CTX_TY
886 #endif
887 );
888
889 VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _init_clone )(
890 NAME *,
891 const NAME *
892 #ifdef CTX_TY
893 , CTX_TY
894 #endif
895 );
896
897 VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _size )( const NAME * );
898
899 VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _bucket_count )( const NAME * );
900
901 VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _is_end )( VT_CAT( NAME, _itr ) );
902
903 VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert )(
904 NAME *,
905 KEY_TY
906 #ifdef VAL_TY
907 , VAL_TY
908 #endif
909 );
910
911 VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get_or_insert )(
912 NAME *,
913 KEY_TY
914 #ifdef VAL_TY
915 , VAL_TY
916 #endif
917 );
918
919 VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get )(
920 const NAME *table,
921 KEY_TY key
922 );
923
924 VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase )( NAME *, KEY_TY );
925
926 VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _next )( VT_CAT( NAME, _itr ) );
927
928 VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _reserve )( NAME *, size_t );
929
930 VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _shrink )( NAME * );
931
932 VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _first )( const NAME * );
933
934 VT_API_FN_QUALIFIERS void VT_CAT( NAME, _clear )( NAME * );
935
936 VT_API_FN_QUALIFIERS void VT_CAT( NAME, _cleanup )( NAME * );
937
938 // Not an API function, but must be prototyped anyway because it is called by the inline NAME_erase_itr below.
939 VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase_itr_raw ) ( NAME *, VT_CAT( NAME, _itr ) );
940
941 // Erases the key pointed to by itr and returns an iterator to the next key in the table.
942 // This function must be inlined to ensure that the compiler optimizes away the NAME_fast_forward call if the returned
943 // iterator is discarded.
944 #ifdef __GNUC__
945 static inline __attribute__((always_inline))
946 #elif defined( _MSC_VER )
947 static __forceinline
948 #else
949 static inline
950 #endif
951 VT_CAT( NAME, _itr ) VT_CAT( NAME, _erase_itr )( NAME *table, VT_CAT( NAME, _itr ) itr )
952 {
953 if( VT_CAT( NAME, _erase_itr_raw )( table, itr ) )
954 return VT_CAT( NAME, _next )( itr );
955
956 return itr;
957 }
958
959 #endif
960
961 /*--------------------------------------------------------------------------------------------------------------------*/
962 /* Function implementations */
963 /*--------------------------------------------------------------------------------------------------------------------*/
964
965 #ifndef HEADER_MODE
966
967 // Default settings.
968
969 #ifndef MAX_LOAD
970 #define MAX_LOAD 0.9
971 #endif
972
973 #ifndef MALLOC_FN
974 #ifdef CTX_TY
975 #define MALLOC_FN vt_malloc_with_ctx
976 #else
977 #define MALLOC_FN vt_malloc
978 #endif
979 #endif
980
981 #ifndef FREE_FN
982 #ifdef CTX_TY
983 #define FREE_FN vt_free_with_ctx
984 #else
985 #define FREE_FN vt_free
986 #endif
987 #endif
988
989 #ifndef HASH_FN
990 #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
991 #ifdef _MSC_VER // In MSVC, the compound literal in the _Generic triggers a warning about unused local variables at /W4.
992 #define HASH_FN \
993 _Pragma( "warning( push )" ) \
994 _Pragma( "warning( disable: 4189 )" ) \
995 _Generic( ( KEY_TY ){ 0 }, char *: vt_hash_string, const char*: vt_hash_string, default: vt_hash_integer ) \
996 _Pragma( "warning( pop )" )
997 #else
998 #define HASH_FN _Generic( ( KEY_TY ){ 0 }, \
999 char *: vt_hash_string, \
1000 const char*: vt_hash_string, \
1001 default: vt_hash_integer \
1002 )
1003 #endif
1004 #else
1005 #error Hash function inference is only available in C11 and later. In C99, you need to define HASH_FN manually to \
1006 vt_hash_integer, vt_hash_string, or your own custom function with the signature uint64_t ( KEY_TY ).
1007 #endif
1008 #endif
1009
1010 #ifndef CMPR_FN
1011 #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
1012 #ifdef _MSC_VER
1013 #define CMPR_FN \
1014 _Pragma( "warning( push )" ) \
1015 _Pragma( "warning( disable: 4189 )" ) \
1016 _Generic( ( KEY_TY ){ 0 }, char *: vt_cmpr_string, const char*: vt_cmpr_string, default: vt_cmpr_integer ) \
1017 _Pragma( "warning( pop )" )
1018 #else
1019 #define CMPR_FN _Generic( ( KEY_TY ){ 0 }, \
1020 char *: vt_cmpr_string, \
1021 const char*: vt_cmpr_string, \
1022 default: vt_cmpr_integer \
1023 )
1024 #endif
1025 #else
1026 #error Comparison function inference is only available in C11 and later. In C99, you need to define CMPR_FN manually \
1027 to vt_cmpr_integer, vt_cmpr_string, or your own custom function with the signature bool ( KEY_TY, KEY_TY ).
1028 #endif
1029 #endif
1030
1031 VT_API_FN_QUALIFIERS void VT_CAT( NAME, _init )(
1032 NAME *table
1033 #ifdef CTX_TY
1034 , CTX_TY ctx
1035 #endif
1036 )
1037 {
1038 table->key_count = 0;
1039 table->buckets_mask = 0x0000000000000000ull;
1040 table->buckets = NULL;
1041 table->metadata = (uint16_t *)&vt_empty_placeholder_metadatum;
1042 #ifdef CTX_TY
1043 table->ctx = ctx;
1044 #endif
1045 }
1046
1047 // For efficiency, especially in the case of a small table, the buckets array and metadata share the same dynamic memory
1048 // allocation:
1049 // +-----------------------------+-----+----------------+--------+
1050 // | Buckets | Pad | Metadata | Excess |
1051 // +-----------------------------+-----+----------------+--------+
1052 // Any allocated metadata array requires four excess elements to ensure that iteration functions, which read four
1053 // metadata at a time, never read beyond the end of it.
1054 // This function returns the offset of the beginning of the metadata, i.e. the size of the buckets array plus the
1055 // (usually zero) padding.
1056 // It assumes that the bucket count is not zero.
1057 static inline size_t VT_CAT( NAME, _metadata_offset )( NAME *table )
1058 {
1059 // Use sizeof, rather than alignof, for C99 compatibility.
1060 return ( ( ( table->buckets_mask + 1 ) * sizeof( VT_CAT( NAME, _bucket ) ) + sizeof( uint16_t ) - 1 ) /
1061 sizeof( uint16_t ) ) * sizeof( uint16_t );
1062 }
1063
1064 // Returns the total allocation size, including the buckets array, padding, metadata, and excess metadata.
1065 // As above, this function assumes that the bucket count is not zero.
1066 static inline size_t VT_CAT( NAME, _total_alloc_size )( NAME *table )
1067 {
1068 return VT_CAT( NAME, _metadata_offset )( table ) + ( table->buckets_mask + 1 + 4 ) * sizeof( uint16_t );
1069 }
1070
1071 VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _init_clone )(
1072 NAME *table,
1073 const NAME *source
1074 #ifdef CTX_TY
1075 , CTX_TY ctx
1076 #endif
1077 )
1078 {
1079 table->key_count = source->key_count;
1080 table->buckets_mask = source->buckets_mask;
1081 #ifdef CTX_TY
1082 table->ctx = ctx;
1083 #endif
1084
1085 if( !source->buckets_mask )
1086 {
1087 table->metadata = (uint16_t *)&vt_empty_placeholder_metadatum;
1088 table->buckets = NULL;
1089 return true;
1090 }
1091
1092 void *allocation = MALLOC_FN(
1093 VT_CAT( NAME, _total_alloc_size )( table )
1094 #ifdef CTX_TY
1095 , &table->ctx
1096 #endif
1097 );
1098
1099 if( VT_UNLIKELY( !allocation ) )
1100 return false;
1101
1102 table->buckets = (VT_CAT( NAME, _bucket ) *)allocation;
1103 table->metadata = (uint16_t *)( (unsigned char *)allocation + VT_CAT( NAME, _metadata_offset )( table ) );
1104 memcpy( allocation, source->buckets, VT_CAT( NAME, _total_alloc_size )( table ) );
1105
1106 return true;
1107 }
1108
1109 VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _size )( const NAME *table )
1110 {
1111 return table->key_count;
1112 }
1113
1114 VT_API_FN_QUALIFIERS size_t VT_CAT( NAME, _bucket_count )( const NAME *table )
1115 {
1116 // If the bucket count is zero, buckets_mask will be zero, not the bucket count minus one.
1117 // We account for this special case by adding (bool)buckets_mask rather than one.
1118 return table->buckets_mask + (bool)table->buckets_mask;
1119 }
1120
1121 VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _is_end )( VT_CAT( NAME, _itr ) itr )
1122 {
1123 return itr.metadatum == itr.metadata_end;
1124 }
1125
1126 // Finds the earliest empty bucket in which a key belonging to home_bucket can be placed, assuming that home_bucket
1127 // is already occupied.
1128 // The reason to begin the search at home_bucket, rather than the end of the existing chain, is that keys deleted from
1129 // other chains might have freed up buckets that could fall in this chain before the final key.
1130 // Returns true if an empty bucket within the range of the displacement limit was found, in which case the final two
1131 // pointer arguments contain the index of the empty bucket and its quadratic displacement from home_bucket.
1132 static inline bool VT_CAT( NAME, _find_first_empty )(
1133 NAME *table,
1134 size_t home_bucket,
1135 size_t *empty,
1136 uint16_t *displacement
1137 )
1138 {
1139 *displacement = 1;
1140 size_t linear_dispacement = 1;
1141
1142 while( true )
1143 {
1144 *empty = ( home_bucket + linear_dispacement ) & table->buckets_mask;
1145 if( table->metadata[ *empty ] == VT_EMPTY )
1146 return true;
1147
1148 if( VT_UNLIKELY( ++*displacement == VT_DISPLACEMENT_MASK ) )
1149 return false;
1150
1151 linear_dispacement += *displacement;
1152 }
1153 }
1154
1155 // Finds the key in the chain beginning in home_bucket after which to link a new key with displacement_to_empty
1156 // quadratic displacement and returns the index of the bucket containing that key.
1157 // Although the new key could simply be linked to the end of the chain, keeping the chain ordered by displacement
1158 // theoretically improves cache locality during lookups.
1159 static inline size_t VT_CAT( NAME, _find_insert_location_in_chain )(
1160 NAME *table,
1161 size_t home_bucket,
1162 uint16_t displacement_to_empty
1163 )
1164 {
1165 size_t candidate = home_bucket;
1166 while( true )
1167 {
1168 uint16_t displacement = table->metadata[ candidate ] & VT_DISPLACEMENT_MASK;
1169
1170 if( displacement > displacement_to_empty )
1171 return candidate;
1172
1173 candidate = ( home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask;
1174 }
1175 }
1176
1177 // Frees up a bucket occupied by a key not belonging there so that a new key belonging there can be placed there as the
1178 // beginning of a new chain.
1179 // This requires:
1180 // * Finding the previous key in the chain to which the occupying key belongs by rehashing it and then traversing the
1181 // chain.
1182 // * Disconnecting the key from the chain.
1183 // * Finding the appropriate empty bucket to which to move the key.
1184 // * Moving the key (and value) data to the empty bucket.
1185 // * Re-linking the key to the chain.
1186 // Returns true if the eviction succeeded, or false if no empty bucket to which to evict the occupying key could be
1187 // found within the displacement limit.
1188 static inline bool VT_CAT( NAME, _evict )( NAME *table, size_t bucket )
1189 {
1190 // Find the previous key in chain.
1191 size_t home_bucket = HASH_FN( table->buckets[ bucket ].key ) & table->buckets_mask;
1192 size_t prev = home_bucket;
1193 while( true )
1194 {
1195 size_t next = ( home_bucket + vt_quadratic( table->metadata[ prev ] & VT_DISPLACEMENT_MASK ) ) &
1196 table->buckets_mask;
1197
1198 if( next == bucket )
1199 break;
1200
1201 prev = next;
1202 }
1203
1204 // Disconnect the key from chain.
1205 table->metadata[ prev ] = ( table->metadata[ prev ] & ~VT_DISPLACEMENT_MASK ) | ( table->metadata[ bucket ] &
1206 VT_DISPLACEMENT_MASK );
1207
1208 // Find the empty bucket to which to move the key.
1209 size_t empty;
1210 uint16_t displacement;
1211 if( VT_UNLIKELY( !VT_CAT( NAME, _find_first_empty )( table, home_bucket, &empty, &displacement ) ) )
1212 return false;
1213
1214 // Find the key in the chain after which to link the moved key.
1215 prev = VT_CAT( NAME, _find_insert_location_in_chain )( table, home_bucket, displacement );
1216
1217 // Move the key (and value) data.
1218 table->buckets[ empty ] = table->buckets[ bucket ];
1219
1220 // Re-link the key to the chain from its new bucket.
1221 table->metadata[ empty ] = ( table->metadata[ bucket ] & VT_HASH_FRAG_MASK ) | ( table->metadata[ prev ] &
1222 VT_DISPLACEMENT_MASK );
1223 table->metadata[ prev ] = ( table->metadata[ prev ] & ~VT_DISPLACEMENT_MASK ) | displacement;
1224
1225 return true;
1226 }
1227
1228 // Returns an end iterator, i.e. any iterator for which .metadatum == .metadata_end.
1229 // This function just cleans up the library code in functions that return an end iterator as a failure indicator.
1230 static inline VT_CAT( NAME, _itr ) VT_CAT( NAME, _end_itr )( void )
1231 {
1232 VT_CAT( NAME, _itr ) itr = { NULL, NULL, NULL, 0 };
1233 return itr;
1234 }
1235
1236 // Inserts a key, optionally replacing the existing key if it already exists.
1237 // There are two main cases that must be handled:
1238 // * If the key's home bucket is empty or occupied by a key that does not belong there, then the key is inserted there,
1239 // evicting the occupying key if there is one.
1240 // * Otherwise, the chain of keys beginning at the home bucket is (if unique is false) traversed in search of a matching
1241 // key.
1242 // If none is found, then the new key is inserted at the earliest available bucket, per quadratic probing from the
1243 // home bucket, and then linked to the chain in a manner that maintains its quadratic order.
1244 // The unique argument tells the function whether to skip searching for the key before inserting it (on rehashing, this
1245 // step is unnecessary).
1246 // The replace argument tells the function whether to replace an existing key.
1247 // If replace is true, the function returns an iterator to the inserted key, or an end iterator if the key was not
1248 // inserted because of the maximum load factor or displacement limit constraints.
1249 // If replace is false, then the return value is as described above, except that if the key already exists, the function
1250 // returns an iterator to the existing key.
1251 static inline VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert_raw )(
1252 NAME *table,
1253 KEY_TY key,
1254 #ifdef VAL_TY
1255 VAL_TY *val,
1256 #endif
1257 bool unique,
1258 bool replace
1259 )
1260 {
1261 uint64_t hash = HASH_FN( key );
1262 uint16_t hashfrag = vt_hashfrag( hash );
1263 size_t home_bucket = hash & table->buckets_mask;
1264
1265 // Case 1: The home bucket is empty or contains a key that doesn't belong there.
1266 // This case also implicitly handles the case of a zero bucket count, since home_bucket will be zero and metadata[ 0 ]
1267 // will be the empty placeholder.
1268 // In that scenario, the zero buckets_mask triggers the below load-factor check.
1269 if( !( table->metadata[ home_bucket ] & VT_IN_HOME_BUCKET_MASK ) )
1270 {
1271 if(
1272 // Load-factor check.
1273 VT_UNLIKELY( table->key_count + 1 > VT_CAT( NAME, _bucket_count )( table ) * MAX_LOAD ) ||
1274 // Vacate the home bucket if it contains a key.
1275 ( table->metadata[ home_bucket ] != VT_EMPTY && VT_UNLIKELY( !VT_CAT( NAME, _evict )( table, home_bucket ) ) )
1276 )
1277 return VT_CAT( NAME, _end_itr )();
1278
1279 table->buckets[ home_bucket ].key = key;
1280 #ifdef VAL_TY
1281 table->buckets[ home_bucket ].val = *val;
1282 #endif
1283 table->metadata[ home_bucket ] = hashfrag | VT_IN_HOME_BUCKET_MASK | VT_DISPLACEMENT_MASK;
1284
1285 ++table->key_count;
1286
1287 VT_CAT( NAME, _itr ) itr = {
1288 table->buckets + home_bucket,
1289 table->metadata + home_bucket,
1290 table->metadata + table->buckets_mask + 1, // Iteration stopper (i.e. the first of the four excess metadata).
1291 home_bucket
1292 };
1293 return itr;
1294 }
1295
1296 // Case 2: The home bucket contains the beginning of a chain.
1297
1298 // Optionally, check the existing chain.
1299 if( !unique )
1300 {
1301 size_t bucket = home_bucket;
1302 while( true )
1303 {
1304 if(
1305 ( table->metadata[ bucket ] & VT_HASH_FRAG_MASK ) == hashfrag &&
1306 VT_LIKELY( CMPR_FN( table->buckets[ bucket ].key, key ) )
1307 )
1308 {
1309 if( replace )
1310 {
1311 #ifdef KEY_DTOR_FN
1312 KEY_DTOR_FN( table->buckets[ bucket ].key );
1313 #endif
1314 table->buckets[ bucket ].key = key;
1315
1316 #ifdef VAL_TY
1317 #ifdef VAL_DTOR_FN
1318 VAL_DTOR_FN( table->buckets[ bucket ].val );
1319 #endif
1320 table->buckets[ bucket ].val = *val;
1321 #endif
1322 }
1323
1324 VT_CAT( NAME, _itr ) itr = {
1325 table->buckets + bucket,
1326 table->metadata + bucket,
1327 table->metadata + table->buckets_mask + 1,
1328 home_bucket
1329 };
1330 return itr;
1331 }
1332
1333 uint16_t displacement = table->metadata[ bucket ] & VT_DISPLACEMENT_MASK;
1334 if( displacement == VT_DISPLACEMENT_MASK )
1335 break;
1336
1337 bucket = ( home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask;
1338 }
1339 }
1340
1341 size_t empty;
1342 uint16_t displacement;
1343 if(
1344 VT_UNLIKELY(
1345 // Load-factor check.
1346 table->key_count + 1 > VT_CAT( NAME, _bucket_count )( table ) * MAX_LOAD ||
1347 // Find the earliest empty bucket, per quadratic probing.
1348 !VT_CAT( NAME, _find_first_empty )( table, home_bucket, &empty, &displacement )
1349 )
1350 )
1351 return VT_CAT( NAME, _end_itr )();
1352
1353 // Insert the new key (and value) in the empty bucket and link it to the chain.
1354
1355 size_t prev = VT_CAT( NAME, _find_insert_location_in_chain )( table, home_bucket, displacement );
1356
1357 table->buckets[ empty ].key = key;
1358 #ifdef VAL_TY
1359 table->buckets[ empty ].val = *val;
1360 #endif
1361 table->metadata[ empty ] = hashfrag | ( table->metadata[ prev ] & VT_DISPLACEMENT_MASK );
1362 table->metadata[ prev ] = ( table->metadata[ prev ] & ~VT_DISPLACEMENT_MASK ) | displacement;
1363
1364 ++table->key_count;
1365
1366 VT_CAT( NAME, _itr ) itr = {
1367 table->buckets + empty,
1368 table->metadata + empty,
1369 table->metadata + table->buckets_mask + 1,
1370 home_bucket
1371 };
1372 return itr;
1373 }
1374
1375 // Resizes the bucket array.
1376 // This function assumes that bucket_count is a power of two and large enough to accommodate all keys without violating
1377 // the maximum load factor.
1378 // Returns false in the case of allocation failure.
1379 // As this function is called very rarely in _insert and _get_or_insert, ideally it should not be inlined into those
1380 // functions.
1381 // In testing, the no-inline approach showed a performance benefit when inserting existing keys (i.e. replacing).
1382 #ifdef __GNUC__
1383 #pragma GCC diagnostic push
1384 #pragma GCC diagnostic ignored "-Wattributes" // Silence warning about combining noinline with static inline.
1385 __attribute__((noinline)) static inline
1386 #elif defined( _MSC_VER )
1387 __declspec(noinline) static inline
1388 #else
1389 static inline
1390 #endif
1391 bool VT_CAT( NAME, _rehash )( NAME *table, size_t bucket_count )
1392 {
1393 // The attempt to resize the bucket array and rehash the keys must occur inside a loop that incrementally doubles the
1394 // target bucket count because a failure could theoretically occur at any load factor due to the displacement limit.
1395 while( true )
1396 {
1397 NAME new_table = {
1398 0,
1399 bucket_count - 1,
1400 NULL,
1401 NULL
1402 #ifdef CTX_TY
1403 , table->ctx
1404 #endif
1405 };
1406
1407 void *allocation = MALLOC_FN(
1408 VT_CAT( NAME, _total_alloc_size )( &new_table )
1409 #ifdef CTX_TY
1410 , &new_table.ctx
1411 #endif
1412 );
1413
1414 if( VT_UNLIKELY( !allocation ) )
1415 return false;
1416
1417 new_table.buckets = (VT_CAT( NAME, _bucket ) *)allocation;
1418 new_table.metadata = (uint16_t *)( (unsigned char *)allocation + VT_CAT( NAME, _metadata_offset )( &new_table ) );
1419
1420 memset( new_table.metadata, 0x00, ( bucket_count + 4 ) * sizeof( uint16_t ) );
1421
1422 // Iteration stopper at the end of the actual metadata array (i.e. the first of the four excess metadata).
1423 new_table.metadata[ bucket_count ] = 0x01;
1424
1425 for( size_t bucket = 0; bucket < VT_CAT( NAME, _bucket_count )( table ); ++bucket )
1426 if( table->metadata[ bucket ] != VT_EMPTY )
1427 {
1428 VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _insert_raw )(
1429 &new_table,
1430 table->buckets[ bucket ].key,
1431 #ifdef VAL_TY
1432 &table->buckets[ bucket ].val,
1433 #endif
1434 true,
1435 false
1436 );
1437
1438 if( VT_UNLIKELY( VT_CAT( NAME, _is_end )( itr ) ) )
1439 break;
1440 }
1441
1442 // If a key could not be reinserted due to the displacement limit, double the bucket count and retry.
1443 if( VT_UNLIKELY( new_table.key_count < table->key_count ) )
1444 {
1445 FREE_FN(
1446 new_table.buckets,
1447 VT_CAT( NAME, _total_alloc_size )( &new_table )
1448 #ifdef CTX_TY
1449 , &new_table.ctx
1450 #endif
1451 );
1452
1453 bucket_count *= 2;
1454 continue;
1455 }
1456
1457 if( table->buckets_mask )
1458 FREE_FN(
1459 table->buckets,
1460 VT_CAT( NAME, _total_alloc_size )( table )
1461 #ifdef CTX_TY
1462 , &table->ctx
1463 #endif
1464 );
1465
1466 *table = new_table;
1467 return true;
1468 }
1469 }
1470 #ifdef __GNUC__
1471 #pragma GCC diagnostic pop
1472 #endif
1473
1474 // Inserts a key, replacing the existing key if it already exists.
1475 // This function wraps insert_raw in a loop that handles growing and rehashing the table if a new key cannot be inserted
1476 // because of the maximum load factor or displacement limit constraints.
1477 // Returns an iterator to the inserted key, or an end iterator in the case of allocation failure.
1478 VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _insert )(
1479 NAME *table,
1480 KEY_TY key
1481 #ifdef VAL_TY
1482 , VAL_TY val
1483 #endif
1484 )
1485 {
1486 while( true )
1487 {
1488 VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _insert_raw )(
1489 table,
1490 key,
1491 #ifdef VAL_TY
1492 &val,
1493 #endif
1494 false,
1495 true
1496 );
1497
1498 if(
1499 // Lookup succeeded, in which case itr points to the found key.
1500 VT_LIKELY( !VT_CAT( NAME, _is_end )( itr ) ) ||
1501 // Lookup failed and rehash also fails, in which case itr is an end iterator.
1502 VT_UNLIKELY(
1503 !VT_CAT( NAME, _rehash )(
1504 table, table->buckets_mask ? VT_CAT( NAME, _bucket_count )( table ) * 2 : VT_MIN_NONZERO_BUCKET_COUNT
1505 )
1506 )
1507 )
1508 return itr;
1509 }
1510 }
1511
1512 // Same as NAME_insert, except that if the key already exists, no insertion occurs and the function returns an iterator
1513 // to the existing key.
1514 VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get_or_insert )(
1515 NAME *table,
1516 KEY_TY key
1517 #ifdef VAL_TY
1518 , VAL_TY val
1519 #endif
1520 )
1521 {
1522 while( true )
1523 {
1524 VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _insert_raw )(
1525 table,
1526 key,
1527 #ifdef VAL_TY
1528 &val,
1529 #endif
1530 false,
1531 false
1532 );
1533
1534 if(
1535 // Lookup succeeded, in which case itr points to the found key.
1536 VT_LIKELY( !VT_CAT( NAME, _is_end )( itr ) ) ||
1537 // Lookup failed and rehash also fails, in which case itr is an end iterator.
1538 VT_UNLIKELY(
1539 !VT_CAT( NAME, _rehash )(
1540 table, table->buckets_mask ? VT_CAT( NAME, _bucket_count )( table ) * 2 : VT_MIN_NONZERO_BUCKET_COUNT
1541 )
1542 )
1543 )
1544 return itr;
1545 }
1546 }
1547
1548 // Returns an iterator pointing to the specified key, or an end iterator if the key does not exist.
1549 VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _get )( const NAME *table, KEY_TY key )
1550 {
1551 uint64_t hash = HASH_FN( key );
1552 size_t home_bucket = hash & table->buckets_mask;
1553
1554 // If the home bucket is empty or contains a key that does not belong there, then our key does not exist.
1555 // This check also implicitly handles the case of a zero bucket count, since home_bucket will be zero and
1556 // metadata[ 0 ] will be the empty placeholder.
1557 if( !( table->metadata[ home_bucket ] & VT_IN_HOME_BUCKET_MASK ) )
1558 return VT_CAT( NAME, _end_itr )();
1559
1560 // Traverse the chain of keys belonging to the home bucket.
1561 uint16_t hashfrag = vt_hashfrag( hash );
1562 size_t bucket = home_bucket;
1563 while( true )
1564 {
1565 if(
1566 ( table->metadata[ bucket ] & VT_HASH_FRAG_MASK ) == hashfrag &&
1567 VT_LIKELY( CMPR_FN( table->buckets[ bucket ].key, key ) )
1568 )
1569 {
1570 VT_CAT( NAME, _itr ) itr = {
1571 table->buckets + bucket,
1572 table->metadata + bucket,
1573 table->metadata + table->buckets_mask + 1,
1574 home_bucket
1575 };
1576 return itr;
1577 }
1578
1579 uint16_t displacement = table->metadata[ bucket ] & VT_DISPLACEMENT_MASK;
1580 if( displacement == VT_DISPLACEMENT_MASK )
1581 return VT_CAT( NAME, _end_itr )();
1582
1583 bucket = ( home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask;
1584 }
1585 }
1586
1587 // Erases the key pointed to by the specified iterator.
1588 // The erasure always occurs at the end of the chain to which the key belongs.
1589 // If the key to be erased is not the last in the chain, it is swapped with the last so that erasure occurs at the end.
1590 // This helps keep a chain's keys close to their home bucket for the sake of cache locality.
1591 // Returns true if, in the case of iteration from first to end, NAME_next should now be called on the iterator to find
1592 // the next key.
1593 // This return value is necessary because at the iterator location, the erasure could result in an empty bucket, a
1594 // bucket containing a moved key already visited during the iteration, or a bucket containing a moved key not yet
1595 // visited.
1596 VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase_itr_raw )( NAME *table, VT_CAT( NAME, _itr ) itr )
1597 {
1598 --table->key_count;
1599 size_t itr_bucket = itr.metadatum - table->metadata;
1600
1601 // For now, we only call the value's destructor because the key may need to be hashed below to determine the home
1602 // bucket.
1603 #ifdef VAL_DTOR_FN
1604 VAL_DTOR_FN( table->buckets[ itr_bucket ].val );
1605 #endif
1606
1607 // Case 1: The key is the only one in its chain, so just remove it.
1608 if(
1609 table->metadata[ itr_bucket ] & VT_IN_HOME_BUCKET_MASK &&
1610 ( table->metadata[ itr_bucket ] & VT_DISPLACEMENT_MASK ) == VT_DISPLACEMENT_MASK
1611 )
1612 {
1613 #ifdef KEY_DTOR_FN
1614 KEY_DTOR_FN( table->buckets[ itr_bucket ].key );
1615 #endif
1616 table->metadata[ itr_bucket ] = VT_EMPTY;
1617 return true;
1618 }
1619
1620 // Case 2 and 3 require that we know the key's home bucket, which the iterator may not have recorded.
1621 if( itr.home_bucket == SIZE_MAX )
1622 {
1623 if( table->metadata[ itr_bucket ] & VT_IN_HOME_BUCKET_MASK )
1624 itr.home_bucket = itr_bucket;
1625 else
1626 itr.home_bucket = HASH_FN( table->buckets[ itr_bucket ].key ) & table->buckets_mask;
1627 }
1628
1629 // The key can now be safely destructed for cases 2 and 3.
1630 #ifdef KEY_DTOR_FN
1631 KEY_DTOR_FN( table->buckets[ itr_bucket ].key );
1632 #endif
1633
1634 // Case 2: The key is the last in a multi-key chain.
1635 // Traverse the chain from the beginning and find the penultimate key.
1636 // Then disconnect the key and erase.
1637 if( ( table->metadata[ itr_bucket ] & VT_DISPLACEMENT_MASK ) == VT_DISPLACEMENT_MASK )
1638 {
1639 size_t bucket = itr.home_bucket;
1640 while( true )
1641 {
1642 uint16_t displacement = table->metadata[ bucket ] & VT_DISPLACEMENT_MASK;
1643 size_t next = ( itr.home_bucket + vt_quadratic( displacement ) ) & table->buckets_mask;
1644 if( next == itr_bucket )
1645 {
1646 table->metadata[ bucket ] |= VT_DISPLACEMENT_MASK;
1647 table->metadata[ itr_bucket ] = VT_EMPTY;
1648 return true;
1649 }
1650
1651 bucket = next;
1652 }
1653 }
1654
1655 // Case 3: The chain has multiple keys, and the key is not the last one.
1656 // Traverse the chain from the key to be erased and find the last and penultimate keys.
1657 // Disconnect the last key from the chain, and swap it with the key to erase.
1658 size_t bucket = itr_bucket;
1659 while( true )
1660 {
1661 size_t prev = bucket;
1662 bucket = ( itr.home_bucket + vt_quadratic( table->metadata[ bucket ] & VT_DISPLACEMENT_MASK ) ) &
1663 table->buckets_mask;
1664
1665 if( ( table->metadata[ bucket ] & VT_DISPLACEMENT_MASK ) == VT_DISPLACEMENT_MASK )
1666 {
1667 table->buckets[ itr_bucket ] = table->buckets[ bucket ];
1668
1669 table->metadata[ itr_bucket ] = ( table->metadata[ itr_bucket ] & ~VT_HASH_FRAG_MASK ) | (
1670 table->metadata[ bucket ] & VT_HASH_FRAG_MASK );
1671
1672 table->metadata[ prev ] |= VT_DISPLACEMENT_MASK;
1673 table->metadata[ bucket ] = VT_EMPTY;
1674
1675 // Whether the iterator should be advanced depends on whether the key moved to the iterator bucket came from
1676 // before or after that bucket.
1677 // In the former case, the iteration would already have hit the moved key, so the iterator should still be
1678 // advanced.
1679 if( bucket > itr_bucket )
1680 return false;
1681
1682 return true;
1683 }
1684 }
1685 }
1686
1687 // Erases the specified key, if it exists.
1688 // Returns true if a key was erased.
1689 VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _erase )( NAME *table, KEY_TY key )
1690 {
1691 VT_CAT( NAME, _itr ) itr = VT_CAT( NAME, _get)( table, key );
1692 if( VT_CAT( NAME, _is_end )( itr ) )
1693 return false;
1694
1695 VT_CAT( NAME, _erase_itr_raw )( table, itr );
1696 return true;
1697 }
1698
1699 // Finds the first occupied bucket at or after the bucket pointed to by itr.
1700 // This function scans four buckets at a time, ideally using intrinsics.
1701 static inline void VT_CAT( NAME, _fast_forward )( VT_CAT( NAME, _itr ) *itr )
1702 {
1703 while( true )
1704 {
1705 uint64_t metadata;
1706 memcpy( &metadata, itr->metadatum, sizeof( uint64_t ) );
1707 if( metadata )
1708 {
1709 int offset = vt_first_nonzero_uint16( metadata );
1710 itr->data += offset;
1711 itr->metadatum += offset;
1712 itr->home_bucket = SIZE_MAX;
1713 return;
1714 }
1715
1716 itr->data += 4;
1717 itr->metadatum += 4;
1718 }
1719 }
1720
1721 VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _next )( VT_CAT( NAME, _itr ) itr )
1722 {
1723 ++itr.data;
1724 ++itr.metadatum;
1725 VT_CAT( NAME, _fast_forward )( &itr );
1726 return itr;
1727 }
1728
1729 // Returns the minimum bucket count required to accommodate a certain number of keys, which is governed by the maximum
1730 // load factor.
1731 static inline size_t VT_CAT( NAME, _min_bucket_count_for_size )( size_t size )
1732 {
1733 if( size == 0 )
1734 return 0;
1735
1736 // Round up to a power of two.
1737 size_t bucket_count = VT_MIN_NONZERO_BUCKET_COUNT;
1738 while( size > bucket_count * MAX_LOAD )
1739 bucket_count *= 2;
1740
1741 return bucket_count;
1742 }
1743
1744 VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _reserve )( NAME *table, size_t size )
1745 {
1746 size_t bucket_count = VT_CAT( NAME, _min_bucket_count_for_size )( size );
1747
1748 if( bucket_count <= VT_CAT( NAME, _bucket_count )( table ) )
1749 return true;
1750
1751 return VT_CAT( NAME, _rehash )( table, bucket_count );
1752 }
1753
1754 VT_API_FN_QUALIFIERS bool VT_CAT( NAME, _shrink )( NAME *table )
1755 {
1756 size_t bucket_count = VT_CAT( NAME, _min_bucket_count_for_size )( table->key_count );
1757
1758 if( bucket_count == VT_CAT( NAME, _bucket_count )( table ) ) // Shrink unnecessary.
1759 return true;
1760
1761 if( bucket_count == 0 )
1762 {
1763 FREE_FN(
1764 table->buckets,
1765 VT_CAT( NAME, _total_alloc_size )( table )
1766 #ifdef CTX_TY
1767 , &table->ctx
1768 #endif
1769 );
1770
1771 table->buckets_mask = 0x0000000000000000ull;
1772 table->metadata = (uint16_t *)&vt_empty_placeholder_metadatum;
1773 return true;
1774 }
1775
1776 return VT_CAT( NAME, _rehash )( table, bucket_count );
1777 }
1778
1779 VT_API_FN_QUALIFIERS VT_CAT( NAME, _itr ) VT_CAT( NAME, _first )( const NAME *table )
1780 {
1781 if( !table->key_count )
1782 return VT_CAT( NAME, _end_itr )();
1783
1784 VT_CAT( NAME, _itr ) itr = { table->buckets, table->metadata, table->metadata + table->buckets_mask + 1, SIZE_MAX };
1785 VT_CAT( NAME, _fast_forward )( &itr );
1786 return itr;
1787 }
1788
1789 VT_API_FN_QUALIFIERS void VT_CAT( NAME, _clear )( NAME *table )
1790 {
1791 if( !table->key_count )
1792 return;
1793
1794 for( size_t i = 0; i < VT_CAT( NAME, _bucket_count )( table ); ++i )
1795 {
1796 if( table->metadata[ i ] != VT_EMPTY )
1797 {
1798 #ifdef KEY_DTOR_FN
1799 KEY_DTOR_FN( table->buckets[ i ].key );
1800 #endif
1801 #ifdef VAL_DTOR_FN
1802 VAL_DTOR_FN( table->buckets[ i ].val );
1803 #endif
1804 }
1805
1806 table->metadata[ i ] = VT_EMPTY;
1807 }
1808
1809 table->key_count = 0;
1810 }
1811
1812 VT_API_FN_QUALIFIERS void VT_CAT( NAME, _cleanup )( NAME *table )
1813 {
1814 if( !table->buckets_mask )
1815 return;
1816
1817 #if defined( KEY_DTOR_FN ) || defined( VAL_DTOR_FN )
1818 VT_CAT( NAME, _clear )( table );
1819 #endif
1820
1821 FREE_FN(
1822 table->buckets,
1823 VT_CAT( NAME, _total_alloc_size )( table )
1824 #ifdef CTX_TY
1825 , &table->ctx
1826 #endif
1827 );
1828
1829 VT_CAT( NAME, _init )(
1830 table
1831 #ifdef CTX_TY
1832 , table->ctx
1833 #endif
1834 );
1835 }
1836
1837 #endif
1838
1839 /*--------------------------------------------------------------------------------------------------------------------*/
1840 /* Wrapper types and functions for the C11 generic API */
1841 /*--------------------------------------------------------------------------------------------------------------------*/
1842
1843 #if defined(__STDC_VERSION__) && \
1844 __STDC_VERSION__ >= 201112L && \
1845 !defined( IMPLEMENTATION_MODE ) && \
1846 !defined( VT_NO_C11_GENERIC_API ) \
1847
1848 typedef NAME VT_CAT( vt_table_, VT_TEMPLATE_COUNT );
1849 typedef VT_CAT( NAME, _itr ) VT_CAT( vt_table_itr_, VT_TEMPLATE_COUNT );
1850
1851 static inline void VT_CAT( vt_init_, VT_TEMPLATE_COUNT )(
1852 NAME *table
1853 #ifdef CTX_TY
1854 , CTX_TY ctx
1855 #endif
1856 )
1857 {
1858 VT_CAT( NAME, _init )(
1859 table
1860 #ifdef CTX_TY
1861 , ctx
1862 #endif
1863 );
1864 }
1865
1866 static inline bool VT_CAT( vt_init_clone_, VT_TEMPLATE_COUNT )(
1867 NAME *table,
1868 const NAME* source
1869 #ifdef CTX_TY
1870 , CTX_TY ctx
1871 #endif
1872 )
1873 {
1874 return VT_CAT( NAME, _init_clone )(
1875 table,
1876 source
1877 #ifdef CTX_TY
1878 , ctx
1879 #endif
1880 );
1881 }
1882
1883 static inline size_t VT_CAT( vt_size_, VT_TEMPLATE_COUNT )( const NAME *table )
1884 {
1885 return VT_CAT( NAME, _size )( table );
1886 }
1887
1888 static inline size_t VT_CAT( vt_bucket_count_, VT_TEMPLATE_COUNT )( const NAME *table )
1889 {
1890 return VT_CAT( NAME, _bucket_count )( table );
1891 }
1892
1893 static inline bool VT_CAT( vt_is_end_, VT_TEMPLATE_COUNT )( VT_CAT( NAME, _itr ) itr )
1894 {
1895 return VT_CAT( NAME, _is_end )( itr );
1896 }
1897
1898 static inline VT_CAT( NAME, _itr ) VT_CAT( vt_insert_, VT_TEMPLATE_COUNT )(
1899 NAME *table,
1900 KEY_TY key
1901 #ifdef VAL_TY
1902 , VAL_TY val
1903 #endif
1904 )
1905 {
1906 return VT_CAT( NAME, _insert )(
1907 table,
1908 key
1909 #ifdef VAL_TY
1910 , val
1911 #endif
1912 );
1913 }
1914
1915 static inline VT_CAT( NAME, _itr ) VT_CAT( vt_get_or_insert_, VT_TEMPLATE_COUNT )(
1916 NAME *table,
1917 KEY_TY key
1918 #ifdef VAL_TY
1919 , VAL_TY val
1920 #endif
1921 )
1922 {
1923 return VT_CAT( NAME, _get_or_insert )(
1924 table,
1925 key
1926 #ifdef VAL_TY
1927 , val
1928 #endif
1929 );
1930 }
1931
1932 static inline VT_CAT( NAME, _itr ) VT_CAT( vt_get_, VT_TEMPLATE_COUNT )( const NAME *table, KEY_TY key )
1933 {
1934 return VT_CAT( NAME, _get )( table, key );
1935 }
1936
1937 static inline bool VT_CAT( vt_erase_, VT_TEMPLATE_COUNT )( NAME *table, KEY_TY key )
1938 {
1939 return VT_CAT( NAME, _erase )( table, key );
1940 }
1941
1942 static inline VT_CAT( NAME, _itr ) VT_CAT( vt_next_, VT_TEMPLATE_COUNT )( VT_CAT( NAME, _itr ) itr )
1943 {
1944 return VT_CAT( NAME, _next )( itr );
1945 }
1946
1947 static inline VT_CAT( NAME, _itr ) VT_CAT( vt_erase_itr_, VT_TEMPLATE_COUNT )( NAME *table, VT_CAT( NAME, _itr ) itr )
1948 {
1949 return VT_CAT( NAME, _erase_itr )( table, itr );
1950 }
1951
1952 static inline bool VT_CAT( vt_reserve_, VT_TEMPLATE_COUNT )( NAME *table, size_t bucket_count )
1953 {
1954 return VT_CAT( NAME, _reserve )( table, bucket_count );
1955 }
1956
1957 static inline bool VT_CAT( vt_shrink_, VT_TEMPLATE_COUNT )( NAME *table )
1958 {
1959 return VT_CAT( NAME, _shrink )( table );
1960 }
1961
1962 static inline VT_CAT( NAME, _itr ) VT_CAT( vt_first_, VT_TEMPLATE_COUNT )( const NAME *table )
1963 {
1964 return VT_CAT( NAME, _first )( table );
1965 }
1966
1967 static inline void VT_CAT( vt_clear_, VT_TEMPLATE_COUNT )( NAME *table )
1968 {
1969 VT_CAT( NAME, _clear )( table );
1970 }
1971
1972 static inline void VT_CAT( vt_cleanup_, VT_TEMPLATE_COUNT )( NAME *table )
1973 {
1974 VT_CAT( NAME, _cleanup )( table );
1975 }
1976
1977 // Increment the template counter.
1978 #if VT_TEMPLATE_COUNT_D1 == 0
1979 #undef VT_TEMPLATE_COUNT_D1
1980 #define VT_TEMPLATE_COUNT_D1 1
1981 #elif VT_TEMPLATE_COUNT_D1 == 1
1982 #undef VT_TEMPLATE_COUNT_D1
1983 #define VT_TEMPLATE_COUNT_D1 2
1984 #elif VT_TEMPLATE_COUNT_D1 == 2
1985 #undef VT_TEMPLATE_COUNT_D1
1986 #define VT_TEMPLATE_COUNT_D1 3
1987 #elif VT_TEMPLATE_COUNT_D1 == 3
1988 #undef VT_TEMPLATE_COUNT_D1
1989 #define VT_TEMPLATE_COUNT_D1 4
1990 #elif VT_TEMPLATE_COUNT_D1 == 4
1991 #undef VT_TEMPLATE_COUNT_D1
1992 #define VT_TEMPLATE_COUNT_D1 5
1993 #elif VT_TEMPLATE_COUNT_D1 == 5
1994 #undef VT_TEMPLATE_COUNT_D1
1995 #define VT_TEMPLATE_COUNT_D1 6
1996 #elif VT_TEMPLATE_COUNT_D1 == 6
1997 #undef VT_TEMPLATE_COUNT_D1
1998 #define VT_TEMPLATE_COUNT_D1 7
1999 #elif VT_TEMPLATE_COUNT_D1 == 7
2000 #undef VT_TEMPLATE_COUNT_D1
2001 #define VT_TEMPLATE_COUNT_D1 0
2002 #if VT_TEMPLATE_COUNT_D2 == 0
2003 #undef VT_TEMPLATE_COUNT_D2
2004 #define VT_TEMPLATE_COUNT_D2 1
2005 #elif VT_TEMPLATE_COUNT_D2 == 1
2006 #undef VT_TEMPLATE_COUNT_D2
2007 #define VT_TEMPLATE_COUNT_D2 2
2008 #elif VT_TEMPLATE_COUNT_D2 == 2
2009 #undef VT_TEMPLATE_COUNT_D2
2010 #define VT_TEMPLATE_COUNT_D2 3
2011 #elif VT_TEMPLATE_COUNT_D2 == 3
2012 #undef VT_TEMPLATE_COUNT_D2
2013 #define VT_TEMPLATE_COUNT_D2 4
2014 #elif VT_TEMPLATE_COUNT_D2 == 4
2015 #undef VT_TEMPLATE_COUNT_D2
2016 #define VT_TEMPLATE_COUNT_D2 5
2017 #elif VT_TEMPLATE_COUNT_D2 == 5
2018 #undef VT_TEMPLATE_COUNT_D2
2019 #define VT_TEMPLATE_COUNT_D2 6
2020 #elif VT_TEMPLATE_COUNT_D2 == 6
2021 #undef VT_TEMPLATE_COUNT_D2
2022 #define VT_TEMPLATE_COUNT_D2 7
2023 #elif VT_TEMPLATE_COUNT_D2 == 7
2024 #undef VT_TEMPLATE_COUNT_D2
2025 #define VT_TEMPLATE_COUNT_D2 0
2026 #if VT_TEMPLATE_COUNT_D3 == 0
2027 #undef VT_TEMPLATE_COUNT_D3
2028 #define VT_TEMPLATE_COUNT_D3 1
2029 #elif VT_TEMPLATE_COUNT_D3 == 1
2030 #undef VT_TEMPLATE_COUNT_D3
2031 #define VT_TEMPLATE_COUNT_D3 2
2032 #elif VT_TEMPLATE_COUNT_D3 == 2
2033 #undef VT_TEMPLATE_COUNT_D3
2034 #define VT_TEMPLATE_COUNT_D3 3
2035 #elif VT_TEMPLATE_COUNT_D3 == 3
2036 #undef VT_TEMPLATE_COUNT_D3
2037 #define VT_TEMPLATE_COUNT_D3 4
2038 #elif VT_TEMPLATE_COUNT_D3 == 4
2039 #undef VT_TEMPLATE_COUNT_D3
2040 #define VT_TEMPLATE_COUNT_D3 5
2041 #elif VT_TEMPLATE_COUNT_D3 == 5
2042 #undef VT_TEMPLATE_COUNT_D3
2043 #define VT_TEMPLATE_COUNT_D3 6
2044 #elif VT_TEMPLATE_COUNT_D3 == 6
2045 #undef VT_TEMPLATE_COUNT_D3
2046 #define VT_TEMPLATE_COUNT_D3 7
2047 #elif VT_TEMPLATE_COUNT_D3 == 7
2048 #error Sorry, the number of template instances is limited to 511. Define VT_NO_C11_GENERIC_API globally and use the \
2049 C99 prefixed function API to circumvent this restriction.
2050 #endif
2051 #endif
2052 #endif
2053
2054 #endif
2055
2056 #undef NAME
2057 #undef KEY_TY
2058 #undef VAL_TY
2059 #undef HASH_FN
2060 #undef CMPR_FN
2061 #undef MAX_LOAD
2062 #undef KEY_DTOR_FN
2063 #undef VAL_DTOR_FN
2064 #undef CTX_TY
2065 #undef MALLOC_FN
2066 #undef FREE_FN
2067 #undef HEADER_MODE
2068 #undef IMPLEMENTATION_MODE
2069 #undef VT_API_FN_QUALIFIERS