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 <assert.h>
26 : #include <cbstmap.h>
27 : #include <internal/test_helpers/cbstmap.h>
28 : #include <math.h>
29 : #include <stdbool.h>
30 : #include <stdio.h>
31 : #include <stdlib.h>
32 : #include <string.h>
33 :
34 : // Upper bound on the height of any AVL tree this map can hold. An AVL tree is
35 : // never taller than about 1.44 * log2(n + 2), so 128 covers every count a
36 : // 64-bit size_t can reach. Every internal stack (the ancestor path of an insert
37 : // or delete, the destroy walk, the iterator) holds one entry per level, so a
38 : // fixed array of this size never overflows and those paths need no heap memory;
39 : // a delete can't run out of memory.
40 : #define CBMAP_MAX_TREE_HEIGHT 128
41 :
42 : // Gives the alignment a stored key of this type needs. Creation calls it once
43 : // to place the key bytes inside every node. It uses _Alignof of the type
44 : // itself, since alignment and width differ on some targets. A string key stores
45 : // bytes, so char alignment; ccol_other_types and unknown types keep
46 : // max_align_t, because their real requirement isn't known.
47 158 : static inline size_t cbmap_key_alignment(ccol_data_type type) {
48 158 : switch (type) {
49 : case ccol_char:
50 : case ccol_signed_char:
51 : case ccol_unsigned_char:
52 : case ccol_string:
53 : return _Alignof(char);
54 : case ccol_short:
55 : case ccol_unsigned_short:
56 : return _Alignof(short);
57 : case ccol_int:
58 : case ccol_unsigned_int:
59 : return _Alignof(int);
60 : case ccol_long:
61 : case ccol_unsigned_long:
62 : return _Alignof(long);
63 : case ccol_long_long:
64 : case ccol_unsigned_long_long:
65 : return _Alignof(long long);
66 : case ccol_float:
67 : return _Alignof(float);
68 : case ccol_double:
69 : return _Alignof(double);
70 : case ccol_long_double:
71 : return _Alignof(long double);
72 : case ccol_pointer:
73 : return _Alignof(void *);
74 : default:
75 : return _Alignof(max_align_t);
76 : }
77 : }
78 :
79 : // Evaluates to n rounded up to a multiple of the power of two a; creation and
80 : // create_new_node() place the key and the value with it. A value is aligned to
81 : // max_align_t because the map doesn't record the value type; a descent never
82 : // reads values, so this costs nothing where it matters.
83 : #define CBMAP_ALIGN_UP_TO(n, a) (((n) + (a) - 1u) & ~(size_t)((a) - 1u))
84 : #define CBMAP_NODE_VAL_ALIGN _Alignof(max_align_t)
85 :
86 : // bmap_node keeps its height in one byte.
87 : _Static_assert(CBMAP_MAX_TREE_HEIGHT <= UINT8_MAX,
88 : "bmap_node stores a height in one byte; raising "
89 : "CBMAP_MAX_TREE_HEIGHT past UINT8_MAX needs a wider field");
90 :
91 : // A tree node. One allocation holds the node, then the key bytes at
92 : // cbm->key_offset, then the value bytes; key_pair and val_pair point into it
93 : // (or are {NULL, 0} for an empty key or value).
94 : typedef struct bmap_node {
95 : cmap_pair key_pair;
96 : cmap_pair val_pair;
97 : struct bmap_node *left;
98 : struct bmap_node *right;
99 : // One byte holds any height below CBMAP_MAX_TREE_HEIGHT and keeps the key
100 : // bytes inside the first 64 bytes of the node, which a descent reads anyway.
101 : uint8_t height;
102 : // True once an update of another size moved the value out of the node's
103 : // allocation into a buffer of its own.
104 : bool val_is_external;
105 : } bmap_node;
106 :
107 : // The map. m_procs is a copy of the caller's allocator, or NULL for the
108 : // default.
109 : typedef struct cbstmap {
110 : size_t elem_count;
111 : bmap_node *root;
112 : ccol_memmgmt_procs *m_procs;
113 : ccol_data_type key_type;
114 : size_t key_alignment; // from key_type, fixed at creation
115 : ccol_comparison_proc custom_comparison_proc;
116 : // Where the key bytes sit in every node and which comparison a descent makes;
117 : // both follow from key_type and the comparator at creation.
118 : size_t key_offset;
119 : uint8_t cmp_kind;
120 : } cbstmap;
121 :
122 : // An in-order iterator: A cmap_iterator plus a fixed stack of nodes whose left
123 : // subtree is done and which are waiting to be visited.
124 : typedef struct cbmap_cmap_iterator {
125 : // The free function of the map's allocator (NULL for the default). A scoped
126 : // iterator can be freed after its map is gone, so freeing it never reads the
127 : // map.
128 : ccol_free free_fn;
129 : bmap_node *node_stack[CBMAP_MAX_TREE_HEIGHT];
130 : size_t node_stack_len;
131 : cmap_iterator user_iter;
132 : } cbmap_cmap_iterator;
133 :
134 : // Evaluates to the cbmap_cmap_iterator that holds the cmap_iterator u_iter, so
135 : // the iterator callbacks can reach the node stack.
136 : #define cmapIter2CbmapIter(u_iter) \
137 : (cbmap_cmap_iterator *)((uint8_t *)u_iter - \
138 : offsetof(cbmap_cmap_iterator, user_iter))
139 :
140 : // One step of the path a descent records: A node and the link that points at
141 : // it.
142 : typedef struct node_stack_entry {
143 : bmap_node *node;
144 : bmap_node **parent_link; // the parent's left or right pointer, or NULL
145 : } node_stack_entry;
146 :
147 : // Pushes node and its chain of left children onto the iterator's stack. The
148 : // in-order walk needs it so the next pop is the smallest key of that subtree
149 : // not visited yet. Asserts if the fixed stack would overflow.
150 592741 : static void push_all_lefts_into_iter_stack(cbmap_cmap_iterator *real_iter,
151 : bmap_node *node) {
152 1777690 : while (node) {
153 1184949 : ccol__assert(real_iter->node_stack_len < CBMAP_MAX_TREE_HEIGHT);
154 1184949 : real_iter->node_stack[real_iter->node_stack_len++] = node;
155 1184949 : node = node->left;
156 : }
157 592741 : }
158 :
159 : // Advances real_iter to the next key in order. begin and next both use it. It
160 : // pops a node, pushes the left chain of its right child and points the user
161 : // iterator at the node's pairs. Gives the user iterator, or NULL at the end,
162 : // when it frees the iterator.
163 1186983 : static cmap_iterator *cmap_real_iter_next(cbmap_cmap_iterator *real_iter) {
164 1186983 : if (real_iter->node_stack_len == 0) {
165 2039 : cbstmap__iterator_destroy(&real_iter->user_iter);
166 2039 : return NULL;
167 : }
168 1184944 : bmap_node *node = real_iter->node_stack[--real_iter->node_stack_len];
169 1184944 : if (node->right) {
170 590699 : push_all_lefts_into_iter_stack(real_iter, node->right);
171 : }
172 :
173 1184944 : real_iter->user_iter.key_pair = &node->key_pair;
174 1184944 : real_iter->user_iter.val_pair = &node->val_pair;
175 1184944 : return &real_iter->user_iter;
176 : }
177 :
178 : static cmap_iterator *cbmap_iter_next(cmap_iterator *iter);
179 :
180 : // Creates an iterator at the smallest key; ccol_begin() calls it for a cbmap.
181 : // It allocates through the map's allocator and gives NULL with *err set when
182 : // that fails. A NULL or empty map gives NULL with *err NULL, the same contract
183 : // as chashmap_begin_iter(), so an unused map field can be iterated with no
184 : // guard.
185 2046 : cmap_iterator *cbstmap_begin_iter(cbmap cbm, char **err) {
186 2046 : if (err) {
187 2043 : *err = NULL;
188 : }
189 :
190 2046 : if (!cbm || !cbm->root) {
191 : return NULL;
192 : }
193 :
194 4084 : cbmap_cmap_iterator *real_iter =
195 2042 : ccol__mem_alloc(cbm->m_procs, sizeof(cbmap_cmap_iterator));
196 2042 : if (!real_iter) {
197 0 : if (err) {
198 0 : *err = CCOL__ERR_STR("Failed to create the iterator buffer");
199 : }
200 0 : return NULL;
201 : }
202 :
203 2042 : real_iter->node_stack_len = 0;
204 2042 : real_iter->free_fn = cbm->m_procs ? cbm->m_procs->free : NULL;
205 2042 : real_iter->user_iter.ccol__next_fn = cbmap_iter_next;
206 2042 : real_iter->user_iter.ccol__free_fn = cbstmap__iterator_destroy;
207 2042 : real_iter->user_iter.ccol__direct_ptr = false;
208 2042 : push_all_lefts_into_iter_stack(real_iter, cbm->root);
209 2042 : return cmap_real_iter_next(real_iter);
210 : }
211 :
212 : // Moves iter to the next key; it's the ccol__next_fn that ccol_iter_next()
213 : // calls. Gives the iterator, or NULL at the end, when the iterator is freed.
214 : // Asserts on a NULL iter.
215 1184941 : static cmap_iterator *cbmap_iter_next(cmap_iterator *iter) {
216 1184941 : if (!iter) {
217 0 : ccol__assert(false);
218 : }
219 :
220 1184941 : cbmap_cmap_iterator *real_iter = cmapIter2CbmapIter(iter);
221 1184941 : return cmap_real_iter_next(real_iter);
222 : }
223 :
224 : // Frees an iterator; it's the ccol__free_fn, used at the end of a walk and by
225 : // ccol_iter_destroy() or a scoped iterator that leaves early. It uses the free
226 : // function saved in the iterator and never reads the map, so it's valid after
227 : // the map is destroyed.
228 2042 : void cbstmap__iterator_destroy(cmap_iterator *iter) {
229 2042 : if (iter) {
230 2042 : cbmap_cmap_iterator *real_iter = cmapIter2CbmapIter(iter);
231 2042 : ccol_free free_fn = real_iter->free_fn;
232 2042 : if (free_fn) {
233 1 : free_fn(real_iter);
234 : } else {
235 2041 : ccol__default_mem_free(real_iter);
236 : }
237 : }
238 2042 : }
239 :
240 : // The comparison a descent makes. CBMAP_CMP_GENERIC goes through
241 : // compare_keys(); every other kind is an integer or char key with no custom
242 : // comparator, compared with < and ==, which gives the same order.
243 : enum {
244 : CBMAP_CMP_GENERIC = 0,
245 : CBMAP_CMP_CHAR,
246 : CBMAP_CMP_S8,
247 : CBMAP_CMP_S16,
248 : CBMAP_CMP_S32,
249 : CBMAP_CMP_S64,
250 : CBMAP_CMP_U8,
251 : CBMAP_CMP_U16,
252 : CBMAP_CMP_U32,
253 : CBMAP_CMP_U64
254 : };
255 :
256 : // Picks the comparison every descent of a new map makes, so the hot loops don't
257 : // dispatch on the key type per node. An integer or char key without a custom
258 : // comparator gets a typed kind by its real width; everything else gets
259 : // CBMAP_CMP_GENERIC.
260 158 : static uint8_t cbmap_cmp_kind(ccol_data_type key_type,
261 : ccol_comparison_proc custom_proc) {
262 158 : if (custom_proc) return CBMAP_CMP_GENERIC;
263 201 : size_t width = ccol_fixed_width_data_type_size(key_type);
264 153 : switch (key_type) {
265 : case ccol_char:
266 : return CBMAP_CMP_CHAR;
267 83 : case ccol_signed_char:
268 : case ccol_short:
269 : case ccol_int:
270 : case ccol_long:
271 : case ccol_long_long:
272 83 : switch (width) {
273 : case 1:
274 : return CBMAP_CMP_S8;
275 4 : case 2:
276 4 : return CBMAP_CMP_S16;
277 64 : case 4:
278 64 : return CBMAP_CMP_S32;
279 10 : case 8:
280 10 : return CBMAP_CMP_S64;
281 : default:
282 : return CBMAP_CMP_GENERIC;
283 : }
284 23 : case ccol_unsigned_char:
285 : case ccol_unsigned_short:
286 : case ccol_unsigned_int:
287 : case ccol_unsigned_long:
288 : case ccol_unsigned_long_long:
289 : case ccol_pointer:
290 23 : switch (width) {
291 : case 1:
292 : return CBMAP_CMP_U8;
293 4 : case 2:
294 4 : return CBMAP_CMP_U16;
295 5 : case 4:
296 5 : return CBMAP_CMP_U32;
297 11 : case 8:
298 11 : return CBMAP_CMP_U64;
299 : default:
300 : return CBMAP_CMP_GENERIC;
301 : }
302 : default:
303 : return CBMAP_CMP_GENERIC;
304 : }
305 : }
306 :
307 : // Checks the creation inputs of cbstmap_create_full(), which means only the
308 : // allocator: Every key type is legal, and one it doesn't know uses memcmp like
309 : // ccol_other_types. Sets *err and gives false on failure.
310 162 : static bool verify_cbmap_create_inputs(ccol_memmgmt_procs *mmgmt_procs,
311 : char **err) {
312 11 : if (!ccol__verify_memmgmt_procs(mmgmt_procs, err)) {
313 4 : return false;
314 : }
315 :
316 : return true;
317 : }
318 :
319 : // Creates an empty map for keys of key_type. It's the one constructor behind
320 : // every create function and cbmap_construct form, so the inputs are checked
321 : // here. mmgmt_procs is the allocator (NULL for malloc and free), which the map
322 : // copies; custom_comparison_proc replaces the default order. Gives the handle,
323 : // or NULL with *err set on failure. key_alignment, key_offset and cmp_kind are
324 : // fixed here for the map's life.
325 162 : cbmap cbstmap_create_full(ccol_data_type key_type,
326 : ccol_memmgmt_procs *mmgmt_procs,
327 : ccol_comparison_proc custom_comparison_proc,
328 : char **err) {
329 162 : if (err) {
330 126 : *err = NULL;
331 : }
332 :
333 162 : if (!verify_cbmap_create_inputs(mmgmt_procs, err)) {
334 4 : return NULL;
335 : }
336 :
337 158 : cbmap cbm = ccol__mem_alloc(mmgmt_procs, sizeof(cbstmap));
338 158 : if (!cbm) {
339 0 : if (err) {
340 0 : *err = CCOL__ERR_STR("Failed to allocate cbstmap area");
341 : }
342 0 : return NULL;
343 : }
344 :
345 158 : if (!ccol__populate_mem_mgmt_procs(cbm, mmgmt_procs, err)) {
346 0 : ccol__mem_free(mmgmt_procs, cbm);
347 0 : return NULL;
348 : }
349 :
350 158 : cbm->elem_count = 0;
351 158 : cbm->root = NULL;
352 158 : cbm->key_type = key_type;
353 158 : cbm->key_alignment = cbmap_key_alignment(key_type);
354 158 : cbm->custom_comparison_proc = custom_comparison_proc;
355 158 : cbm->key_offset = CBMAP_ALIGN_UP_TO(sizeof(bmap_node), cbm->key_alignment);
356 158 : cbm->cmp_kind = cbmap_cmp_kind(key_type, custom_comparison_proc);
357 :
358 158 : return cbm;
359 : }
360 :
361 : // Frees one node and, when an update moved it out, its value buffer. Clear,
362 : // delete and the replacement logic use it. The key is part of the node's block.
363 : // The caller unlinks the node first; the child pointers aren't touched.
364 2012671 : static void destroy_bmap_node(cbmap cbm, bmap_node *node) {
365 2012671 : if (node) {
366 2012671 : if (node->val_is_external) {
367 4 : ccol__mem_free(cbm->m_procs, node->val_pair.ptr);
368 : }
369 2012671 : ccol__mem_free(cbm->m_procs, node);
370 : }
371 2012671 : }
372 :
373 : // Frees every node of the map, for reset and destroy. It walks in post-order
374 : // over a fixed stack, so a parent's child pointers stay valid until both
375 : // children are gone, and needs no memory. Sets root to NULL and elem_count to
376 : // 0.
377 157 : static void clear_nodes(cbmap cbm) {
378 157 : if (!cbm->root) {
379 30 : return;
380 : }
381 :
382 : bmap_node *stack[CBMAP_MAX_TREE_HEIGHT];
383 : size_t stack_len = 0;
384 :
385 : bmap_node *current = cbm->root;
386 : bmap_node *last_visited = NULL;
387 :
388 2503420 : while (stack_len > 0 || current) {
389 2503293 : if (current) {
390 1001343 : ccol__assert(stack_len < CBMAP_MAX_TREE_HEIGHT);
391 1001343 : stack[stack_len++] = current;
392 1001343 : current = current->left;
393 : } else {
394 1501950 : bmap_node *peek = stack[stack_len - 1];
395 :
396 1501950 : if (peek->right && peek->right != last_visited) {
397 : current = peek->right;
398 : } else {
399 1001343 : --stack_len;
400 1001343 : destroy_bmap_node(cbm, peek);
401 1001343 : last_visited = peek;
402 : }
403 : }
404 : }
405 :
406 127 : cbm->root = NULL;
407 127 : cbm->elem_count = 0;
408 : }
409 :
410 : // Frees every node, the allocator copy and the map; cbstmap_destroy() and the
411 : // scoped cleanup call it. NULL is fine. The free function is read before the
412 : // copy that holds it goes away.
413 155 : void cbstmap__destroy(cbmap cbm) {
414 155 : if (cbm) {
415 155 : clear_nodes(cbm);
416 :
417 155 : if (cbm->m_procs) {
418 7 : ccol_free free_func = cbm->m_procs->free;
419 7 : free_func(cbm->m_procs);
420 7 : free_func(cbm);
421 : } else {
422 148 : ccol__default_mem_free(cbm);
423 : }
424 : }
425 155 : }
426 :
427 : // Gives the number of entries in cbm, for callers and cbmap_size(). Asserts on
428 : // a NULL cbm.
429 38170 : size_t cbstmap_size(cbmap cbm) {
430 38170 : if (!cbm) {
431 0 : ccol__assert(false);
432 : }
433 :
434 38170 : return cbm->elem_count;
435 : }
436 :
437 : // Removes every entry and keeps the empty map usable, for callers and
438 : // cbmap_reset(). Gives ccol_success. Asserts on a NULL cbm.
439 2 : ccol_retval cbstmap_reset(cbmap cbm) {
440 2 : if (!cbm) {
441 0 : ccol__assert(false);
442 : }
443 :
444 2 : clear_nodes(cbm);
445 :
446 2 : return ccol_success;
447 : }
448 :
449 : // Compares two signed integers of 1, 2, 4 or 8 bytes as signed values, so 0xFF
450 : // is -1. compare_keys() uses it for the signed key types. A plain char key
451 : // never comes here; ccol_char compares as the platform's own char.
452 0 : static inline int cmp_signed_small(void *ptr1, void *ptr2, size_t size) {
453 0 : switch (size) {
454 : case 1: {
455 0 : return ccol__typed_cmp(ptr1, ptr2, int8_t);
456 : }
457 : case 2: {
458 0 : return ccol__typed_cmp(ptr1, ptr2, int16_t);
459 : }
460 : case 4: {
461 0 : return ccol__typed_cmp(ptr1, ptr2, int32_t);
462 : }
463 : case 8: {
464 0 : return ccol__typed_cmp(ptr1, ptr2, int64_t);
465 : }
466 : default: {
467 0 : ccol__assert(false);
468 : return 0;
469 : }
470 : }
471 : }
472 :
473 : // Compares two unsigned integers or pointers of 1, 2, 4 or 8 bytes, with memcmp
474 : // for any other size. compare_keys() uses it only for unsigned and pointer key
475 : // types, never for a struct that happens to have one of these sizes.
476 0 : static inline int cmp_unsigned_small(void *ptr1, void *ptr2, size_t size) {
477 0 : switch (size) {
478 : case 1: {
479 0 : return ccol__typed_cmp(ptr1, ptr2, uint8_t);
480 : }
481 : case 2: {
482 0 : return ccol__typed_cmp(ptr1, ptr2, uint16_t);
483 : }
484 : case 4: {
485 0 : return ccol__typed_cmp(ptr1, ptr2, uint32_t);
486 : }
487 : case 8: {
488 0 : return ccol__typed_cmp(ptr1, ptr2, uint64_t);
489 : }
490 0 : default: {
491 0 : return memcmp(ptr1, ptr2, size);
492 : }
493 : }
494 : }
495 :
496 : // Three-way comparison of two T values with NaN above every other value and
497 : // equal only to NaN. A BST needs a real total order: With the native < and > a
498 : // NaN key compares equal to the first node it meets, and an insert would
499 : // overwrite that node's value. The operands are read with memcpy because a
500 : // caller's pair carries no alignment or effective type of T. The temporaries
501 : // have module-specific names so they can't capture a caller's ptr expression.
502 : #define cmp_float_val(T, ptr1, ptr2) \
503 : ({ \
504 : T cbmap_cfv_lhs; \
505 : T cbmap_cfv_rhs; \
506 : memcpy(&cbmap_cfv_lhs, (ptr1), sizeof(T)); \
507 : memcpy(&cbmap_cfv_rhs, (ptr2), sizeof(T)); \
508 : bool cbmap_cfv_nan_lhs = isnan(cbmap_cfv_lhs); \
509 : bool cbmap_cfv_nan_rhs = isnan(cbmap_cfv_rhs); \
510 : (cbmap_cfv_nan_lhs || cbmap_cfv_nan_rhs) \
511 : ? (cbmap_cfv_nan_lhs == cbmap_cfv_nan_rhs \
512 : ? 0 \
513 : : (cbmap_cfv_nan_lhs ? 1 : -1)) \
514 : : (cbmap_cfv_lhs > cbmap_cfv_rhs) - (cbmap_cfv_lhs < cbmap_cfv_rhs); \
515 : })
516 :
517 : // Compares two floating keys by value for compare_keys(). It dispatches on
518 : // key_type because long double can have the size of double. -0.0 equals 0.0 and
519 : // NaN follows the rule of cmp_float_val.
520 74 : static inline int cmp_float_small(ccol_data_type key_type, void *ptr1,
521 : void *ptr2) {
522 74 : switch (key_type) {
523 : case ccol_float: {
524 9 : return cmp_float_val(float, ptr1, ptr2);
525 : }
526 : case ccol_double: {
527 56 : return cmp_float_val(double, ptr1, ptr2);
528 : }
529 : case ccol_long_double: {
530 9 : return cmp_float_val(long double, ptr1, ptr2);
531 : }
532 : default: {
533 0 : ccol__assert(false);
534 : return 0;
535 : }
536 : }
537 : }
538 :
539 : // Compares two keys of the map and gives < 0, 0 or > 0. Every descent that
540 : // can't use a typed comparison comes here. It uses the custom comparator when
541 : // there is one; for two sizes the common prefix and then the length (only
542 : // variable-width keys get here); otherwise by key_type, as signed, unsigned,
543 : // floating, string bytes or, for ccol_other_types and unknown types, memcmp. A
544 : // stored empty key is {NULL, 0}, and memcmp must not get a NULL pointer even
545 : // for 0 bytes, hence the zero-size checks.
546 2449 : static inline int compare_keys(cbmap cbm, const cmap_pair *key_pair1,
547 : const cmap_pair *key_pair2) {
548 2449 : if (cbm->custom_comparison_proc) {
549 1094 : return cbm->custom_comparison_proc(key_pair1->ptr, key_pair2->ptr);
550 : }
551 :
552 1355 : if (key_pair1->size != key_pair2->size) {
553 29 : size_t min_size = ccol__min(key_pair1->size, key_pair2->size);
554 61 : int cmp =
555 29 : min_size == 0 ? 0 : memcmp(key_pair1->ptr, key_pair2->ptr, min_size);
556 28 : if (cmp != 0) {
557 : return cmp;
558 : }
559 :
560 4 : return (key_pair1->size > key_pair2->size) -
561 4 : (key_pair1->size < key_pair2->size);
562 : }
563 :
564 1326 : switch (cbm->key_type) {
565 81 : case ccol_string: {
566 81 : return memcmp(key_pair1->ptr, key_pair2->ptr, key_pair1->size);
567 : }
568 :
569 0 : case ccol_char: {
570 0 : return ccol__typed_cmp(key_pair1->ptr, key_pair2->ptr, char);
571 : }
572 :
573 0 : case ccol_signed_char:
574 : case ccol_short:
575 : case ccol_int:
576 : case ccol_long:
577 : case ccol_long_long: {
578 0 : return cmp_signed_small(key_pair1->ptr, key_pair2->ptr, key_pair1->size);
579 : }
580 :
581 0 : case ccol_unsigned_char:
582 : case ccol_unsigned_short:
583 : case ccol_unsigned_int:
584 : case ccol_unsigned_long:
585 : case ccol_unsigned_long_long:
586 : case ccol_pointer: {
587 0 : return cmp_unsigned_small(key_pair1->ptr, key_pair2->ptr,
588 : key_pair1->size);
589 : }
590 :
591 74 : case ccol_float:
592 : case ccol_double:
593 : case ccol_long_double: {
594 74 : return cmp_float_small(cbm->key_type, key_pair1->ptr, key_pair2->ptr);
595 : }
596 :
597 1171 : case ccol_other_types:
598 : default: {
599 1171 : if (key_pair1->size == 0) return 0;
600 1168 : return memcmp(key_pair1->ptr, key_pair2->ptr, key_pair1->size);
601 : }
602 : }
603 : }
604 :
605 : // The body of cbmap_copy_bytes() and cbmap_move_bytes(), with fn being memcpy
606 : // or memmove. It copies n bytes from src to dst with a constant length for 1,
607 : // 2, 4, 8 and 16 bytes, which compile to one load and one store; other sizes
608 : // call the C library.
609 : #define CBMAP_SMALL_COPY_BODY(fn) \
610 : switch (n) { \
611 : case 1: \
612 : fn(dst, src, 1); \
613 : break; \
614 : case 2: \
615 : fn(dst, src, 2); \
616 : break; \
617 : case 4: \
618 : fn(dst, src, 4); \
619 : break; \
620 : case 8: \
621 : fn(dst, src, 8); \
622 : break; \
623 : case 16: \
624 : fn(dst, src, 16); \
625 : break; \
626 : default: \
627 : fn(dst, src, n); \
628 : break; \
629 : }
630 : // These copy n bytes of a key or value: cbmap_copy_bytes() for separate ranges,
631 : // cbmap_move_bytes() for ranges that may overlap. Node creation and updates use
632 : // them so the usual small sizes need no library call.
633 4025366 : static inline void cbmap_copy_bytes(void *restrict dst,
634 : const void *restrict src, size_t n) {
635 4025366 : CBMAP_SMALL_COPY_BODY(memcpy)
636 4025366 : }
637 8748 : static inline void cbmap_move_bytes(void *dst, const void *src, size_t n) {
638 8748 : CBMAP_SMALL_COPY_BODY(memmove)
639 8748 : }
640 : #undef CBMAP_SMALL_COPY_BODY
641 :
642 : // The typed loop of cbmap_find_node(): Reads the wanted key once, reads each
643 : // node's key at key_offset and compares with < and ==. The caller has checked
644 : // that the key has its type's width, so the read stays inside its bytes.
645 : #define CBMAP_FIND_TYPED(T) \
646 : do { \
647 : T cbmap_want_; \
648 : memcpy(&cbmap_want_, key_pair->ptr, sizeof(T)); \
649 : const size_t cbmap_off_ = cbm->key_offset; \
650 : bmap_node *cbmap_n_ = cbm->root; \
651 : while (cbmap_n_) { \
652 : T cbmap_have_; \
653 : memcpy(&cbmap_have_, (const char *)cbmap_n_ + cbmap_off_, sizeof(T)); \
654 : if (cbmap_want_ == cbmap_have_) return cbmap_n_; \
655 : cbmap_n_ = cbmap_want_ < cbmap_have_ ? cbmap_n_->left : cbmap_n_->right; \
656 : } \
657 : return NULL; \
658 : } while (0)
659 :
660 : // Gives the node holding key_pair, or NULL; the lookups and the accessor use
661 : // it. It picks the comparison once per call from cmp_kind. The caller has
662 : // checked the key size.
663 1220920 : static inline bmap_node *cbmap_find_node(cbmap cbm, const cmap_pair *key_pair) {
664 1220920 : switch (cbm->cmp_kind) {
665 12 : case CBMAP_CMP_CHAR:
666 35 : CBMAP_FIND_TYPED(char);
667 13 : case CBMAP_CMP_S8:
668 34 : CBMAP_FIND_TYPED(int8_t);
669 10 : case CBMAP_CMP_S16:
670 23 : CBMAP_FIND_TYPED(int16_t);
671 1220411 : case CBMAP_CMP_S32:
672 20587830 : CBMAP_FIND_TYPED(int32_t);
673 25 : case CBMAP_CMP_S64:
674 55 : CBMAP_FIND_TYPED(int64_t);
675 9 : case CBMAP_CMP_U8:
676 22 : CBMAP_FIND_TYPED(uint8_t);
677 9 : case CBMAP_CMP_U16:
678 20 : CBMAP_FIND_TYPED(uint16_t);
679 109 : case CBMAP_CMP_U32:
680 600 : CBMAP_FIND_TYPED(uint32_t);
681 26 : case CBMAP_CMP_U64:
682 59 : CBMAP_FIND_TYPED(uint64_t);
683 : default:
684 296 : break;
685 : }
686 296 : bmap_node *tracker = cbm->root;
687 1363 : while (tracker) {
688 1326 : int comparison = compare_keys(cbm, key_pair, &tracker->key_pair);
689 1326 : if (comparison == 0) return tracker;
690 1067 : tracker = comparison < 0 ? tracker->left : tracker->right;
691 : }
692 : return NULL;
693 : }
694 : #undef CBMAP_FIND_TYPED
695 :
696 : // The typed loop of cbmap_descend_with_path(), like CBMAP_FIND_TYPED but
697 : // recording the path.
698 : #define CBMAP_DESCEND_TYPED(T) \
699 : do { \
700 : T cbmap_want_; \
701 : memcpy(&cbmap_want_, key_pair->ptr, sizeof(T)); \
702 : const size_t cbmap_off_ = cbm->key_offset; \
703 : while (current) { \
704 : T cbmap_have_; \
705 : memcpy(&cbmap_have_, (const char *)current + cbmap_off_, sizeof(T)); \
706 : if (cbmap_want_ == cbmap_have_) break; \
707 : ccol__assert(len < CBMAP_MAX_TREE_HEIGHT); \
708 : path[len++] = (node_stack_entry){current, link}; \
709 : if (cbmap_want_ < cbmap_have_) { \
710 : link = ¤t->left; \
711 : current = current->left; \
712 : } else { \
713 : link = ¤t->right; \
714 : current = current->right; \
715 : } \
716 : } \
717 : } while (0)
718 :
719 : // Walks from the root towards key_pair and records each node it passes in path,
720 : // with the link that points at it; insert and delete need that path to
721 : // rebalance upward without recursion. Gives the node holding the key or NULL,
722 : // the path length in *path_len_out, and in *link_out that node's link or the
723 : // empty link where the key belongs.
724 3045396 : static inline __attribute__((always_inline)) bmap_node *cbmap_descend_with_path(
725 : cbmap cbm, const cmap_pair *key_pair, node_stack_entry *path,
726 : size_t *path_len_out, bmap_node ***link_out) {
727 3045396 : bmap_node *current = cbm->root;
728 3045396 : bmap_node **link = &cbm->root;
729 3045396 : size_t len = 0;
730 3045396 : switch (cbm->cmp_kind) {
731 16 : case CBMAP_CMP_CHAR:
732 53 : CBMAP_DESCEND_TYPED(char);
733 : break;
734 16 : case CBMAP_CMP_S8:
735 49 : CBMAP_DESCEND_TYPED(int8_t);
736 : break;
737 7 : case CBMAP_CMP_S16:
738 19 : CBMAP_DESCEND_TYPED(int16_t);
739 : break;
740 3044943 : case CBMAP_CMP_S32:
741 54686351 : CBMAP_DESCEND_TYPED(int32_t);
742 : break;
743 17 : case CBMAP_CMP_S64:
744 46 : CBMAP_DESCEND_TYPED(int64_t);
745 : break;
746 6 : case CBMAP_CMP_U8:
747 19 : CBMAP_DESCEND_TYPED(uint8_t);
748 : break;
749 6 : case CBMAP_CMP_U16:
750 16 : CBMAP_DESCEND_TYPED(uint16_t);
751 : break;
752 105 : case CBMAP_CMP_U32:
753 688 : CBMAP_DESCEND_TYPED(uint32_t);
754 : break;
755 17 : case CBMAP_CMP_U64:
756 45 : CBMAP_DESCEND_TYPED(uint64_t);
757 : break;
758 : default:
759 1340 : while (current) {
760 1123 : int comparison = compare_keys(cbm, key_pair, ¤t->key_pair);
761 1123 : if (comparison == 0) break;
762 1077 : ccol__assert(len < CBMAP_MAX_TREE_HEIGHT);
763 1077 : path[len++] = (node_stack_entry){current, link};
764 1077 : if (comparison > 0) {
765 844 : link = ¤t->right;
766 844 : current = current->right;
767 : } else {
768 233 : link = ¤t->left;
769 233 : current = current->left;
770 : }
771 : }
772 : break;
773 : }
774 3045396 : *path_len_out = len;
775 3045396 : *link_out = link;
776 3045396 : return current;
777 : }
778 : #undef CBMAP_DESCEND_TYPED
779 :
780 : // Creates a detached node holding copies of key_pair and val_pair, for insert.
781 : // It allocates one block for the node, the key at key_offset and the value at
782 : // the next max_align_t boundary; each term of the size is checked against what
783 : // remains, so the sum can't wrap. The key lives in the node, so it's never
784 : // freed on its own and never moves; a removal relinks the replacement node
785 : // instead of copying it. An empty key or value never goes to the allocator
786 : // (malloc(0) may give NULL) and is stored as {NULL, 0}. Gives NULL when the
787 : // allocation fails.
788 2012672 : static bmap_node *create_new_node(cbmap cbm, const cmap_pair *key_pair,
789 : const cmap_pair *val_pair) {
790 2012672 : size_t key_offset = cbm->key_offset;
791 2012672 : if (key_pair->size > SIZE_MAX - key_offset - CBMAP_NODE_VAL_ALIGN) {
792 : return NULL;
793 : }
794 2012672 : size_t val_offset =
795 2012672 : CBMAP_ALIGN_UP_TO(key_offset + key_pair->size, CBMAP_NODE_VAL_ALIGN);
796 2012672 : if (val_pair->size > SIZE_MAX - val_offset) {
797 : return NULL;
798 : }
799 4025344 : bmap_node *new_node =
800 2012672 : ccol__mem_alloc(cbm->m_procs, val_offset + val_pair->size);
801 2012672 : if (!new_node) {
802 : return NULL;
803 : }
804 :
805 4025344 : new_node->key_pair.ptr =
806 2012672 : (key_pair->size > 0) ? (char *)new_node + key_offset : NULL;
807 4025344 : new_node->val_pair.ptr =
808 2012672 : (val_pair->size > 0) ? (char *)new_node + val_offset : NULL;
809 2012672 : new_node->val_is_external = false;
810 :
811 2012672 : if (key_pair->size > 0) {
812 2012671 : cbmap_copy_bytes(new_node->key_pair.ptr, key_pair->ptr, key_pair->size);
813 : }
814 2012672 : new_node->key_pair.size = key_pair->size;
815 2012672 : if (val_pair->size > 0) {
816 2012671 : cbmap_copy_bytes(new_node->val_pair.ptr, val_pair->ptr, val_pair->size);
817 : }
818 2012672 : new_node->val_pair.size = val_pair->size;
819 :
820 2012672 : new_node->left = NULL;
821 2012672 : new_node->right = NULL;
822 2012672 : new_node->height = 1;
823 :
824 2012672 : return new_node;
825 : }
826 :
827 : // Gives the larger of x and y, for the height computation.
828 12582077 : static size_t maximum(size_t x, size_t y) {
829 12582077 : if (x >= y) {
830 : return x;
831 : }
832 : return y;
833 : }
834 :
835 : // Replaces the value of a node already in the map, for an insert of an existing
836 : // key. On success it sets *result to ccol_key_already_present; on a failed
837 : // allocation it changes nothing and leaves *result alone. A value of the same
838 : // size is copied in place with memmove, because val_pair can point at the
839 : // stored value (from cbstmap_get_elem_ref()). Another size goes into a new
840 : // buffer before the old one is freed, for the same reason, and never moves back
841 : // into the node, whose room isn't recorded. Size 0 frees any buffer and stores
842 : // {NULL, 0}, since realloc(p, 0) can't tell a free from a failure.
843 8757 : static void update_bmap_node_value(cbmap cbm, bmap_node *node,
844 : const cmap_pair *val_pair,
845 : ccol_retval *result) {
846 8757 : if (node->val_pair.size != val_pair->size) {
847 9 : if (val_pair->size == 0) {
848 1 : if (node->val_is_external) {
849 0 : ccol__mem_free(cbm->m_procs, node->val_pair.ptr);
850 : }
851 1 : node->val_pair.ptr = NULL;
852 1 : node->val_pair.size = 0;
853 1 : node->val_is_external = false;
854 1 : *result = ccol_key_already_present;
855 1 : return;
856 : }
857 :
858 8 : void *new_ptr = ccol__mem_alloc(cbm->m_procs, val_pair->size);
859 8 : if (!new_ptr) {
860 : return;
861 : }
862 8 : memcpy(new_ptr, val_pair->ptr, val_pair->size);
863 8 : if (node->val_is_external) {
864 4 : ccol__mem_free(cbm->m_procs, node->val_pair.ptr);
865 : }
866 8 : node->val_pair.ptr = new_ptr;
867 8 : node->val_pair.size = val_pair->size;
868 8 : node->val_is_external = true;
869 8 : *result = ccol_key_already_present;
870 8 : return;
871 : }
872 8748 : if (node->val_pair.ptr != val_pair->ptr && val_pair->size > 0) {
873 8748 : cbmap_move_bytes(node->val_pair.ptr, val_pair->ptr, val_pair->size);
874 : }
875 8748 : *result = ccol_key_already_present;
876 : }
877 :
878 : // Gives the height of node, 0 for NULL (a leaf is 1), so the balance code needs
879 : // no NULL checks.
880 199018011 : static size_t node_height(bmap_node *node) {
881 199018011 : if (!node) {
882 : return 0;
883 : }
884 :
885 113071578 : return node->height;
886 : }
887 :
888 : // Gives right height minus left height, which the rebalance and the validator
889 : // test against [-1, 1].
890 86929075 : static int node_balance(bmap_node *node) {
891 86929075 : if (!node) {
892 : return 0;
893 : }
894 :
895 37017174 : return (int)node_height(node->right) - (int)node_height(node->left);
896 : }
897 :
898 : // Sets node->height from its children, after every structural change. The cast
899 : // to one byte can't truncate; the _Static_assert on CBMAP_MAX_TREE_HEIGHT
900 : // guarantees it.
901 12582077 : static void recalculate_node_height(bmap_node *node) {
902 12582077 : if (!node) {
903 : return;
904 : }
905 :
906 22656362 : node->height =
907 17617433 : (uint8_t)(maximum(node_height(node->left), node_height(node->right)) + 1);
908 : }
909 :
910 : // Updates the height of parent and restores the AVL rule there with a left,
911 : // right, right-left or left-right rotation when needed. Insert, delete and the
912 : // extreme detach call it on every ancestor. Gives the subtree's new root;
913 : // heights are recomputed bottom-up after each rotation.
914 7556665 : static bmap_node *check_node_balance(bmap_node *parent) {
915 7556665 : recalculate_node_height(parent);
916 7556665 : int balance = node_balance(parent);
917 :
918 7556665 : if (balance > 1 || balance < -1) {
919 2509294 : bmap_node *p = parent;
920 :
921 2509294 : if (balance > 1) {
922 4009538 : if (node_balance(parent->right) >= 0 || !(parent->right->left)) {
923 2504251 : parent = parent->right;
924 2504251 : p->right = parent->left;
925 2504251 : parent->left = p;
926 2504251 : recalculate_node_height(p);
927 2504251 : recalculate_node_height(parent);
928 : } else {
929 1502 : bmap_node *rl_left = parent->right->left->left;
930 1502 : bmap_node *rl_right = parent->right->left->right;
931 1502 : parent = parent->right->left;
932 1502 : parent->left = p;
933 1502 : parent->right = p->right;
934 1502 : parent->right->left = rl_right;
935 1502 : parent->left->right = rl_left;
936 1502 : recalculate_node_height(parent->left);
937 1502 : recalculate_node_height(parent->right);
938 1502 : recalculate_node_height(parent);
939 : }
940 : } else {
941 7082 : if (node_balance(parent->left) <= 0 || !(parent->left->right)) {
942 1931 : parent = parent->left;
943 1931 : p->left = parent->right;
944 1931 : parent->right = p;
945 1931 : recalculate_node_height(p);
946 1931 : recalculate_node_height(parent);
947 : } else {
948 1610 : bmap_node *lr_left = parent->left->right->left;
949 1610 : bmap_node *lr_right = parent->left->right->right;
950 1610 : parent = parent->left->right;
951 1610 : parent->right = p;
952 1610 : parent->left = p->left;
953 1610 : parent->left->right = lr_left;
954 1610 : parent->right->left = lr_right;
955 1610 : recalculate_node_height(parent->left);
956 1610 : recalculate_node_height(parent->right);
957 1610 : recalculate_node_height(parent);
958 : }
959 : }
960 : }
961 :
962 7556665 : int final_balance = node_balance(parent);
963 7556665 : if (final_balance > 1 || final_balance < -1) {
964 0 : ccol__assert(false);
965 : }
966 7556665 : return parent;
967 : }
968 :
969 : // Detaches the smallest (max false) or largest (max true) node of the subtree
970 : // at root, for the replacement of a deleted node with two children. The node
971 : // goes to *extreme, its only child takes its place, the path is rebalanced
972 : // bottom-up, and it gives the new subtree root. The path is a fixed array, so
973 : // the delete can't fail for lack of memory.
974 3712 : static bmap_node *cbmap_detach_extreme_iter(bmap_node *root, bool max,
975 : bmap_node **extreme) {
976 3712 : if (!root) {
977 0 : ccol__assert(false);
978 : }
979 :
980 : node_stack_entry path[CBMAP_MAX_TREE_HEIGHT];
981 : size_t path_len = 0;
982 :
983 : bmap_node *current = root;
984 : bmap_node **parent_link = NULL;
985 :
986 8484 : while (true) {
987 8484 : if (max) {
988 1883 : if (current->right) {
989 1131 : ccol__assert(path_len < CBMAP_MAX_TREE_HEIGHT);
990 1131 : path[path_len++] = (node_stack_entry){current, parent_link};
991 1131 : parent_link = &(current->right);
992 1131 : current = current->right;
993 : } else {
994 752 : *extreme = current;
995 752 : break;
996 : }
997 : } else {
998 6601 : if (current->left) {
999 3641 : ccol__assert(path_len < CBMAP_MAX_TREE_HEIGHT);
1000 3641 : path[path_len++] = (node_stack_entry){current, parent_link};
1001 3641 : parent_link = &(current->left);
1002 3641 : current = current->left;
1003 : } else {
1004 2960 : *extreme = current;
1005 2960 : break;
1006 : }
1007 : }
1008 : }
1009 :
1010 3712 : bmap_node *replacement = max ? current->left : current->right;
1011 :
1012 3712 : if (path_len == 0) {
1013 : return replacement;
1014 : }
1015 :
1016 2451 : node_stack_entry last_entry = path[path_len - 1];
1017 2451 : if (max) {
1018 615 : last_entry.node->right = replacement;
1019 : } else {
1020 1836 : last_entry.node->left = replacement;
1021 : }
1022 :
1023 7223 : for (size_t i = path_len; i-- > 0;) {
1024 4772 : node_stack_entry entry = path[i];
1025 4772 : bmap_node *balanced = check_node_balance(entry.node);
1026 :
1027 4772 : if (entry.parent_link) {
1028 2321 : *(entry.parent_link) = balanced;
1029 : } else {
1030 : root = balanced;
1031 : }
1032 : }
1033 :
1034 : return root;
1035 : }
1036 :
1037 : // Says whether key_pair has a size the map's key type allows; every raw entry
1038 : // point checks it. A fixed-width key must have exactly its type's width, or the
1039 : // prefix and length order of compare_keys() would make it a different key that
1040 : // no correct lookup finds, and a custom comparator would read past it. A string
1041 : // key needs at least 1 byte (its NUL); a ccol_other_types key may have any
1042 : // size, 0 included.
1043 5266505 : static inline bool key_size_is_valid_for_type(cbmap cbm,
1044 : const cmap_pair *key_pair) {
1045 1220795 : size_t fixed_width = ccol_fixed_width_data_type_size(cbm->key_type);
1046 5266505 : if (fixed_width != 0) {
1047 5266188 : return key_pair->size == fixed_width;
1048 : }
1049 317 : return key_pair->size != 0 || cbm->key_type != ccol_string;
1050 : }
1051 :
1052 : // Says whether the bytes of a caller's pair can be read; every raw entry point
1053 : // checks it so a bad pair is refused instead of dereferenced. A NULL ptr with a
1054 : // non-zero size fails; size 0 passes, with or without a ptr.
1055 7287959 : static inline bool pair_bytes_are_readable(const cmap_pair *pair) {
1056 7287959 : return pair->ptr != NULL || pair->size == 0;
1057 : }
1058 :
1059 : // Inserts a copy of the key and the value, or replaces the value of a key that
1060 : // is already there (ccol_key_already_present). cbmap_insert() and raw callers
1061 : // use it. It descends with a fixed path array, links a new node and rebalances
1062 : // upward, updating root and elem_count. The capacity check runs only for a new
1063 : // key, so an update in a full map works. The rebalance stops at the first
1064 : // ancestor whose height didn't change, or after the one rotation an insert can
1065 : // need, since nothing above changes.
1066 2021452 : ccol_retval cbstmap_insert_elem(cbmap cbm, const cmap_pair *key_pair,
1067 : const cmap_pair *val_pair) {
1068 2021452 : if (!cbm) {
1069 0 : ccol__assert(false);
1070 : }
1071 :
1072 4042901 : if (!key_pair || !val_pair || !pair_bytes_are_readable(key_pair) ||
1073 2021448 : !pair_bytes_are_readable(val_pair)) {
1074 : return ccol_invalid_args;
1075 : }
1076 :
1077 4042728 : if (!key_size_is_valid_for_type(cbm, key_pair)) {
1078 : return ccol_invalid_args;
1079 : }
1080 :
1081 2021429 : if (!cbm->root) {
1082 161 : cbm->root = create_new_node(cbm, key_pair, val_pair);
1083 161 : if (!cbm->root) {
1084 : return ccol_not_enough_memory;
1085 : }
1086 161 : cbm->elem_count++;
1087 161 : return ccol_success;
1088 : }
1089 :
1090 2021268 : node_stack_entry path[CBMAP_MAX_TREE_HEIGHT];
1091 2021268 : size_t path_len = 0;
1092 2021268 : bmap_node **parent_link = NULL;
1093 2021268 : ccol_retval result = ccol_not_enough_memory;
1094 :
1095 2021268 : bmap_node *existing =
1096 2021268 : cbmap_descend_with_path(cbm, key_pair, path, &path_len, &parent_link);
1097 2021268 : if (existing) {
1098 8757 : update_bmap_node_value(cbm, existing, val_pair, &result);
1099 8757 : return result;
1100 : }
1101 :
1102 2012511 : if (cbm->elem_count == ccol_max_elem_count) {
1103 : return ccol_container_full;
1104 : }
1105 :
1106 2012511 : bmap_node *new_node = create_new_node(cbm, key_pair, val_pair);
1107 2012511 : if (!new_node) {
1108 : return ccol_not_enough_memory;
1109 : }
1110 :
1111 2012511 : *parent_link = new_node;
1112 2012511 : result = ccol_success;
1113 :
1114 6034252 : for (size_t i = path_len; i-- > 0;) {
1115 6033961 : node_stack_entry entry = path[i];
1116 6033961 : size_t height_before = entry.node->height;
1117 6033961 : bmap_node *balanced = check_node_balance(entry.node);
1118 :
1119 6033961 : if (entry.parent_link) {
1120 6033961 : *(entry.parent_link) = balanced;
1121 : } else {
1122 0 : cbm->root = balanced;
1123 : }
1124 :
1125 6033961 : if (balanced != entry.node || balanced->height == height_before) {
1126 : break;
1127 : }
1128 : }
1129 :
1130 2012511 : cbm->elem_count++;
1131 2012511 : return result;
1132 : }
1133 :
1134 : // Looks up key_pair and copies its value into target_buf, for callers that want
1135 : // their own copy. The sizes must match exactly, so nothing is truncated. Gives
1136 : // ccol_success, ccol_key_not_found or ccol_invalid_args.
1137 133 : ccol_retval cbstmap_get_elem_copy(cbmap cbm, const cmap_pair *key_pair,
1138 : void *target_buf, size_t target_buf_size) {
1139 133 : if (!cbm) {
1140 0 : ccol__assert(false);
1141 : }
1142 :
1143 265 : if (!key_pair || !pair_bytes_are_readable(key_pair)) {
1144 : return ccol_invalid_args;
1145 : }
1146 :
1147 131 : if (!target_buf && target_buf_size != 0) {
1148 : return ccol_invalid_args;
1149 : }
1150 :
1151 260 : if (!key_size_is_valid_for_type(cbm, key_pair)) {
1152 : return ccol_invalid_args;
1153 : }
1154 :
1155 128 : bmap_node *tracker = cbmap_find_node(cbm, key_pair);
1156 128 : if (!tracker) {
1157 : return ccol_key_not_found;
1158 : }
1159 26 : if (target_buf_size != tracker->val_pair.size) {
1160 : return ccol_invalid_args;
1161 : }
1162 25 : if (target_buf_size > 0) {
1163 24 : cbmap_copy_bytes(target_buf, tracker->val_pair.ptr, target_buf_size);
1164 : }
1165 : return ccol_success;
1166 : }
1167 :
1168 : // Checks key_pair and finds its node; cbstmap_get_elem_ref() and
1169 : // cbstmap__get_val_accessor() share it. Gives the node, or NULL with the
1170 : // failure code in *ret.
1171 1220798 : static bmap_node *cbmap_lookup_checked(cbmap cbm, const cmap_pair *key_pair,
1172 : ccol_retval *ret) {
1173 2441594 : if (!key_pair || !pair_bytes_are_readable(key_pair) ||
1174 1220654 : !key_size_is_valid_for_type(cbm, key_pair)) {
1175 6 : *ret = ccol_invalid_args;
1176 6 : return NULL;
1177 : }
1178 1220792 : bmap_node *tracker = cbmap_find_node(cbm, key_pair);
1179 1220792 : *ret = tracker ? ccol_success : ccol_key_not_found;
1180 1220792 : return tracker;
1181 : }
1182 :
1183 : // Looks up key_pair and fills val_pair with the address and size of its value,
1184 : // so callers can read or edit it in place; cbmap_get() and cbmap_get_ptr() use
1185 : // it. On failure val_pair gets {NULL, 0}.
1186 1220788 : ccol_retval cbstmap_get_elem_ref(cbmap cbm, const cmap_pair *key_pair,
1187 : cmap_pair *val_pair) {
1188 1220788 : if (!cbm) {
1189 0 : ccol__assert(false);
1190 : }
1191 :
1192 1220788 : if (!val_pair) {
1193 : return ccol_invalid_args;
1194 : }
1195 :
1196 1220787 : ccol_retval ret;
1197 1220787 : bmap_node *tracker = cbmap_lookup_checked(cbm, key_pair, &ret);
1198 1220787 : if (!tracker) {
1199 218432 : val_pair->ptr = NULL;
1200 218432 : val_pair->size = 0;
1201 218432 : return ret;
1202 : }
1203 1002355 : *val_pair = tracker->val_pair;
1204 1002355 : return ccol_success;
1205 : }
1206 :
1207 : // Looks up key_pair and hands out the address of its value accessor, for the
1208 : // string arm of cbmap_get_ptr(): The accessor's ptr field is the only char *
1209 : // object of a string value. *val_accessor is NULL on failure.
1210 11 : ccol_retval cbstmap__get_val_accessor(cbmap cbm, const cmap_pair *key_pair,
1211 : const cmap_pair **val_accessor) {
1212 11 : if (!cbm) {
1213 0 : ccol__assert(false);
1214 : }
1215 11 : if (!val_accessor) {
1216 : return ccol_invalid_args;
1217 : }
1218 :
1219 11 : ccol_retval ret;
1220 11 : bmap_node *tracker = cbmap_lookup_checked(cbm, key_pair, &ret);
1221 11 : *val_accessor = tracker ? &tracker->val_pair : NULL;
1222 11 : return ret;
1223 : }
1224 :
1225 : // Frees parent and gives the root of the subtree that replaces it, for delete.
1226 : // With two children the taller side gives up its extreme node (the right
1227 : // minimum on a tie), which keeps the order and needs the fewest rotations.
1228 1011328 : static bmap_node *perform_element_removal(cbmap cbm, bmap_node *parent) {
1229 1011328 : bmap_node *left = parent->left;
1230 1011328 : bmap_node *right = parent->right;
1231 1011328 : destroy_bmap_node(cbm, parent);
1232 :
1233 1011328 : if (!left) {
1234 : parent = right;
1235 4658 : } else if (!right) {
1236 : parent = left;
1237 : } else {
1238 3712 : if (right->height >= left->height) {
1239 2960 : bmap_node *right_min = NULL;
1240 2960 : right = cbmap_detach_extreme_iter(right, false, &right_min);
1241 2960 : parent = right_min;
1242 2960 : parent->right = right;
1243 2960 : parent->left = left;
1244 5093 : recalculate_node_height(parent);
1245 : } else {
1246 752 : bmap_node *left_max = NULL;
1247 752 : left = cbmap_detach_extreme_iter(left, true, &left_max);
1248 752 : parent = left_max;
1249 752 : parent->right = right;
1250 752 : parent->left = left;
1251 1504 : recalculate_node_height(parent);
1252 : }
1253 : }
1254 :
1255 1011328 : return parent;
1256 : }
1257 :
1258 : // Deletes key_pair and its value; cbmap_remove() and raw callers use it. Gives
1259 : // ccol_success, ccol_key_not_found or ccol_invalid_args. It descends with a
1260 : // fixed path array, removes the node and rebalances upward, updating root and
1261 : // elem_count. A rotation after a delete can lower a subtree, so the walk stops
1262 : // on an unchanged height, not on whether a rotation happened.
1263 2024135 : ccol_retval cbstmap_remove_elem(cbmap cbm, const cmap_pair *key_pair) {
1264 2024135 : if (!cbm) {
1265 0 : ccol__assert(false);
1266 : }
1267 :
1268 4048269 : if (!key_pair || !pair_bytes_are_readable(key_pair)) {
1269 : return ccol_invalid_args;
1270 : }
1271 :
1272 4048261 : if (!key_size_is_valid_for_type(cbm, key_pair)) {
1273 : return ccol_invalid_args;
1274 : }
1275 :
1276 2024131 : if (!cbm->root) {
1277 : return ccol_key_not_found;
1278 : }
1279 :
1280 1024128 : node_stack_entry path[CBMAP_MAX_TREE_HEIGHT];
1281 1024128 : size_t path_len = 0;
1282 1024128 : bmap_node **parent_link = NULL;
1283 1024128 : ccol_retval result = ccol_key_not_found;
1284 :
1285 1024128 : bmap_node *current =
1286 1024128 : cbmap_descend_with_path(cbm, key_pair, path, &path_len, &parent_link);
1287 1024128 : if (current) {
1288 1011328 : bmap_node *replacement = perform_element_removal(cbm, current);
1289 1011328 : *parent_link = replacement;
1290 1011328 : result = ccol_success;
1291 : }
1292 :
1293 1011328 : if (result == ccol_success) {
1294 1518085 : for (size_t i = path_len; i-- > 0;) {
1295 1517932 : node_stack_entry entry = path[i];
1296 1517932 : size_t height_before = entry.node->height;
1297 1517932 : bmap_node *balanced = check_node_balance(entry.node);
1298 :
1299 1517932 : if (entry.parent_link) {
1300 1517932 : *(entry.parent_link) = balanced;
1301 : } else {
1302 0 : cbm->root = balanced;
1303 : }
1304 :
1305 1517932 : if (balanced->height == height_before) {
1306 : break;
1307 : }
1308 : }
1309 :
1310 1011328 : cbm->elem_count--;
1311 : }
1312 :
1313 : return result;
1314 : }
1315 :
1316 : #ifdef RUNNING_UNIT_TESTS
1317 : // Checks the height and the balance of every node, for the tests, which can't
1318 : // see the opaque nodes. It walks iteratively over a fixed stack. Only a pass or
1319 : // fail leaves this file, so no node pointer crosses the API.
1320 40063 : bool cbmap_debug_validate_avl(cbmap cbm) {
1321 40063 : if (!cbm || !cbm->root) {
1322 : return true;
1323 : }
1324 :
1325 40060 : bmap_node *stack[CBMAP_MAX_TREE_HEIGHT];
1326 40060 : size_t sp = 0;
1327 40060 : stack[sp++] = cbm->root;
1328 :
1329 69386571 : while (sp > 0) {
1330 69306451 : bmap_node *node = stack[--sp];
1331 :
1332 138612902 : size_t expected_height =
1333 138572842 : 1 + (node_height(node->left) > node_height(node->right)
1334 10989857 : ? node_height(node->left)
1335 58316594 : : node_height(node->right));
1336 69306451 : if (node->height != expected_height) {
1337 : return false;
1338 : }
1339 :
1340 69306451 : int balance = node_balance(node);
1341 69306451 : if (balance > 1 || balance < -1) {
1342 : return false;
1343 : }
1344 :
1345 69306451 : if (node->left) {
1346 34499218 : if (sp >= CBMAP_MAX_TREE_HEIGHT) return false;
1347 34499218 : stack[sp++] = node->left;
1348 : }
1349 69306451 : if (node->right) {
1350 34767173 : if (sp >= CBMAP_MAX_TREE_HEIGHT) return false;
1351 34767173 : stack[sp++] = node->right;
1352 : }
1353 : }
1354 :
1355 : return true;
1356 : }
1357 : #endif
|