Coverage Report

Created: 2026-06-07 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/croaring/src/roaring64.c
Line
Count
Source
1
#include <assert.h>
2
#include <stdarg.h>
3
#include <stdint.h>
4
#include <string.h>
5
6
#include <roaring/art/art.h>
7
#include <roaring/portability.h>
8
#include <roaring/roaring64.h>
9
10
// For serialization / deserialization
11
#include <roaring/containers/array.h>
12
#include <roaring/containers/bitset.h>
13
#include <roaring/containers/run.h>
14
#include <roaring/roaring.h>
15
#include <roaring/roaring_array.h>
16
// containers.h last to avoid conflict with ROARING_CONTAINER_T.
17
#include <roaring/containers/containers.h>
18
19
#define CROARING_ALIGN_BUF(buf, alignment)          \
20
0
    (char *)(((uintptr_t)(buf) + ((alignment)-1)) & \
21
0
             (ptrdiff_t)(~((alignment)-1)))
22
23
0
#define CROARING_BITSET_ALIGNMENT 64
24
25
#ifdef __cplusplus
26
using namespace ::roaring::internal;
27
28
extern "C" {
29
namespace roaring {
30
namespace api {
31
#endif
32
33
// TODO: Copy on write.
34
// TODO: Error on failed allocation.
35
36
typedef struct roaring64_bitmap_s {
37
    art_t art;
38
    uint8_t flags;
39
    uint64_t first_free;
40
    uint64_t capacity;
41
    container_t **containers;
42
} roaring64_bitmap_t;
43
44
// Leaf type of the ART used to keep the high 48 bits of each entry.
45
// Low 8 bits: typecode
46
// High 56 bits: container index
47
typedef roaring64_leaf_t leaf_t;
48
49
// Iterator struct to hold iteration state.
50
typedef struct roaring64_iterator_s {
51
    const roaring64_bitmap_t *r;
52
    art_iterator_t art_it;
53
    roaring_container_iterator_t container_it;
54
    uint64_t high48;  // Key that art_it points to.
55
56
    uint64_t value;
57
    bool has_value;
58
59
    // If has_value is false, then the iterator is saturated. This field
60
    // indicates the direction of saturation. If true, there are no more values
61
    // in the forward direction. If false, there are no more values in the
62
    // backward direction.
63
    bool saturated_forward;
64
} roaring64_iterator_t;
65
66
0
static inline bool is_frozen64(const roaring64_bitmap_t *r) {
67
0
    return r->flags & ROARING_FLAG_FROZEN;
68
0
}
69
70
// Splits the given uint64 key into high 48 bit and low 16 bit components.
71
// Expects high48_out to be of length ART_KEY_BYTES.
72
0
static inline uint16_t split_key(uint64_t key, uint8_t high48_out[]) {
73
0
    uint64_t tmp = croaring_htobe64(key);
74
0
    memcpy(high48_out, (uint8_t *)(&tmp), ART_KEY_BYTES);
75
0
    return (uint16_t)key;
76
0
}
77
78
// Recombines the high 48 bit and low 16 bit components into a uint64 key.
79
// Expects high48_out to be of length ART_KEY_BYTES.
80
0
static inline uint64_t combine_key(const uint8_t high48[], uint16_t low16) {
81
0
    uint64_t result = 0;
82
0
    memcpy((uint8_t *)(&result), high48, ART_KEY_BYTES);
83
0
    return croaring_be64toh(result) | low16;
84
0
}
85
86
0
static inline uint64_t minimum(uint64_t a, uint64_t b) {
87
0
    return (a < b) ? a : b;
88
0
}
89
90
0
static inline leaf_t create_leaf(uint64_t container_index, uint8_t typecode) {
91
0
    return (container_index << 8) | typecode;
92
0
}
93
94
0
static inline uint8_t get_typecode(leaf_t leaf) { return (uint8_t)leaf; }
95
96
0
static inline uint64_t get_index(leaf_t leaf) { return leaf >> 8; }
97
98
static inline container_t *get_container(const roaring64_bitmap_t *r,
99
0
                                         leaf_t leaf) {
100
0
    return r->containers[get_index(leaf)];
101
0
}
102
103
// Replaces the container of `leaf` with the given container. Returns the
104
// modified leaf for convenience.
105
static inline leaf_t replace_container(roaring64_bitmap_t *r, leaf_t *leaf,
106
                                       container_t *container,
107
0
                                       uint8_t typecode) {
108
0
    uint64_t index = get_index(*leaf);
109
0
    r->containers[index] = container;
110
0
    *leaf = create_leaf(index, typecode);
111
0
    return *leaf;
112
0
}
113
114
/**
115
 * Extends the array of container pointers.
116
 */
117
0
static void extend_containers(roaring64_bitmap_t *r) {
118
0
    uint64_t size = r->first_free;
119
0
    if (size < r->capacity) {
120
0
        return;
121
0
    }
122
0
    uint64_t new_capacity;
123
0
    if (r->capacity == 0) {
124
0
        new_capacity = 2;
125
0
    } else if (r->capacity < 1024) {
126
0
        new_capacity = 2 * r->capacity;
127
0
    } else {
128
0
        new_capacity = 5 * r->capacity / 4;
129
0
    }
130
0
    uint64_t increase = new_capacity - r->capacity;
131
0
    r->containers = (container_t **)roaring_realloc(
132
0
        r->containers, new_capacity * sizeof(container_t *));
133
0
    memset(r->containers + r->capacity, 0, increase * sizeof(container_t *));
134
0
    r->capacity = new_capacity;
135
0
}
136
137
0
static uint64_t next_free_container_idx(const roaring64_bitmap_t *r) {
138
0
    for (uint64_t i = r->first_free + 1; i < r->capacity; ++i) {
139
0
        if (r->containers[i] == NULL) {
140
0
            return i;
141
0
        }
142
0
    }
143
0
    return r->capacity;
144
0
}
145
146
0
static uint64_t allocate_index(roaring64_bitmap_t *r) {
147
0
    uint64_t first_free = r->first_free;
148
0
    if (first_free == r->capacity) {
149
0
        extend_containers(r);
150
0
    }
151
0
    r->first_free = next_free_container_idx(r);
152
0
    return first_free;
153
0
}
154
155
static leaf_t add_container(roaring64_bitmap_t *r, container_t *container,
156
0
                            uint8_t typecode) {
157
0
    uint64_t index = allocate_index(r);
158
0
    r->containers[index] = container;
159
0
    return create_leaf(index, typecode);
160
0
}
161
162
0
static void remove_container(roaring64_bitmap_t *r, leaf_t leaf) {
163
0
    uint64_t index = get_index(leaf);
164
0
    r->containers[index] = NULL;
165
0
    if (index < r->first_free) {
166
0
        r->first_free = index;
167
0
    }
168
0
}
169
170
// Copies the container referenced by `leaf` from `r1` to `r2`.
171
static inline leaf_t copy_leaf_container(const roaring64_bitmap_t *r1,
172
0
                                         roaring64_bitmap_t *r2, leaf_t leaf) {
173
0
    uint8_t typecode = get_typecode(leaf);
174
    // get_copy_of_container modifies the typecode passed in.
175
0
    container_t *container = get_copy_of_container(
176
0
        get_container(r1, leaf), &typecode, /*copy_on_write=*/false);
177
0
    return add_container(r2, container, typecode);
178
0
}
179
180
static inline int compare_high48(art_key_chunk_t key1[],
181
0
                                 art_key_chunk_t key2[]) {
182
0
    return art_compare_keys(key1, key2);
183
0
}
184
185
static inline bool roaring64_iterator_init_at_leaf_first(
186
0
    roaring64_iterator_t *it) {
187
0
    it->high48 = combine_key(it->art_it.key, 0);
188
0
    leaf_t leaf = (leaf_t)*it->art_it.value;
189
0
    uint16_t low16 = 0;
190
0
    it->container_it = container_init_iterator(get_container(it->r, leaf),
191
0
                                               get_typecode(leaf), &low16);
192
0
    it->value = it->high48 | low16;
193
0
    return (it->has_value = true);
194
0
}
195
196
static inline bool roaring64_iterator_init_at_leaf_last(
197
0
    roaring64_iterator_t *it) {
198
0
    it->high48 = combine_key(it->art_it.key, 0);
199
0
    leaf_t leaf = (leaf_t)*it->art_it.value;
200
0
    uint16_t low16 = 0;
201
0
    it->container_it = container_init_iterator_last(get_container(it->r, leaf),
202
0
                                                    get_typecode(leaf), &low16);
203
0
    it->value = it->high48 | low16;
204
0
    return (it->has_value = true);
205
0
}
206
207
static inline roaring64_iterator_t *roaring64_iterator_init_at(
208
0
    const roaring64_bitmap_t *r, roaring64_iterator_t *it, bool first) {
209
0
    it->r = r;
210
0
    it->art_it = art_init_iterator((art_t *)&r->art, first);
211
0
    it->has_value = it->art_it.value != NULL;
212
0
    if (it->has_value) {
213
0
        if (first) {
214
0
            roaring64_iterator_init_at_leaf_first(it);
215
0
        } else {
216
0
            roaring64_iterator_init_at_leaf_last(it);
217
0
        }
218
0
    } else {
219
0
        it->saturated_forward = first;
220
0
    }
221
0
    return it;
222
0
}
223
224
0
roaring64_bitmap_t *roaring64_bitmap_create(void) {
225
0
    roaring64_bitmap_t *r =
226
0
        (roaring64_bitmap_t *)roaring_malloc(sizeof(roaring64_bitmap_t));
227
0
    art_init_cleared(&r->art);
228
0
    r->flags = 0;
229
0
    r->capacity = 0;
230
0
    r->first_free = 0;
231
0
    r->containers = NULL;
232
0
    return r;
233
0
}
234
235
0
void roaring64_bitmap_free(roaring64_bitmap_t *r) {
236
0
    if (!r) {
237
0
        return;
238
0
    }
239
0
    art_iterator_t it = art_init_iterator(&r->art, /*first=*/true);
240
0
    while (it.value != NULL) {
241
0
        leaf_t leaf = (leaf_t)*it.value;
242
0
        if (is_frozen64(r)) {
243
            // Only free the container itself, not the buffer-backed contents
244
            // within.
245
0
            roaring_free(get_container(r, leaf));
246
0
        } else {
247
0
            container_free(get_container(r, leaf), get_typecode(leaf));
248
0
        }
249
0
        art_iterator_next(&it);
250
0
    }
251
0
    if (!is_frozen64(r)) {
252
0
        art_free(&r->art);
253
0
    }
254
0
    roaring_free(r->containers);
255
0
    roaring_free(r);
256
0
}
257
258
0
roaring64_bitmap_t *roaring64_bitmap_copy(const roaring64_bitmap_t *r) {
259
0
    roaring64_bitmap_t *result = roaring64_bitmap_create();
260
261
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/true);
262
0
    while (it.value != NULL) {
263
0
        leaf_t leaf = (leaf_t)*it.value;
264
0
        uint8_t result_typecode = get_typecode(leaf);
265
0
        container_t *result_container = get_copy_of_container(
266
0
            get_container(r, leaf), &result_typecode, /*copy_on_write=*/false);
267
0
        leaf_t result_leaf =
268
0
            add_container(result, result_container, result_typecode);
269
0
        art_insert(&result->art, it.key, (art_val_t)result_leaf);
270
0
        art_iterator_next(&it);
271
0
    }
272
0
    return result;
273
0
}
274
275
void roaring64_bitmap_overwrite(roaring64_bitmap_t *dest,
276
0
                                const roaring64_bitmap_t *src) {
277
0
    if (dest == src) {
278
0
        return;
279
0
    }
280
281
    // Free dest's containers.
282
0
    art_iterator_t it = art_init_iterator(&dest->art, /*first=*/true);
283
0
    while (it.value != NULL) {
284
0
        leaf_t leaf = (leaf_t)*it.value;
285
0
        container_free(get_container(dest, leaf), get_typecode(leaf));
286
0
        art_iterator_next(&it);
287
0
    }
288
0
    art_free(&dest->art);
289
290
    // Reinitialize dest.
291
0
    art_init_cleared(&dest->art);
292
0
    dest->flags = 0;
293
0
    dest->first_free = 0;
294
0
    if (dest->capacity > 0) {
295
0
        memset(dest->containers, 0,
296
0
               sizeof(dest->containers[0]) * dest->capacity);
297
0
    }
298
299
    // Copy src's containers into dest.
300
0
    it = art_init_iterator((art_t *)&src->art, /*first=*/true);
301
0
    while (it.value != NULL) {
302
0
        leaf_t leaf = (leaf_t)*it.value;
303
0
        uint8_t typecode = get_typecode(leaf);
304
0
        container_t *container = get_copy_of_container(
305
0
            get_container(src, leaf), &typecode, /*copy_on_write=*/false);
306
0
        leaf_t dest_leaf = add_container(dest, container, typecode);
307
0
        art_insert(&dest->art, it.key, (art_val_t)dest_leaf);
308
0
        art_iterator_next(&it);
309
0
    }
310
0
}
311
312
/**
313
 * Steal the containers from a 32-bit bitmap and insert them into a 64-bit
314
 * bitmap (with an offset)
315
 *
316
 * After calling this function, the original bitmap will be empty, and the
317
 * returned bitmap will contain all the values from the original bitmap.
318
 */
319
static void move_from_roaring32_offset(roaring64_bitmap_t *dst,
320
                                       roaring_bitmap_t *src,
321
0
                                       uint32_t high_bits) {
322
0
    uint64_t key_base = ((uint64_t)high_bits) << 32;
323
0
    uint32_t r32_size = ra_get_size(&src->high_low_container);
324
0
    for (uint32_t i = 0; i < r32_size; ++i) {
325
0
        uint16_t key = ra_get_key_at_index(&src->high_low_container, i);
326
0
        uint8_t typecode;
327
0
        container_t *container = ra_get_container_at_index(
328
0
            &src->high_low_container, (uint16_t)i, &typecode);
329
330
0
        uint8_t high48[ART_KEY_BYTES];
331
0
        uint64_t high48_bits = key_base | ((uint64_t)key << 16);
332
0
        split_key(high48_bits, high48);
333
0
        leaf_t leaf = add_container(dst, container, typecode);
334
0
        art_insert(&dst->art, high48, (art_val_t)leaf);
335
0
    }
336
    // We stole all the containers, so leave behind a size of zero
337
0
    src->high_low_container.size = 0;
338
0
}
339
340
roaring64_bitmap_t *roaring64_bitmap_move_from_roaring32(
341
0
    roaring_bitmap_t *bitmap32) {
342
0
    roaring64_bitmap_t *result = roaring64_bitmap_create();
343
344
0
    move_from_roaring32_offset(result, bitmap32, 0);
345
346
0
    return result;
347
0
}
348
349
roaring64_bitmap_t *roaring64_bitmap_from_range(uint64_t min, uint64_t max,
350
0
                                                uint64_t step) {
351
0
    if (step == 0 || max <= min) {
352
0
        return NULL;
353
0
    }
354
0
    roaring64_bitmap_t *r = roaring64_bitmap_create();
355
0
    if (step >= (1 << 16)) {
356
        // Only one value per container.
357
0
        for (uint64_t value = min; value < max; value += step) {
358
0
            roaring64_bitmap_add(r, value);
359
0
            if (value > UINT64_MAX - step) {
360
0
                break;
361
0
            }
362
0
        }
363
0
        return r;
364
0
    }
365
0
    do {
366
0
        uint64_t high_bits = min & 0xFFFFFFFFFFFF0000;
367
0
        uint16_t container_min = min & 0xFFFF;
368
0
        uint32_t container_max = (uint32_t)minimum(max - high_bits, 1 << 16);
369
370
0
        uint8_t typecode;
371
0
        container_t *container = container_from_range(
372
0
            &typecode, container_min, container_max, (uint16_t)step);
373
374
0
        uint8_t high48[ART_KEY_BYTES];
375
0
        split_key(min, high48);
376
0
        leaf_t leaf = add_container(r, container, typecode);
377
0
        art_insert(&r->art, high48, (art_val_t)leaf);
378
379
0
        uint64_t gap = container_max - container_min + step - 1;
380
0
        uint64_t increment = gap - (gap % step);
381
0
        if (min > UINT64_MAX - increment) {
382
0
            break;
383
0
        }
384
0
        min += increment;
385
0
    } while (min < max);
386
0
    return r;
387
0
}
388
389
roaring64_bitmap_t *roaring64_bitmap_of_ptr(size_t n_args,
390
0
                                            const uint64_t *vals) {
391
0
    roaring64_bitmap_t *r = roaring64_bitmap_create();
392
0
    roaring64_bitmap_add_many(r, n_args, vals);
393
0
    return r;
394
0
}
395
396
static inline leaf_t *containerptr_roaring64_bitmap_add(roaring64_bitmap_t *r,
397
                                                        uint8_t *high48,
398
                                                        uint16_t low16,
399
0
                                                        leaf_t *leaf) {
400
0
    if (leaf != NULL) {
401
0
        uint8_t typecode = get_typecode(*leaf);
402
0
        container_t *container = get_container(r, *leaf);
403
0
        uint8_t typecode2;
404
0
        container_t *container2 =
405
0
            container_add(container, low16, typecode, &typecode2);
406
0
        if (container2 != container) {
407
0
            container_free(container, typecode);
408
0
            replace_container(r, leaf, container2, typecode2);
409
0
        }
410
0
        return leaf;
411
0
    } else {
412
0
        array_container_t *ac = array_container_create();
413
0
        uint8_t typecode;
414
0
        container_t *container =
415
0
            container_add(ac, low16, ARRAY_CONTAINER_TYPE, &typecode);
416
0
        assert(ac == container);
417
0
        leaf_t new_leaf = add_container(r, container, typecode);
418
0
        return (leaf_t *)art_insert(&r->art, high48, (art_val_t)new_leaf);
419
0
    }
420
0
}
421
422
0
void roaring64_bitmap_add(roaring64_bitmap_t *r, uint64_t val) {
423
0
    uint8_t high48[ART_KEY_BYTES];
424
0
    uint16_t low16 = split_key(val, high48);
425
0
    leaf_t *leaf = (leaf_t *)art_find(&r->art, high48);
426
0
    containerptr_roaring64_bitmap_add(r, high48, low16, leaf);
427
0
}
428
429
0
bool roaring64_bitmap_add_checked(roaring64_bitmap_t *r, uint64_t val) {
430
0
    uint8_t high48[ART_KEY_BYTES];
431
0
    uint16_t low16 = split_key(val, high48);
432
0
    leaf_t *leaf = (leaf_t *)art_find(&r->art, high48);
433
434
0
    int old_cardinality = 0;
435
0
    if (leaf != NULL) {
436
0
        old_cardinality = container_get_cardinality(get_container(r, *leaf),
437
0
                                                    get_typecode(*leaf));
438
0
    }
439
0
    leaf = containerptr_roaring64_bitmap_add(r, high48, low16, leaf);
440
0
    int new_cardinality =
441
0
        container_get_cardinality(get_container(r, *leaf), get_typecode(*leaf));
442
0
    return old_cardinality != new_cardinality;
443
0
}
444
445
void roaring64_bitmap_add_bulk(roaring64_bitmap_t *r,
446
                               roaring64_bulk_context_t *context,
447
0
                               uint64_t val) {
448
0
    uint8_t high48[ART_KEY_BYTES];
449
0
    uint16_t low16 = split_key(val, high48);
450
0
    leaf_t *leaf = context->leaf;
451
0
    if (leaf != NULL && compare_high48(context->high_bytes, high48) == 0) {
452
        // We're at a container with the correct high bits.
453
0
        uint8_t typecode1 = get_typecode(*leaf);
454
0
        container_t *container1 = get_container(r, *leaf);
455
0
        uint8_t typecode2;
456
0
        container_t *container2 =
457
0
            container_add(container1, low16, typecode1, &typecode2);
458
0
        if (container2 != container1) {
459
0
            container_free(container1, typecode1);
460
0
            replace_container(r, leaf, container2, typecode2);
461
0
        }
462
0
    } else {
463
        // We're not positioned anywhere yet or the high bits of the key
464
        // differ.
465
0
        leaf = (leaf_t *)art_find(&r->art, high48);
466
0
        context->leaf =
467
0
            containerptr_roaring64_bitmap_add(r, high48, low16, leaf);
468
0
        memcpy(context->high_bytes, high48, ART_KEY_BYTES);
469
0
    }
470
0
}
471
472
void roaring64_bitmap_add_many(roaring64_bitmap_t *r, size_t n_args,
473
0
                               const uint64_t *vals) {
474
0
    if (n_args == 0) {
475
0
        return;
476
0
    }
477
0
    const uint64_t *end = vals + n_args;
478
0
    roaring64_bulk_context_t context = CROARING_ZERO_INITIALIZER;
479
0
    for (const uint64_t *current_val = vals; current_val != end;
480
0
         current_val++) {
481
0
        roaring64_bitmap_add_bulk(r, &context, *current_val);
482
0
    }
483
0
}
484
485
static inline void add_range_closed_at(roaring64_bitmap_t *r, art_t *art,
486
                                       uint8_t *high48, uint16_t min,
487
0
                                       uint16_t max) {
488
0
    leaf_t *leaf = (leaf_t *)art_find(art, high48);
489
0
    if (leaf != NULL) {
490
0
        uint8_t typecode1 = get_typecode(*leaf);
491
0
        container_t *container1 = get_container(r, *leaf);
492
0
        uint8_t typecode2;
493
0
        container_t *container2 =
494
0
            container_add_range(container1, typecode1, min, max, &typecode2);
495
0
        if (container2 != container1) {
496
0
            container_free(container1, typecode1);
497
0
            replace_container(r, leaf, container2, typecode2);
498
0
        }
499
0
        return;
500
0
    }
501
0
    uint8_t typecode;
502
    // container_add_range is inclusive, but `container_range_of_ones` is
503
    // exclusive.
504
0
    container_t *container = container_range_of_ones(min, max + 1, &typecode);
505
0
    leaf_t new_leaf = add_container(r, container, typecode);
506
0
    art_insert(art, high48, (art_val_t)new_leaf);
507
0
}
508
509
void roaring64_bitmap_add_range(roaring64_bitmap_t *r, uint64_t min,
510
0
                                uint64_t max) {
511
0
    if (min >= max) {
512
0
        return;
513
0
    }
514
0
    roaring64_bitmap_add_range_closed(r, min, max - 1);
515
0
}
516
517
void roaring64_bitmap_add_range_closed(roaring64_bitmap_t *r, uint64_t min,
518
0
                                       uint64_t max) {
519
0
    if (min > max) {
520
0
        return;
521
0
    }
522
523
0
    art_t *art = &r->art;
524
0
    uint8_t min_high48[ART_KEY_BYTES];
525
0
    uint16_t min_low16 = split_key(min, min_high48);
526
0
    uint8_t max_high48[ART_KEY_BYTES];
527
0
    uint16_t max_low16 = split_key(max, max_high48);
528
0
    if (compare_high48(min_high48, max_high48) == 0) {
529
        // Only populate range within one container.
530
0
        add_range_closed_at(r, art, min_high48, min_low16, max_low16);
531
0
        return;
532
0
    }
533
534
    // Populate a range across containers. Fill intermediate containers
535
    // entirely.
536
0
    add_range_closed_at(r, art, min_high48, min_low16, 0xffff);
537
0
    uint64_t min_high_bits = min >> 16;
538
0
    uint64_t max_high_bits = max >> 16;
539
0
    for (uint64_t current = min_high_bits + 1; current < max_high_bits;
540
0
         ++current) {
541
0
        uint8_t current_high48[ART_KEY_BYTES];
542
0
        split_key(current << 16, current_high48);
543
0
        add_range_closed_at(r, art, current_high48, 0, 0xffff);
544
0
    }
545
0
    add_range_closed_at(r, art, max_high48, 0, max_low16);
546
0
}
547
548
0
bool roaring64_bitmap_contains(const roaring64_bitmap_t *r, uint64_t val) {
549
0
    uint8_t high48[ART_KEY_BYTES];
550
0
    uint16_t low16 = split_key(val, high48);
551
0
    leaf_t *leaf = (leaf_t *)art_find(&r->art, high48);
552
0
    if (leaf != NULL) {
553
0
        return container_contains(get_container(r, *leaf), low16,
554
0
                                  get_typecode(*leaf));
555
0
    }
556
0
    return false;
557
0
}
558
559
bool roaring64_bitmap_contains_range(const roaring64_bitmap_t *r, uint64_t min,
560
0
                                     uint64_t max) {
561
0
    if (min >= max) {
562
0
        return true;
563
0
    }
564
0
    return roaring64_bitmap_contains_range_closed(r, min, max - 1);
565
0
}
566
567
bool roaring64_bitmap_contains_range_closed(const roaring64_bitmap_t *r,
568
0
                                            uint64_t min, uint64_t max) {
569
0
    if (min > max) {
570
0
        return true;
571
0
    }
572
573
0
    uint8_t min_high48[ART_KEY_BYTES];
574
0
    uint16_t min_low16 = split_key(min, min_high48);
575
0
    uint8_t max_high48[ART_KEY_BYTES];
576
0
    uint16_t max_low16 = split_key(max, max_high48);
577
0
    uint64_t max_high48_bits = max & 0xFFFFFFFFFFFF0000;
578
579
0
    art_iterator_t it = art_lower_bound((art_t *)&r->art, min_high48);
580
0
    if (it.value == NULL || combine_key(it.key, 0) > min) {
581
0
        return false;
582
0
    }
583
0
    uint64_t prev_high48_bits = min & 0xFFFFFFFFFFFF0000;
584
0
    while (it.value != NULL) {
585
0
        uint64_t current_high48_bits = combine_key(it.key, 0);
586
0
        if (current_high48_bits > max_high48_bits) {
587
            // We've passed the end of the range with all containers containing
588
            // the range.
589
0
            return true;
590
0
        }
591
0
        if (current_high48_bits - prev_high48_bits > 0x10000) {
592
            // There is a gap in the iterator that falls in the range.
593
0
            return false;
594
0
        }
595
596
0
        leaf_t leaf = (leaf_t)*it.value;
597
0
        uint32_t container_min = 0;
598
0
        if (compare_high48(it.key, min_high48) == 0) {
599
0
            container_min = min_low16;
600
0
        }
601
0
        uint32_t container_max = 0xFFFF + 1;  // Exclusive
602
0
        if (compare_high48(it.key, max_high48) == 0) {
603
0
            container_max = (uint32_t)max_low16 + 1;
604
0
        }
605
606
        // For the first and last containers we use container_contains_range,
607
        // for the intermediate containers we can use container_is_full.
608
0
        if (container_min == 0 && container_max == 0xFFFF + 1) {
609
0
            if (!container_is_full(get_container(r, leaf),
610
0
                                   get_typecode(leaf))) {
611
0
                return false;
612
0
            }
613
0
        } else if (!container_contains_range(get_container(r, leaf),
614
0
                                             container_min, container_max,
615
0
                                             get_typecode(leaf))) {
616
0
            return false;
617
0
        }
618
0
        prev_high48_bits = current_high48_bits;
619
0
        art_iterator_next(&it);
620
0
    }
621
0
    return prev_high48_bits == max_high48_bits;
622
0
}
623
624
bool roaring64_bitmap_contains_bulk(const roaring64_bitmap_t *r,
625
                                    roaring64_bulk_context_t *context,
626
0
                                    uint64_t val) {
627
0
    uint8_t high48[ART_KEY_BYTES];
628
0
    uint16_t low16 = split_key(val, high48);
629
630
0
    if (context->leaf == NULL ||
631
0
        art_compare_keys(context->high_bytes, high48) != 0) {
632
        // We're not positioned anywhere yet or the high bits of the key
633
        // differ.
634
0
        leaf_t *leaf = (leaf_t *)art_find(&r->art, high48);
635
0
        if (leaf == NULL) {
636
0
            return false;
637
0
        }
638
0
        context->leaf = leaf;
639
0
        memcpy(context->high_bytes, high48, ART_KEY_BYTES);
640
0
    }
641
0
    return container_contains(get_container(r, *context->leaf), low16,
642
0
                              get_typecode(*context->leaf));
643
0
}
644
645
bool roaring64_bitmap_select(const roaring64_bitmap_t *r, uint64_t rank,
646
0
                             uint64_t *element) {
647
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/true);
648
0
    uint64_t start_rank = 0;
649
0
    while (it.value != NULL) {
650
0
        leaf_t leaf = (leaf_t)*it.value;
651
0
        uint64_t cardinality = container_get_cardinality(get_container(r, leaf),
652
0
                                                         get_typecode(leaf));
653
0
        if (start_rank + cardinality > rank) {
654
0
            uint32_t uint32_start = 0;
655
0
            uint32_t uint32_rank = rank - start_rank;
656
0
            uint32_t uint32_element = 0;
657
0
            if (container_select(get_container(r, leaf), get_typecode(leaf),
658
0
                                 &uint32_start, uint32_rank, &uint32_element)) {
659
0
                *element = combine_key(it.key, (uint16_t)uint32_element);
660
0
                return true;
661
0
            }
662
0
            return false;
663
0
        }
664
0
        start_rank += cardinality;
665
0
        art_iterator_next(&it);
666
0
    }
667
0
    return false;
668
0
}
669
670
0
uint64_t roaring64_bitmap_rank(const roaring64_bitmap_t *r, uint64_t val) {
671
0
    uint8_t high48[ART_KEY_BYTES];
672
0
    uint16_t low16 = split_key(val, high48);
673
674
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/true);
675
0
    uint64_t rank = 0;
676
0
    while (it.value != NULL) {
677
0
        leaf_t leaf = (leaf_t)*it.value;
678
0
        int compare_result = compare_high48(it.key, high48);
679
0
        if (compare_result < 0) {
680
0
            rank += container_get_cardinality(get_container(r, leaf),
681
0
                                              get_typecode(leaf));
682
0
        } else if (compare_result == 0) {
683
0
            return rank + container_rank(get_container(r, leaf),
684
0
                                         get_typecode(leaf), low16);
685
0
        } else {
686
0
            return rank;
687
0
        }
688
0
        art_iterator_next(&it);
689
0
    }
690
0
    return rank;
691
0
}
692
693
bool roaring64_bitmap_get_index(const roaring64_bitmap_t *r, uint64_t val,
694
0
                                uint64_t *out_index) {
695
0
    uint8_t high48[ART_KEY_BYTES];
696
0
    uint16_t low16 = split_key(val, high48);
697
698
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/true);
699
0
    uint64_t index = 0;
700
0
    while (it.value != NULL) {
701
0
        leaf_t leaf = (leaf_t)*it.value;
702
0
        int compare_result = compare_high48(it.key, high48);
703
0
        if (compare_result < 0) {
704
0
            index += container_get_cardinality(get_container(r, leaf),
705
0
                                               get_typecode(leaf));
706
0
        } else if (compare_result == 0) {
707
0
            int index16 = container_get_index(get_container(r, leaf),
708
0
                                              get_typecode(leaf), low16);
709
0
            if (index16 < 0) {
710
0
                return false;
711
0
            }
712
0
            *out_index = index + index16;
713
0
            return true;
714
0
        } else {
715
0
            return false;
716
0
        }
717
0
        art_iterator_next(&it);
718
0
    }
719
0
    return false;
720
0
}
721
722
// Returns true if a container was removed.
723
static inline bool containerptr_roaring64_bitmap_remove(roaring64_bitmap_t *r,
724
                                                        uint8_t *high48,
725
                                                        uint16_t low16,
726
0
                                                        leaf_t *leaf) {
727
0
    if (leaf == NULL) {
728
0
        return false;
729
0
    }
730
731
0
    uint8_t typecode = get_typecode(*leaf);
732
0
    container_t *container = get_container(r, *leaf);
733
0
    uint8_t typecode2;
734
0
    container_t *container2 =
735
0
        container_remove(container, low16, typecode, &typecode2);
736
0
    if (container2 != container) {
737
0
        container_free(container, typecode);
738
0
        replace_container(r, leaf, container2, typecode2);
739
0
    }
740
0
    if (!container_nonzero_cardinality(container2, typecode2)) {
741
0
        container_free(container2, typecode2);
742
0
        bool erased = art_erase(&r->art, high48, (art_val_t *)leaf);
743
0
        assert(erased);
744
0
        (void)erased;
745
0
        remove_container(r, *leaf);
746
0
        return true;
747
0
    }
748
0
    return false;
749
0
}
750
751
0
void roaring64_bitmap_remove(roaring64_bitmap_t *r, uint64_t val) {
752
0
    art_t *art = &r->art;
753
0
    uint8_t high48[ART_KEY_BYTES];
754
0
    uint16_t low16 = split_key(val, high48);
755
756
0
    leaf_t *leaf = (leaf_t *)art_find(art, high48);
757
0
    containerptr_roaring64_bitmap_remove(r, high48, low16, leaf);
758
0
}
759
760
0
bool roaring64_bitmap_remove_checked(roaring64_bitmap_t *r, uint64_t val) {
761
0
    art_t *art = &r->art;
762
0
    uint8_t high48[ART_KEY_BYTES];
763
0
    uint16_t low16 = split_key(val, high48);
764
0
    leaf_t *leaf = (leaf_t *)art_find(art, high48);
765
766
0
    if (leaf == NULL) {
767
0
        return false;
768
0
    }
769
0
    int old_cardinality =
770
0
        container_get_cardinality(get_container(r, *leaf), get_typecode(*leaf));
771
0
    if (containerptr_roaring64_bitmap_remove(r, high48, low16, leaf)) {
772
0
        return true;
773
0
    }
774
0
    int new_cardinality =
775
0
        container_get_cardinality(get_container(r, *leaf), get_typecode(*leaf));
776
0
    return new_cardinality != old_cardinality;
777
0
}
778
779
void roaring64_bitmap_remove_bulk(roaring64_bitmap_t *r,
780
                                  roaring64_bulk_context_t *context,
781
0
                                  uint64_t val) {
782
0
    art_t *art = &r->art;
783
0
    uint8_t high48[ART_KEY_BYTES];
784
0
    uint16_t low16 = split_key(val, high48);
785
0
    if (context->leaf != NULL &&
786
0
        compare_high48(context->high_bytes, high48) == 0) {
787
        // We're at a container with the correct high bits.
788
0
        uint8_t typecode = get_typecode(*context->leaf);
789
0
        container_t *container = get_container(r, *context->leaf);
790
0
        uint8_t typecode2;
791
0
        container_t *container2 =
792
0
            container_remove(container, low16, typecode, &typecode2);
793
0
        if (container2 != container) {
794
0
            container_free(container, typecode);
795
0
            replace_container(r, context->leaf, container2, typecode2);
796
0
        }
797
0
        if (!container_nonzero_cardinality(container2, typecode2)) {
798
0
            container_free(container2, typecode2);
799
0
            leaf_t leaf = 0;
800
0
            bool erased = art_erase(art, high48, (art_val_t *)&leaf);
801
0
            assert(erased);
802
0
            (void)erased;
803
0
            remove_container(r, leaf);
804
0
            context->leaf = NULL;
805
0
        }
806
0
    } else {
807
        // We're not positioned anywhere yet or the high bits of the key
808
        // differ.
809
0
        leaf_t *leaf = (leaf_t *)art_find(art, high48);
810
0
        containerptr_roaring64_bitmap_remove(r, high48, low16, leaf);
811
0
        context->leaf = leaf;
812
0
        memcpy(context->high_bytes, high48, ART_KEY_BYTES);
813
0
    }
814
0
}
815
816
void roaring64_bitmap_remove_many(roaring64_bitmap_t *r, size_t n_args,
817
0
                                  const uint64_t *vals) {
818
0
    if (n_args == 0) {
819
0
        return;
820
0
    }
821
0
    const uint64_t *end = vals + n_args;
822
0
    roaring64_bulk_context_t context = CROARING_ZERO_INITIALIZER;
823
0
    for (const uint64_t *current_val = vals; current_val != end;
824
0
         current_val++) {
825
0
        roaring64_bitmap_remove_bulk(r, &context, *current_val);
826
0
    }
827
0
}
828
829
static inline void remove_range_closed_at(roaring64_bitmap_t *r, art_t *art,
830
                                          uint8_t *high48, uint16_t min,
831
0
                                          uint16_t max) {
832
0
    leaf_t *leaf = (leaf_t *)art_find(art, high48);
833
0
    if (leaf == NULL) {
834
0
        return;
835
0
    }
836
0
    uint8_t typecode = get_typecode(*leaf);
837
0
    container_t *container = get_container(r, *leaf);
838
0
    uint8_t typecode2;
839
0
    container_t *container2 =
840
0
        container_remove_range(container, typecode, min, max, &typecode2);
841
0
    if (container2 != container) {
842
0
        container_free(container, typecode);
843
0
        if (container2 != NULL) {
844
0
            replace_container(r, leaf, container2, typecode2);
845
0
        } else {
846
0
            bool erased = art_erase(art, high48, NULL);
847
0
            assert(erased);
848
0
            (void)erased;
849
0
            remove_container(r, *leaf);
850
0
        }
851
0
    }
852
0
}
853
854
void roaring64_bitmap_remove_range(roaring64_bitmap_t *r, uint64_t min,
855
0
                                   uint64_t max) {
856
0
    if (min >= max) {
857
0
        return;
858
0
    }
859
0
    roaring64_bitmap_remove_range_closed(r, min, max - 1);
860
0
}
861
862
void roaring64_bitmap_remove_range_closed(roaring64_bitmap_t *r, uint64_t min,
863
0
                                          uint64_t max) {
864
0
    if (min > max) {
865
0
        return;
866
0
    }
867
868
0
    art_t *art = &r->art;
869
0
    uint8_t min_high48[ART_KEY_BYTES];
870
0
    uint16_t min_low16 = split_key(min, min_high48);
871
0
    uint8_t max_high48[ART_KEY_BYTES];
872
0
    uint16_t max_low16 = split_key(max, max_high48);
873
0
    if (compare_high48(min_high48, max_high48) == 0) {
874
        // Only remove a range within one container.
875
0
        remove_range_closed_at(r, art, min_high48, min_low16, max_low16);
876
0
        return;
877
0
    }
878
879
    // Remove a range across containers. Remove intermediate containers
880
    // entirely.
881
0
    remove_range_closed_at(r, art, min_high48, min_low16, 0xffff);
882
883
0
    art_iterator_t it = art_upper_bound(art, min_high48);
884
0
    while (it.value != NULL && art_compare_keys(it.key, max_high48) < 0) {
885
0
        leaf_t leaf = 0;
886
0
        bool erased = art_iterator_erase(&it, (art_val_t *)&leaf);
887
0
        assert(erased);
888
0
        (void)erased;
889
0
        container_free(get_container(r, leaf), get_typecode(leaf));
890
0
        remove_container(r, leaf);
891
0
    }
892
0
    remove_range_closed_at(r, art, max_high48, 0, max_low16);
893
0
}
894
895
0
void roaring64_bitmap_clear(roaring64_bitmap_t *r) {
896
0
    roaring64_bitmap_remove_range_closed(r, 0, UINT64_MAX);
897
0
}
898
899
0
uint64_t roaring64_bitmap_get_cardinality(const roaring64_bitmap_t *r) {
900
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/true);
901
0
    uint64_t cardinality = 0;
902
0
    while (it.value != NULL) {
903
0
        leaf_t leaf = (leaf_t)*it.value;
904
0
        cardinality += container_get_cardinality(get_container(r, leaf),
905
0
                                                 get_typecode(leaf));
906
0
        art_iterator_next(&it);
907
0
    }
908
0
    return cardinality;
909
0
}
910
911
uint64_t roaring64_bitmap_range_cardinality(const roaring64_bitmap_t *r,
912
0
                                            uint64_t min, uint64_t max) {
913
0
    if (min >= max) {
914
0
        return 0;
915
0
    }
916
    // Convert to a closed range
917
    // No underflow here: passing the above condition implies min < max, so
918
    // there is a number less than max
919
0
    return roaring64_bitmap_range_closed_cardinality(r, min, max - 1);
920
0
}
921
922
uint64_t roaring64_bitmap_range_closed_cardinality(const roaring64_bitmap_t *r,
923
0
                                                   uint64_t min, uint64_t max) {
924
0
    if (min > max) {
925
0
        return 0;
926
0
    }
927
928
0
    uint64_t cardinality = 0;
929
0
    uint8_t min_high48[ART_KEY_BYTES];
930
0
    uint16_t min_low16 = split_key(min, min_high48);
931
0
    uint8_t max_high48[ART_KEY_BYTES];
932
0
    uint16_t max_low16 = split_key(max, max_high48);
933
934
0
    art_iterator_t it = art_lower_bound((art_t *)&r->art, min_high48);
935
0
    while (it.value != NULL) {
936
0
        int max_compare_result = compare_high48(it.key, max_high48);
937
0
        if (max_compare_result > 0) {
938
            // We're outside the range.
939
0
            break;
940
0
        }
941
942
0
        leaf_t leaf = (leaf_t)*it.value;
943
0
        uint8_t typecode = get_typecode(leaf);
944
0
        container_t *container = get_container(r, leaf);
945
0
        if (max_compare_result == 0) {
946
            // We're at the max high key, add only the range up to the low
947
            // 16 bits of max.
948
0
            cardinality += container_rank(container, typecode, max_low16);
949
0
        } else {
950
            // We're not yet at the max high key, add the full container
951
            // range.
952
0
            cardinality += container_get_cardinality(container, typecode);
953
0
        }
954
0
        if (compare_high48(it.key, min_high48) == 0 && min_low16 > 0) {
955
            // We're at the min high key, remove the range up to the low 16
956
            // bits of min.
957
0
            cardinality -= container_rank(container, typecode, min_low16 - 1);
958
0
        }
959
0
        art_iterator_next(&it);
960
0
    }
961
0
    return cardinality;
962
0
}
963
964
0
bool roaring64_bitmap_is_empty(const roaring64_bitmap_t *r) {
965
0
    return art_is_empty(&r->art);
966
0
}
967
968
0
uint64_t roaring64_bitmap_minimum(const roaring64_bitmap_t *r) {
969
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/true);
970
0
    if (it.value == NULL) {
971
0
        return UINT64_MAX;
972
0
    }
973
0
    leaf_t leaf = (leaf_t)*it.value;
974
0
    return combine_key(
975
0
        it.key, container_minimum(get_container(r, leaf), get_typecode(leaf)));
976
0
}
977
978
0
uint64_t roaring64_bitmap_maximum(const roaring64_bitmap_t *r) {
979
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/false);
980
0
    if (it.value == NULL) {
981
0
        return 0;
982
0
    }
983
0
    leaf_t leaf = (leaf_t)*it.value;
984
0
    return combine_key(
985
0
        it.key, container_maximum(get_container(r, leaf), get_typecode(leaf)));
986
0
}
987
988
0
bool roaring64_bitmap_remove_run_compression(roaring64_bitmap_t *r) {
989
0
    art_iterator_t it = art_init_iterator(&r->art, /*first=*/true);
990
0
    bool removed = false;
991
0
    while (it.value != NULL) {
992
0
        leaf_t *leaf = (leaf_t *)it.value;
993
0
        if (get_typecode(*leaf) == RUN_CONTAINER_TYPE) {
994
0
            run_container_t *run = CAST_run(get_container(r, *leaf));
995
0
            int32_t card = run_container_cardinality(run);
996
0
            uint8_t new_typecode;
997
0
            container_t *new_container =
998
0
                convert_to_bitset_or_array_container(run, card, &new_typecode);
999
0
            run_container_free(run);
1000
0
            replace_container(r, leaf, new_container, new_typecode);
1001
0
            removed = true;
1002
0
        }
1003
0
        art_iterator_next(&it);
1004
0
    }
1005
0
    return removed;
1006
0
}
1007
1008
0
bool roaring64_bitmap_run_optimize(roaring64_bitmap_t *r) {
1009
0
    art_iterator_t it = art_init_iterator(&r->art, /*first=*/true);
1010
0
    bool has_run_container = false;
1011
0
    while (it.value != NULL) {
1012
0
        leaf_t *leaf = (leaf_t *)it.value;
1013
0
        uint8_t new_typecode;
1014
        // We don't need to free the existing container if a new one was
1015
        // created, convert_run_optimize does that internally.
1016
0
        container_t *new_container = convert_run_optimize(
1017
0
            get_container(r, *leaf), get_typecode(*leaf), &new_typecode);
1018
0
        replace_container(r, leaf, new_container, new_typecode);
1019
0
        has_run_container |= new_typecode == RUN_CONTAINER_TYPE;
1020
0
        art_iterator_next(&it);
1021
0
    }
1022
0
    return has_run_container;
1023
0
}
1024
1025
0
static void move_to_shrink(roaring64_bitmap_t *r, leaf_t *leaf) {
1026
0
    uint64_t idx = get_index(*leaf);
1027
0
    if (idx < r->first_free) {
1028
0
        return;
1029
0
    }
1030
0
    r->containers[r->first_free] = get_container(r, *leaf);
1031
0
    r->containers[idx] = NULL;
1032
0
    *leaf = create_leaf(r->first_free, get_typecode(*leaf));
1033
0
    r->first_free = next_free_container_idx(r);
1034
0
}
1035
1036
0
static inline bool is_shrunken(const roaring64_bitmap_t *r) {
1037
0
    return art_is_shrunken(&r->art) && r->first_free == r->capacity;
1038
0
}
1039
1040
0
size_t roaring64_bitmap_shrink_to_fit(roaring64_bitmap_t *r) {
1041
0
    size_t freed = art_shrink_to_fit(&r->art);
1042
0
    art_iterator_t it = art_init_iterator(&r->art, true);
1043
0
    while (it.value != NULL) {
1044
0
        leaf_t *leaf = (leaf_t *)it.value;
1045
0
        freed += container_shrink_to_fit(get_container(r, *leaf),
1046
0
                                         get_typecode(*leaf));
1047
0
        move_to_shrink(r, leaf);
1048
0
        art_iterator_next(&it);
1049
0
    }
1050
0
    if (is_shrunken(r)) {
1051
0
        return freed;
1052
0
    }
1053
0
    uint64_t new_capacity = r->first_free;
1054
0
    if (new_capacity < r->capacity) {
1055
0
        r->containers = (container_t **)roaring_realloc(
1056
0
            r->containers, new_capacity * sizeof(container_t *));
1057
0
        freed += (r->capacity - new_capacity) * sizeof(container_t *);
1058
0
        r->capacity = new_capacity;
1059
0
    }
1060
0
    return freed;
1061
0
}
1062
1063
/**
1064
 *  (For advanced users.)
1065
 * Collect statistics about the bitmap
1066
 */
1067
void roaring64_bitmap_statistics(const roaring64_bitmap_t *r,
1068
0
                                 roaring64_statistics_t *stat) {
1069
0
    memset(stat, 0, sizeof(*stat));
1070
0
    stat->min_value = roaring64_bitmap_minimum(r);
1071
0
    stat->max_value = roaring64_bitmap_maximum(r);
1072
1073
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, true);
1074
0
    while (it.value != NULL) {
1075
0
        leaf_t leaf = (leaf_t)*it.value;
1076
0
        stat->n_containers++;
1077
0
        uint8_t truetype =
1078
0
            get_container_type(get_container(r, leaf), get_typecode(leaf));
1079
0
        uint32_t card = container_get_cardinality(get_container(r, leaf),
1080
0
                                                  get_typecode(leaf));
1081
0
        uint32_t sbytes =
1082
0
            container_size_in_bytes(get_container(r, leaf), get_typecode(leaf));
1083
0
        stat->cardinality += card;
1084
0
        switch (truetype) {
1085
0
            case BITSET_CONTAINER_TYPE:
1086
0
                stat->n_bitset_containers++;
1087
0
                stat->n_values_bitset_containers += card;
1088
0
                stat->n_bytes_bitset_containers += sbytes;
1089
0
                break;
1090
0
            case ARRAY_CONTAINER_TYPE:
1091
0
                stat->n_array_containers++;
1092
0
                stat->n_values_array_containers += card;
1093
0
                stat->n_bytes_array_containers += sbytes;
1094
0
                break;
1095
0
            case RUN_CONTAINER_TYPE:
1096
0
                stat->n_run_containers++;
1097
0
                stat->n_values_run_containers += card;
1098
0
                stat->n_bytes_run_containers += sbytes;
1099
0
                break;
1100
0
            default:
1101
0
                assert(false);
1102
0
                roaring_unreachable;
1103
0
        }
1104
0
        art_iterator_next(&it);
1105
0
    }
1106
0
}
1107
1108
static bool roaring64_leaf_internal_validate(const art_val_t val,
1109
                                             const char **reason,
1110
0
                                             void *context) {
1111
0
    leaf_t leaf = (leaf_t)val;
1112
0
    roaring64_bitmap_t *r = (roaring64_bitmap_t *)context;
1113
0
    return container_internal_validate(get_container(r, leaf),
1114
0
                                       get_typecode(leaf), reason);
1115
0
}
1116
1117
bool roaring64_bitmap_internal_validate(const roaring64_bitmap_t *r,
1118
0
                                        const char **reason) {
1119
0
    return art_internal_validate(&r->art, reason,
1120
0
                                 roaring64_leaf_internal_validate, (void *)r);
1121
0
}
1122
1123
bool roaring64_bitmap_equals(const roaring64_bitmap_t *r1,
1124
0
                             const roaring64_bitmap_t *r2) {
1125
0
    art_iterator_t it1 = art_init_iterator((art_t *)&r1->art, /*first=*/true);
1126
0
    art_iterator_t it2 = art_init_iterator((art_t *)&r2->art, /*first=*/true);
1127
1128
0
    while (it1.value != NULL && it2.value != NULL) {
1129
0
        if (compare_high48(it1.key, it2.key) != 0) {
1130
0
            return false;
1131
0
        }
1132
0
        leaf_t leaf1 = (leaf_t)*it1.value;
1133
0
        leaf_t leaf2 = (leaf_t)*it2.value;
1134
0
        if (!container_equals(get_container(r1, leaf1), get_typecode(leaf1),
1135
0
                              get_container(r2, leaf2), get_typecode(leaf2))) {
1136
0
            return false;
1137
0
        }
1138
0
        art_iterator_next(&it1);
1139
0
        art_iterator_next(&it2);
1140
0
    }
1141
0
    return it1.value == NULL && it2.value == NULL;
1142
0
}
1143
1144
bool roaring64_bitmap_is_subset(const roaring64_bitmap_t *r1,
1145
0
                                const roaring64_bitmap_t *r2) {
1146
0
    art_iterator_t it1 = art_init_iterator((art_t *)&r1->art, /*first=*/true);
1147
0
    art_iterator_t it2 = art_init_iterator((art_t *)&r2->art, /*first=*/true);
1148
1149
0
    while (it1.value != NULL) {
1150
0
        bool it2_present = it2.value != NULL;
1151
1152
0
        int compare_result = 0;
1153
0
        if (it2_present) {
1154
0
            compare_result = compare_high48(it1.key, it2.key);
1155
0
            if (compare_result == 0) {
1156
0
                leaf_t leaf1 = (leaf_t)*it1.value;
1157
0
                leaf_t leaf2 = (leaf_t)*it2.value;
1158
0
                if (!container_is_subset(
1159
0
                        get_container(r1, leaf1), get_typecode(leaf1),
1160
0
                        get_container(r2, leaf2), get_typecode(leaf2))) {
1161
0
                    return false;
1162
0
                }
1163
0
                art_iterator_next(&it1);
1164
0
                art_iterator_next(&it2);
1165
0
            }
1166
0
        }
1167
0
        if (!it2_present || compare_result < 0) {
1168
0
            return false;
1169
0
        } else if (compare_result > 0) {
1170
0
            art_iterator_lower_bound(&it2, it1.key);
1171
0
        }
1172
0
    }
1173
0
    return true;
1174
0
}
1175
1176
bool roaring64_bitmap_is_strict_subset(const roaring64_bitmap_t *r1,
1177
0
                                       const roaring64_bitmap_t *r2) {
1178
0
    return roaring64_bitmap_get_cardinality(r1) <
1179
0
               roaring64_bitmap_get_cardinality(r2) &&
1180
0
           roaring64_bitmap_is_subset(r1, r2);
1181
0
}
1182
1183
roaring64_bitmap_t *roaring64_bitmap_and(const roaring64_bitmap_t *r1,
1184
0
                                         const roaring64_bitmap_t *r2) {
1185
0
    roaring64_bitmap_t *result = roaring64_bitmap_create();
1186
1187
0
    art_iterator_t it1 = art_init_iterator((art_t *)&r1->art, /*first=*/true);
1188
0
    art_iterator_t it2 = art_init_iterator((art_t *)&r2->art, /*first=*/true);
1189
1190
0
    while (it1.value != NULL && it2.value != NULL) {
1191
        // Cases:
1192
        // 1. it1 <  it2 -> it1++
1193
        // 2. it1 == it1 -> output it1 & it2, it1++, it2++
1194
        // 3. it1 >  it2 -> it2++
1195
0
        int compare_result = compare_high48(it1.key, it2.key);
1196
0
        if (compare_result == 0) {
1197
            // Case 2: iterators at the same high key position.
1198
0
            leaf_t leaf1 = (leaf_t)*it1.value;
1199
0
            leaf_t leaf2 = (leaf_t)*it2.value;
1200
0
            uint8_t result_typecode;
1201
0
            container_t *result_container =
1202
0
                container_and(get_container(r1, leaf1), get_typecode(leaf1),
1203
0
                              get_container(r2, leaf2), get_typecode(leaf2),
1204
0
                              &result_typecode);
1205
0
            if (container_nonzero_cardinality(result_container,
1206
0
                                              result_typecode)) {
1207
0
                leaf_t result_leaf =
1208
0
                    add_container(result, result_container, result_typecode);
1209
0
                art_insert(&result->art, it1.key, (art_val_t)result_leaf);
1210
0
            } else {
1211
0
                container_free(result_container, result_typecode);
1212
0
            }
1213
0
            art_iterator_next(&it1);
1214
0
            art_iterator_next(&it2);
1215
0
        } else if (compare_result < 0) {
1216
            // Case 1: it1 is before it2.
1217
0
            art_iterator_lower_bound(&it1, it2.key);
1218
0
        } else {
1219
            // Case 3: it2 is before it1.
1220
0
            art_iterator_lower_bound(&it2, it1.key);
1221
0
        }
1222
0
    }
1223
0
    return result;
1224
0
}
1225
1226
uint64_t roaring64_bitmap_and_cardinality(const roaring64_bitmap_t *r1,
1227
0
                                          const roaring64_bitmap_t *r2) {
1228
0
    uint64_t result = 0;
1229
1230
0
    art_iterator_t it1 = art_init_iterator((art_t *)&r1->art, /*first=*/true);
1231
0
    art_iterator_t it2 = art_init_iterator((art_t *)&r2->art, /*first=*/true);
1232
1233
0
    while (it1.value != NULL && it2.value != NULL) {
1234
        // Cases:
1235
        // 1. it1 <  it2 -> it1++
1236
        // 2. it1 == it1 -> output cardinaltiy it1 & it2, it1++, it2++
1237
        // 3. it1 >  it2 -> it2++
1238
0
        int compare_result = compare_high48(it1.key, it2.key);
1239
0
        if (compare_result == 0) {
1240
            // Case 2: iterators at the same high key position.
1241
0
            leaf_t leaf1 = (leaf_t)*it1.value;
1242
0
            leaf_t leaf2 = (leaf_t)*it2.value;
1243
0
            result += container_and_cardinality(
1244
0
                get_container(r1, leaf1), get_typecode(leaf1),
1245
0
                get_container(r2, leaf2), get_typecode(leaf2));
1246
0
            art_iterator_next(&it1);
1247
0
            art_iterator_next(&it2);
1248
0
        } else if (compare_result < 0) {
1249
            // Case 1: it1 is before it2.
1250
0
            art_iterator_lower_bound(&it1, it2.key);
1251
0
        } else {
1252
            // Case 3: it2 is before it1.
1253
0
            art_iterator_lower_bound(&it2, it1.key);
1254
0
        }
1255
0
    }
1256
0
    return result;
1257
0
}
1258
1259
// Inplace and (modifies its first argument).
1260
void roaring64_bitmap_and_inplace(roaring64_bitmap_t *r1,
1261
0
                                  const roaring64_bitmap_t *r2) {
1262
0
    if (r1 == r2) {
1263
0
        return;
1264
0
    }
1265
0
    art_iterator_t it1 = art_init_iterator(&r1->art, /*first=*/true);
1266
0
    art_iterator_t it2 = art_init_iterator((art_t *)&r2->art, /*first=*/true);
1267
1268
0
    while (it1.value != NULL) {
1269
        // Cases:
1270
        // 1. !it2_present -> erase it1
1271
        // 2. it2_present
1272
        //    a. it1 <  it2 -> erase it1
1273
        //    b. it1 == it2 -> output it1 & it2, it1++, it2++
1274
        //    c. it1 >  it2 -> it2++
1275
0
        bool it2_present = it2.value != NULL;
1276
0
        int compare_result = 0;
1277
0
        if (it2_present) {
1278
0
            compare_result = compare_high48(it1.key, it2.key);
1279
0
            if (compare_result == 0) {
1280
                // Case 2a: iterators at the same high key position.
1281
0
                leaf_t *leaf1 = (leaf_t *)it1.value;
1282
0
                leaf_t leaf2 = (leaf_t)*it2.value;
1283
1284
                // We do the computation "in place" only when c1 is not a
1285
                // shared container. Rationale: using a shared container
1286
                // safely with in place computation would require making a
1287
                // copy and then doing the computation in place which is
1288
                // likely less efficient than avoiding in place entirely and
1289
                // always generating a new container.
1290
0
                uint8_t typecode = get_typecode(*leaf1);
1291
0
                container_t *container = get_container(r1, *leaf1);
1292
0
                uint8_t typecode2;
1293
0
                container_t *container2;
1294
0
                if (typecode == SHARED_CONTAINER_TYPE) {
1295
0
                    container2 = container_and(container, typecode,
1296
0
                                               get_container(r2, leaf2),
1297
0
                                               get_typecode(leaf2), &typecode2);
1298
0
                } else {
1299
0
                    container2 = container_iand(
1300
0
                        container, typecode, get_container(r2, leaf2),
1301
0
                        get_typecode(leaf2), &typecode2);
1302
0
                }
1303
1304
0
                if (container2 != container) {
1305
0
                    container_free(container, typecode);
1306
0
                }
1307
0
                if (!container_nonzero_cardinality(container2, typecode2)) {
1308
0
                    container_free(container2, typecode2);
1309
0
                    art_iterator_erase(&it1, NULL);
1310
0
                    remove_container(r1, *leaf1);
1311
0
                } else {
1312
0
                    if (container2 != container) {
1313
0
                        replace_container(r1, leaf1, container2, typecode2);
1314
0
                    }
1315
                    // Only advance the iterator if we didn't delete the
1316
                    // leaf, as erasing advances by itself.
1317
0
                    art_iterator_next(&it1);
1318
0
                }
1319
0
                art_iterator_next(&it2);
1320
0
            }
1321
0
        }
1322
1323
0
        if (!it2_present || compare_result < 0) {
1324
            // Cases 1 and 3a: it1 is the only iterator or is before it2.
1325
0
            leaf_t leaf = 0;
1326
0
            bool erased = art_iterator_erase(&it1, (art_val_t *)&leaf);
1327
0
            assert(erased);
1328
0
            (void)erased;
1329
0
            container_free(get_container(r1, leaf), get_typecode(leaf));
1330
0
            remove_container(r1, leaf);
1331
0
        } else if (compare_result > 0) {
1332
            // Case 2c: it1 is after it2.
1333
0
            art_iterator_lower_bound(&it2, it1.key);
1334
0
        }
1335
0
    }
1336
0
}
1337
1338
bool roaring64_bitmap_intersect(const roaring64_bitmap_t *r1,
1339
0
                                const roaring64_bitmap_t *r2) {
1340
0
    bool intersect = false;
1341
0
    art_iterator_t it1 = art_init_iterator((art_t *)&r1->art, /*first=*/true);
1342
0
    art_iterator_t it2 = art_init_iterator((art_t *)&r2->art, /*first=*/true);
1343
1344
0
    while (it1.value != NULL && it2.value != NULL) {
1345
        // Cases:
1346
        // 1. it1 <  it2 -> it1++
1347
        // 2. it1 == it1 -> intersect |= it1 & it2, it1++, it2++
1348
        // 3. it1 >  it2 -> it2++
1349
0
        int compare_result = compare_high48(it1.key, it2.key);
1350
0
        if (compare_result == 0) {
1351
            // Case 2: iterators at the same high key position.
1352
0
            leaf_t leaf1 = (leaf_t)*it1.value;
1353
0
            leaf_t leaf2 = (leaf_t)*it2.value;
1354
0
            intersect |= container_intersect(
1355
0
                get_container(r1, leaf1), get_typecode(leaf1),
1356
0
                get_container(r2, leaf2), get_typecode(leaf2));
1357
0
            art_iterator_next(&it1);
1358
0
            art_iterator_next(&it2);
1359
0
        } else if (compare_result < 0) {
1360
            // Case 1: it1 is before it2.
1361
0
            art_iterator_lower_bound(&it1, it2.key);
1362
0
        } else {
1363
            // Case 3: it2 is before it1.
1364
0
            art_iterator_lower_bound(&it2, it1.key);
1365
0
        }
1366
0
    }
1367
0
    return intersect;
1368
0
}
1369
1370
bool roaring64_bitmap_intersect_with_range(const roaring64_bitmap_t *r,
1371
0
                                           uint64_t min, uint64_t max) {
1372
0
    if (min >= max) {
1373
0
        return false;
1374
0
    }
1375
0
    roaring64_iterator_t it;
1376
0
    roaring64_iterator_init_at(r, &it, /*first=*/true);
1377
0
    if (!roaring64_iterator_move_equalorlarger(&it, min)) {
1378
0
        return false;
1379
0
    }
1380
0
    return roaring64_iterator_has_value(&it) &&
1381
0
           roaring64_iterator_value(&it) < max;
1382
0
}
1383
1384
double roaring64_bitmap_jaccard_index(const roaring64_bitmap_t *r1,
1385
0
                                      const roaring64_bitmap_t *r2) {
1386
0
    uint64_t c1 = roaring64_bitmap_get_cardinality(r1);
1387
0
    uint64_t c2 = roaring64_bitmap_get_cardinality(r2);
1388
0
    uint64_t inter = roaring64_bitmap_and_cardinality(r1, r2);
1389
0
    return (double)inter / (double)(c1 + c2 - inter);
1390
0
}
1391
1392
roaring64_bitmap_t *roaring64_bitmap_or(const roaring64_bitmap_t *r1,
1393
0
                                        const roaring64_bitmap_t *r2) {
1394
0
    roaring64_bitmap_t *result = roaring64_bitmap_create();
1395
1396
0
    art_iterator_t it1 = art_init_iterator((art_t *)&r1->art, /*first=*/true);
1397
0
    art_iterator_t it2 = art_init_iterator((art_t *)&r2->art, /*first=*/true);
1398
1399
0
    while (it1.value != NULL || it2.value != NULL) {
1400
0
        bool it1_present = it1.value != NULL;
1401
0
        bool it2_present = it2.value != NULL;
1402
1403
        // Cases:
1404
        // 1. it1_present  && !it2_present -> output it1, it1++
1405
        // 2. !it1_present && it2_present  -> output it2, it2++
1406
        // 3. it1_present  && it2_present
1407
        //    a. it1 <  it2 -> output it1, it1++
1408
        //    b. it1 == it2 -> output it1 | it2, it1++, it2++
1409
        //    c. it1 >  it2 -> output it2, it2++
1410
0
        int compare_result = 0;
1411
0
        if (it1_present && it2_present) {
1412
0
            compare_result = compare_high48(it1.key, it2.key);
1413
0
            if (compare_result == 0) {
1414
                // Case 3b: iterators at the same high key position.
1415
0
                leaf_t leaf1 = (leaf_t)*it1.value;
1416
0
                leaf_t leaf2 = (leaf_t)*it2.value;
1417
0
                uint8_t result_typecode;
1418
0
                container_t *result_container =
1419
0
                    container_or(get_container(r1, leaf1), get_typecode(leaf1),
1420
0
                                 get_container(r2, leaf2), get_typecode(leaf2),
1421
0
                                 &result_typecode);
1422
0
                leaf_t result_leaf =
1423
0
                    add_container(result, result_container, result_typecode);
1424
0
                art_insert(&result->art, it1.key, (art_val_t)result_leaf);
1425
0
                art_iterator_next(&it1);
1426
0
                art_iterator_next(&it2);
1427
0
            }
1428
0
        }
1429
0
        if ((it1_present && !it2_present) || compare_result < 0) {
1430
            // Cases 1 and 3a: it1 is the only iterator or is before it2.
1431
0
            leaf_t result_leaf =
1432
0
                copy_leaf_container(r1, result, (leaf_t)*it1.value);
1433
0
            art_insert(&result->art, it1.key, (art_val_t)result_leaf);
1434
0
            art_iterator_next(&it1);
1435
0
        } else if ((!it1_present && it2_present) || compare_result > 0) {
1436
            // Cases 2 and 3c: it2 is the only iterator or is before it1.
1437
0
            leaf_t result_leaf =
1438
0
                copy_leaf_container(r2, result, (leaf_t)*it2.value);
1439
0
            art_insert(&result->art, it2.key, (art_val_t)result_leaf);
1440
0
            art_iterator_next(&it2);
1441
0
        }
1442
0
    }
1443
0
    return result;
1444
0
}
1445
1446
uint64_t roaring64_bitmap_or_cardinality(const roaring64_bitmap_t *r1,
1447
0
                                         const roaring64_bitmap_t *r2) {
1448
0
    uint64_t c1 = roaring64_bitmap_get_cardinality(r1);
1449
0
    uint64_t c2 = roaring64_bitmap_get_cardinality(r2);
1450
0
    uint64_t inter = roaring64_bitmap_and_cardinality(r1, r2);
1451
0
    return c1 + c2 - inter;
1452
0
}
1453
1454
void roaring64_bitmap_or_inplace(roaring64_bitmap_t *r1,
1455
0
                                 const roaring64_bitmap_t *r2) {
1456
0
    if (r1 == r2) {
1457
0
        return;
1458
0
    }
1459
0
    art_iterator_t it1 = art_init_iterator(&r1->art, /*first=*/true);
1460
0
    art_iterator_t it2 = art_init_iterator((art_t *)&r2->art, /*first=*/true);
1461
1462
0
    while (it1.value != NULL || it2.value != NULL) {
1463
0
        bool it1_present = it1.value != NULL;
1464
0
        bool it2_present = it2.value != NULL;
1465
1466
        // Cases:
1467
        // 1. it1_present  && !it2_present -> it1++
1468
        // 2. !it1_present && it2_present  -> add it2, it2++
1469
        // 3. it1_present  && it2_present
1470
        //    a. it1 <  it2 -> it1++
1471
        //    b. it1 == it2 -> it1 | it2, it1++, it2++
1472
        //    c. it1 >  it2 -> add it2, it2++
1473
0
        int compare_result = 0;
1474
0
        if (it1_present && it2_present) {
1475
0
            compare_result = compare_high48(it1.key, it2.key);
1476
0
            if (compare_result == 0) {
1477
                // Case 3b: iterators at the same high key position.
1478
0
                leaf_t *leaf1 = (leaf_t *)it1.value;
1479
0
                leaf_t leaf2 = (leaf_t)*it2.value;
1480
0
                uint8_t typecode1 = get_typecode(*leaf1);
1481
0
                container_t *container1 = get_container(r1, *leaf1);
1482
0
                uint8_t typecode2;
1483
0
                container_t *container2;
1484
0
                if (get_typecode(*leaf1) == SHARED_CONTAINER_TYPE) {
1485
0
                    container2 = container_or(container1, typecode1,
1486
0
                                              get_container(r2, leaf2),
1487
0
                                              get_typecode(leaf2), &typecode2);
1488
0
                } else {
1489
0
                    container2 = container_ior(container1, typecode1,
1490
0
                                               get_container(r2, leaf2),
1491
0
                                               get_typecode(leaf2), &typecode2);
1492
0
                }
1493
0
                if (container2 != container1) {
1494
0
                    container_free(container1, typecode1);
1495
0
                    replace_container(r1, leaf1, container2, typecode2);
1496
0
                }
1497
0
                art_iterator_next(&it1);
1498
0
                art_iterator_next(&it2);
1499
0
            }
1500
0
        }
1501
0
        if ((it1_present && !it2_present) || compare_result < 0) {
1502
            // Cases 1 and 3a: it1 is the only iterator or is before it2.
1503
0
            art_iterator_next(&it1);
1504
0
        } else if ((!it1_present && it2_present) || compare_result > 0) {
1505
            // Cases 2 and 3c: it2 is the only iterator or is before it1.
1506
0
            leaf_t result_leaf =
1507
0
                copy_leaf_container(r2, r1, (leaf_t)*it2.value);
1508
0
            art_iterator_insert(&it1, it2.key, (art_val_t)result_leaf);
1509
0
            art_iterator_next(&it2);
1510
0
        }
1511
0
    }
1512
0
}
1513
1514
roaring64_bitmap_t *roaring64_bitmap_xor(const roaring64_bitmap_t *r1,
1515
0
                                         const roaring64_bitmap_t *r2) {
1516
0
    roaring64_bitmap_t *result = roaring64_bitmap_create();
1517
1518
0
    art_iterator_t it1 = art_init_iterator((art_t *)&r1->art, /*first=*/true);
1519
0
    art_iterator_t it2 = art_init_iterator((art_t *)&r2->art, /*first=*/true);
1520
1521
0
    while (it1.value != NULL || it2.value != NULL) {
1522
0
        bool it1_present = it1.value != NULL;
1523
0
        bool it2_present = it2.value != NULL;
1524
1525
        // Cases:
1526
        // 1. it1_present  && !it2_present -> output it1, it1++
1527
        // 2. !it1_present && it2_present  -> output it2, it2++
1528
        // 3. it1_present  && it2_present
1529
        //    a. it1 <  it2 -> output it1, it1++
1530
        //    b. it1 == it2 -> output it1 ^ it2, it1++, it2++
1531
        //    c. it1 >  it2 -> output it2, it2++
1532
0
        int compare_result = 0;
1533
0
        if (it1_present && it2_present) {
1534
0
            compare_result = compare_high48(it1.key, it2.key);
1535
0
            if (compare_result == 0) {
1536
                // Case 3b: iterators at the same high key position.
1537
0
                leaf_t leaf1 = (leaf_t)*it1.value;
1538
0
                leaf_t leaf2 = (leaf_t)*it2.value;
1539
0
                uint8_t result_typecode;
1540
0
                container_t *result_container =
1541
0
                    container_xor(get_container(r1, leaf1), get_typecode(leaf1),
1542
0
                                  get_container(r2, leaf2), get_typecode(leaf2),
1543
0
                                  &result_typecode);
1544
0
                if (container_nonzero_cardinality(result_container,
1545
0
                                                  result_typecode)) {
1546
0
                    leaf_t result_leaf = add_container(result, result_container,
1547
0
                                                       result_typecode);
1548
0
                    art_insert(&result->art, it1.key, (art_val_t)result_leaf);
1549
0
                } else {
1550
0
                    container_free(result_container, result_typecode);
1551
0
                }
1552
0
                art_iterator_next(&it1);
1553
0
                art_iterator_next(&it2);
1554
0
            }
1555
0
        }
1556
0
        if ((it1_present && !it2_present) || compare_result < 0) {
1557
            // Cases 1 and 3a: it1 is the only iterator or is before it2.
1558
0
            leaf_t result_leaf =
1559
0
                copy_leaf_container(r1, result, (leaf_t)*it1.value);
1560
0
            art_insert(&result->art, it1.key, (art_val_t)result_leaf);
1561
0
            art_iterator_next(&it1);
1562
0
        } else if ((!it1_present && it2_present) || compare_result > 0) {
1563
            // Cases 2 and 3c: it2 is the only iterator or is before it1.
1564
0
            leaf_t result_leaf =
1565
0
                copy_leaf_container(r2, result, (leaf_t)*it2.value);
1566
0
            art_insert(&result->art, it2.key, (art_val_t)result_leaf);
1567
0
            art_iterator_next(&it2);
1568
0
        }
1569
0
    }
1570
0
    return result;
1571
0
}
1572
1573
uint64_t roaring64_bitmap_xor_cardinality(const roaring64_bitmap_t *r1,
1574
0
                                          const roaring64_bitmap_t *r2) {
1575
0
    uint64_t c1 = roaring64_bitmap_get_cardinality(r1);
1576
0
    uint64_t c2 = roaring64_bitmap_get_cardinality(r2);
1577
0
    uint64_t inter = roaring64_bitmap_and_cardinality(r1, r2);
1578
0
    return c1 + c2 - 2 * inter;
1579
0
}
1580
1581
void roaring64_bitmap_xor_inplace(roaring64_bitmap_t *r1,
1582
0
                                  const roaring64_bitmap_t *r2) {
1583
0
    assert(r1 != r2);
1584
0
    art_iterator_t it1 = art_init_iterator(&r1->art, /*first=*/true);
1585
0
    art_iterator_t it2 = art_init_iterator((art_t *)&r2->art, /*first=*/true);
1586
1587
0
    while (it1.value != NULL || it2.value != NULL) {
1588
0
        bool it1_present = it1.value != NULL;
1589
0
        bool it2_present = it2.value != NULL;
1590
1591
        // Cases:
1592
        // 1.  it1_present && !it2_present -> it1++
1593
        // 2. !it1_present &&  it2_present -> add it2, it2++
1594
        // 3.  it1_present &&  it2_present
1595
        //    a. it1 <  it2 -> it1++
1596
        //    b. it1 == it2 -> it1 ^ it2, it1++, it2++
1597
        //    c. it1 >  it2 -> add it2, it2++
1598
0
        int compare_result = 0;
1599
0
        if (it1_present && it2_present) {
1600
0
            compare_result = compare_high48(it1.key, it2.key);
1601
0
            if (compare_result == 0) {
1602
                // Case 3b: iterators at the same high key position.
1603
0
                leaf_t *leaf1 = (leaf_t *)it1.value;
1604
0
                leaf_t leaf2 = (leaf_t)*it2.value;
1605
0
                uint8_t typecode1 = get_typecode(*leaf1);
1606
0
                container_t *container1 = get_container(r1, *leaf1);
1607
0
                uint8_t typecode2;
1608
0
                container_t *container2;
1609
0
                if (typecode1 == SHARED_CONTAINER_TYPE) {
1610
0
                    container2 = container_xor(container1, typecode1,
1611
0
                                               get_container(r2, leaf2),
1612
0
                                               get_typecode(leaf2), &typecode2);
1613
0
                    if (container2 != container1) {
1614
                        // We only free when doing container_xor, not
1615
                        // container_ixor, as ixor frees the original
1616
                        // internally.
1617
0
                        container_free(container1, typecode1);
1618
0
                    }
1619
0
                } else {
1620
0
                    container2 = container_ixor(
1621
0
                        container1, typecode1, get_container(r2, leaf2),
1622
0
                        get_typecode(leaf2), &typecode2);
1623
0
                }
1624
1625
0
                if (!container_nonzero_cardinality(container2, typecode2)) {
1626
0
                    container_free(container2, typecode2);
1627
0
                    bool erased = art_iterator_erase(&it1, NULL);
1628
0
                    assert(erased);
1629
0
                    (void)erased;
1630
0
                    remove_container(r1, *leaf1);
1631
0
                } else {
1632
0
                    if (container2 != container1) {
1633
0
                        replace_container(r1, leaf1, container2, typecode2);
1634
0
                    }
1635
                    // Only advance the iterator if we didn't delete the
1636
                    // leaf, as erasing advances by itself.
1637
0
                    art_iterator_next(&it1);
1638
0
                }
1639
0
                art_iterator_next(&it2);
1640
0
            }
1641
0
        }
1642
0
        if ((it1_present && !it2_present) || compare_result < 0) {
1643
            // Cases 1 and 3a: it1 is the only iterator or is before it2.
1644
0
            art_iterator_next(&it1);
1645
0
        } else if ((!it1_present && it2_present) || compare_result > 0) {
1646
            // Cases 2 and 3c: it2 is the only iterator or is before it1.
1647
0
            leaf_t result_leaf =
1648
0
                copy_leaf_container(r2, r1, (leaf_t)*it2.value);
1649
0
            if (it1_present) {
1650
0
                art_iterator_insert(&it1, it2.key, (art_val_t)result_leaf);
1651
0
                art_iterator_next(&it1);
1652
0
            } else {
1653
0
                art_insert(&r1->art, it2.key, (art_val_t)result_leaf);
1654
0
            }
1655
0
            art_iterator_next(&it2);
1656
0
        }
1657
0
    }
1658
0
}
1659
1660
roaring64_bitmap_t *roaring64_bitmap_andnot(const roaring64_bitmap_t *r1,
1661
0
                                            const roaring64_bitmap_t *r2) {
1662
0
    roaring64_bitmap_t *result = roaring64_bitmap_create();
1663
1664
0
    art_iterator_t it1 = art_init_iterator((art_t *)&r1->art, /*first=*/true);
1665
0
    art_iterator_t it2 = art_init_iterator((art_t *)&r2->art, /*first=*/true);
1666
1667
0
    while (it1.value != NULL) {
1668
        // Cases:
1669
        // 1. it1_present && !it2_present -> output it1, it1++
1670
        // 2. it1_present && it2_present
1671
        //    a. it1 <  it2 -> output it1, it1++
1672
        //    b. it1 == it2 -> output it1 - it2, it1++, it2++
1673
        //    c. it1 >  it2 -> it2++
1674
0
        bool it2_present = it2.value != NULL;
1675
0
        int compare_result = 0;
1676
0
        if (it2_present) {
1677
0
            compare_result = compare_high48(it1.key, it2.key);
1678
0
            if (compare_result == 0) {
1679
                // Case 2b: iterators at the same high key position.
1680
0
                leaf_t *leaf1 = (leaf_t *)it1.value;
1681
0
                leaf_t leaf2 = (leaf_t)*it2.value;
1682
0
                uint8_t result_typecode;
1683
0
                container_t *result_container = container_andnot(
1684
0
                    get_container(r1, *leaf1), get_typecode(*leaf1),
1685
0
                    get_container(r2, leaf2), get_typecode(leaf2),
1686
0
                    &result_typecode);
1687
1688
0
                if (container_nonzero_cardinality(result_container,
1689
0
                                                  result_typecode)) {
1690
0
                    leaf_t result_leaf = add_container(result, result_container,
1691
0
                                                       result_typecode);
1692
0
                    art_insert(&result->art, it1.key, (art_val_t)result_leaf);
1693
0
                } else {
1694
0
                    container_free(result_container, result_typecode);
1695
0
                }
1696
0
                art_iterator_next(&it1);
1697
0
                art_iterator_next(&it2);
1698
0
            }
1699
0
        }
1700
0
        if (!it2_present || compare_result < 0) {
1701
            // Cases 1 and 2a: it1 is the only iterator or is before it2.
1702
0
            leaf_t result_leaf =
1703
0
                copy_leaf_container(r1, result, (leaf_t)*it1.value);
1704
0
            art_insert(&result->art, it1.key, (art_val_t)result_leaf);
1705
0
            art_iterator_next(&it1);
1706
0
        } else if (compare_result > 0) {
1707
            // Case 2c: it1 is after it2.
1708
0
            art_iterator_next(&it2);
1709
0
        }
1710
0
    }
1711
0
    return result;
1712
0
}
1713
1714
uint64_t roaring64_bitmap_andnot_cardinality(const roaring64_bitmap_t *r1,
1715
0
                                             const roaring64_bitmap_t *r2) {
1716
0
    uint64_t c1 = roaring64_bitmap_get_cardinality(r1);
1717
0
    uint64_t inter = roaring64_bitmap_and_cardinality(r1, r2);
1718
0
    return c1 - inter;
1719
0
}
1720
1721
void roaring64_bitmap_andnot_inplace(roaring64_bitmap_t *r1,
1722
0
                                     const roaring64_bitmap_t *r2) {
1723
0
    art_iterator_t it1 = art_init_iterator(&r1->art, /*first=*/true);
1724
0
    art_iterator_t it2 = art_init_iterator((art_t *)&r2->art, /*first=*/true);
1725
1726
0
    while (it1.value != NULL) {
1727
        // Cases:
1728
        // 1. it1_present && !it2_present -> it1++
1729
        // 2. it1_present &&  it2_present
1730
        //    a. it1 <  it2 -> it1++
1731
        //    b. it1 == it2 -> it1 - it2, it1++, it2++
1732
        //    c. it1 >  it2 -> it2++
1733
0
        bool it2_present = it2.value != NULL;
1734
0
        int compare_result = 0;
1735
0
        if (it2_present) {
1736
0
            compare_result = compare_high48(it1.key, it2.key);
1737
0
            if (compare_result == 0) {
1738
                // Case 2b: iterators at the same high key position.
1739
0
                leaf_t *leaf1 = (leaf_t *)it1.value;
1740
0
                leaf_t leaf2 = (leaf_t)*it2.value;
1741
0
                uint8_t typecode1 = get_typecode(*leaf1);
1742
0
                container_t *container1 = get_container(r1, *leaf1);
1743
0
                uint8_t typecode2;
1744
0
                container_t *container2;
1745
0
                if (typecode1 == SHARED_CONTAINER_TYPE) {
1746
0
                    container2 = container_andnot(
1747
0
                        container1, typecode1, get_container(r2, leaf2),
1748
0
                        get_typecode(leaf2), &typecode2);
1749
0
                    if (container2 != container1) {
1750
                        // We only free when doing container_andnot, not
1751
                        // container_iandnot, as iandnot frees the original
1752
                        // internally.
1753
0
                        container_free(container1, typecode1);
1754
0
                    }
1755
0
                } else {
1756
0
                    container2 = container_iandnot(
1757
0
                        container1, typecode1, get_container(r2, leaf2),
1758
0
                        get_typecode(leaf2), &typecode2);
1759
0
                }
1760
1761
0
                if (!container_nonzero_cardinality(container2, typecode2)) {
1762
0
                    container_free(container2, typecode2);
1763
0
                    bool erased = art_iterator_erase(&it1, NULL);
1764
0
                    assert(erased);
1765
0
                    (void)erased;
1766
0
                    remove_container(r1, *leaf1);
1767
0
                } else {
1768
0
                    if (container2 != container1) {
1769
0
                        replace_container(r1, leaf1, container2, typecode2);
1770
0
                    }
1771
                    // Only advance the iterator if we didn't delete the
1772
                    // leaf, as erasing advances by itself.
1773
0
                    art_iterator_next(&it1);
1774
0
                }
1775
0
                art_iterator_next(&it2);
1776
0
            }
1777
0
        }
1778
0
        if (!it2_present || compare_result < 0) {
1779
            // Cases 1 and 2a: it1 is the only iterator or is before it2.
1780
0
            art_iterator_next(&it1);
1781
0
        } else if (compare_result > 0) {
1782
            // Case 2c: it1 is after it2.
1783
0
            art_iterator_next(&it2);
1784
0
        }
1785
0
    }
1786
0
}
1787
1788
/**
1789
 * Flips the leaf at high48 in the range [min, max), adding the result to
1790
 * `r2`. If the high48 key is not found in `r1`, a new container is created.
1791
 */
1792
static void roaring64_flip_leaf(const roaring64_bitmap_t *r1,
1793
                                roaring64_bitmap_t *r2, uint8_t high48[],
1794
0
                                uint32_t min, uint32_t max) {
1795
0
    leaf_t *leaf1 = (leaf_t *)art_find(&r1->art, high48);
1796
0
    uint8_t typecode2;
1797
0
    container_t *container2;
1798
0
    if (leaf1 == NULL) {
1799
        // No container at this key, create a full container.
1800
0
        container2 = container_range_of_ones(min, max, &typecode2);
1801
0
    } else if (min == 0 && max > 0xFFFF) {
1802
        // Flip whole container.
1803
0
        container2 = container_not(get_container(r1, *leaf1),
1804
0
                                   get_typecode(*leaf1), &typecode2);
1805
0
    } else {
1806
        // Partially flip a container.
1807
0
        container2 =
1808
0
            container_not_range(get_container(r1, *leaf1), get_typecode(*leaf1),
1809
0
                                min, max, &typecode2);
1810
0
    }
1811
0
    if (container_nonzero_cardinality(container2, typecode2)) {
1812
0
        leaf_t leaf2 = add_container(r2, container2, typecode2);
1813
0
        art_insert(&r2->art, high48, (art_val_t)leaf2);
1814
0
    } else {
1815
0
        container_free(container2, typecode2);
1816
0
    }
1817
0
}
1818
1819
/**
1820
 * Flips the leaf at high48 in the range [min, max). If the high48 key is
1821
 * not found in the bitmap, a new container is created. Deletes the leaf and
1822
 * associated container if the negation results in an empty range.
1823
 */
1824
static void roaring64_flip_leaf_inplace(roaring64_bitmap_t *r, uint8_t high48[],
1825
0
                                        uint32_t min, uint32_t max) {
1826
0
    leaf_t *leaf = (leaf_t *)art_find(&r->art, high48);
1827
0
    container_t *container2;
1828
0
    uint8_t typecode2;
1829
0
    if (leaf == NULL) {
1830
        // No container at this key, insert a full container.
1831
0
        container2 = container_range_of_ones(min, max, &typecode2);
1832
0
        leaf_t new_leaf = add_container(r, container2, typecode2);
1833
0
        art_insert(&r->art, high48, (art_val_t)new_leaf);
1834
0
        return;
1835
0
    }
1836
1837
0
    if (min == 0 && max > 0xFFFF) {
1838
        // Flip whole container.
1839
0
        container2 = container_inot(get_container(r, *leaf),
1840
0
                                    get_typecode(*leaf), &typecode2);
1841
0
    } else {
1842
        // Partially flip a container.
1843
0
        container2 = container_inot_range(
1844
0
            get_container(r, *leaf), get_typecode(*leaf), min, max, &typecode2);
1845
0
    }
1846
1847
0
    if (container_nonzero_cardinality(container2, typecode2)) {
1848
0
        replace_container(r, leaf, container2, typecode2);
1849
0
    } else {
1850
0
        bool erased = art_erase(&r->art, high48, NULL);
1851
0
        assert(erased);
1852
0
        (void)erased;
1853
0
        container_free(container2, typecode2);
1854
0
        remove_container(r, *leaf);
1855
0
    }
1856
0
}
1857
1858
roaring64_bitmap_t *roaring64_bitmap_flip(const roaring64_bitmap_t *r,
1859
0
                                          uint64_t min, uint64_t max) {
1860
0
    if (min >= max) {
1861
0
        return roaring64_bitmap_copy(r);
1862
0
    }
1863
0
    return roaring64_bitmap_flip_closed(r, min, max - 1);
1864
0
}
1865
1866
roaring64_bitmap_t *roaring64_bitmap_flip_closed(const roaring64_bitmap_t *r1,
1867
0
                                                 uint64_t min, uint64_t max) {
1868
0
    if (min > max) {
1869
0
        return roaring64_bitmap_copy(r1);
1870
0
    }
1871
0
    uint8_t min_high48_key[ART_KEY_BYTES];
1872
0
    uint16_t min_low16 = split_key(min, min_high48_key);
1873
0
    uint8_t max_high48_key[ART_KEY_BYTES];
1874
0
    uint16_t max_low16 = split_key(max, max_high48_key);
1875
0
    uint64_t min_high48_bits = (min & 0xFFFFFFFFFFFF0000ULL) >> 16;
1876
0
    uint64_t max_high48_bits = (max & 0xFFFFFFFFFFFF0000ULL) >> 16;
1877
1878
0
    roaring64_bitmap_t *r2 = roaring64_bitmap_create();
1879
0
    art_iterator_t it = art_init_iterator((art_t *)&r1->art, /*first=*/true);
1880
1881
    // Copy the containers before min unchanged.
1882
0
    while (it.value != NULL && compare_high48(it.key, min_high48_key) < 0) {
1883
0
        leaf_t leaf1 = (leaf_t)*it.value;
1884
0
        uint8_t typecode2 = get_typecode(leaf1);
1885
0
        container_t *container2 = get_copy_of_container(
1886
0
            get_container(r1, leaf1), &typecode2, /*copy_on_write=*/false);
1887
0
        leaf_t leaf2 = add_container(r2, container2, typecode2);
1888
0
        art_insert(&r2->art, it.key, (art_val_t)leaf2);
1889
0
        art_iterator_next(&it);
1890
0
    }
1891
1892
    // Flip the range (including non-existent containers!) between min and
1893
    // max.
1894
0
    for (uint64_t high48_bits = min_high48_bits; high48_bits <= max_high48_bits;
1895
0
         high48_bits++) {
1896
0
        uint8_t current_high48_key[ART_KEY_BYTES];
1897
0
        split_key(high48_bits << 16, current_high48_key);
1898
1899
0
        uint32_t min_container = 0;
1900
0
        if (high48_bits == min_high48_bits) {
1901
0
            min_container = min_low16;
1902
0
        }
1903
0
        uint32_t max_container = 0xFFFF + 1;  // Exclusive range.
1904
0
        if (high48_bits == max_high48_bits) {
1905
0
            max_container = max_low16 + 1;  // Exclusive.
1906
0
        }
1907
1908
0
        roaring64_flip_leaf(r1, r2, current_high48_key, min_container,
1909
0
                            max_container);
1910
0
    }
1911
1912
    // Copy the containers after max unchanged.
1913
0
    it = art_upper_bound((art_t *)&r1->art, max_high48_key);
1914
0
    while (it.value != NULL) {
1915
0
        leaf_t leaf1 = (leaf_t)*it.value;
1916
0
        uint8_t typecode2 = get_typecode(leaf1);
1917
0
        container_t *container2 = get_copy_of_container(
1918
0
            get_container(r1, leaf1), &typecode2, /*copy_on_write=*/false);
1919
0
        leaf_t leaf2 = add_container(r2, container2, typecode2);
1920
0
        art_insert(&r2->art, it.key, (art_val_t)leaf2);
1921
0
        art_iterator_next(&it);
1922
0
    }
1923
1924
0
    return r2;
1925
0
}
1926
1927
void roaring64_bitmap_flip_inplace(roaring64_bitmap_t *r, uint64_t min,
1928
0
                                   uint64_t max) {
1929
0
    if (min >= max) {
1930
0
        return;
1931
0
    }
1932
0
    roaring64_bitmap_flip_closed_inplace(r, min, max - 1);
1933
0
}
1934
1935
void roaring64_bitmap_flip_closed_inplace(roaring64_bitmap_t *r, uint64_t min,
1936
0
                                          uint64_t max) {
1937
0
    if (min > max) {
1938
0
        return;
1939
0
    }
1940
0
    uint16_t min_low16 = (uint16_t)min;
1941
0
    uint16_t max_low16 = (uint16_t)max;
1942
0
    uint64_t min_high48_bits = (min & 0xFFFFFFFFFFFF0000ULL) >> 16;
1943
0
    uint64_t max_high48_bits = (max & 0xFFFFFFFFFFFF0000ULL) >> 16;
1944
1945
    // Flip the range (including non-existent containers!) between min and
1946
    // max.
1947
0
    for (uint64_t high48_bits = min_high48_bits; high48_bits <= max_high48_bits;
1948
0
         high48_bits++) {
1949
0
        uint8_t current_high48_key[ART_KEY_BYTES];
1950
0
        split_key(high48_bits << 16, current_high48_key);
1951
1952
0
        uint32_t min_container = 0;
1953
0
        if (high48_bits == min_high48_bits) {
1954
0
            min_container = min_low16;
1955
0
        }
1956
0
        uint32_t max_container = 0xFFFF + 1;  // Exclusive range.
1957
0
        if (high48_bits == max_high48_bits) {
1958
0
            max_container = max_low16 + 1;  // Exclusive.
1959
0
        }
1960
1961
0
        roaring64_flip_leaf_inplace(r, current_high48_key, min_container,
1962
0
                                    max_container);
1963
0
    }
1964
0
}
1965
1966
roaring64_bitmap_t *roaring64_bitmap_add_offset_signed(
1967
0
    const roaring64_bitmap_t *r, bool positive, uint64_t offset) {
1968
0
    if (offset == 0) {
1969
0
        return roaring64_bitmap_copy(r);
1970
0
    }
1971
1972
0
    roaring64_bitmap_t *answer = roaring64_bitmap_create();
1973
1974
    // Decompose the offset into a signed container-level shift and an
1975
    // intra-container shift. For negative offsets the low 16 bits wrap: e.g.
1976
    // -1 = container_offset(-1) + in_offset(0xffff), because shifting by -1
1977
    // container is a shift of -0x1_0000, so we need to shift up within
1978
    // containers to get back to -1
1979
0
    uint16_t low16 = (uint16_t)offset;
1980
0
    int64_t container_offset;
1981
0
    uint16_t in_offset;
1982
0
    if (positive) {
1983
0
        container_offset = (int64_t)(offset >> 16);
1984
0
        in_offset = low16;
1985
0
    } else if (low16 == 0) {
1986
0
        container_offset = -(int64_t)(offset >> 16);
1987
0
        in_offset = 0;
1988
0
    } else {
1989
0
        container_offset = -(int64_t)(offset >> 16) - 1;
1990
0
        in_offset = (uint16_t)-low16;
1991
0
    }
1992
1993
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/true);
1994
1995
0
    if (in_offset == 0) {
1996
0
        while (it.value != NULL) {
1997
0
            leaf_t leaf = (leaf_t)*it.value;
1998
0
            int64_t k =
1999
0
                (int64_t)(combine_key(it.key, 0) >> 16) + container_offset;
2000
0
            if ((uint64_t)k < (uint64_t)1 << 48) {
2001
0
                uint8_t new_high48[ART_KEY_BYTES];
2002
0
                split_key((uint64_t)k << 16, new_high48);
2003
0
                uint8_t typecode = get_typecode(leaf);
2004
0
                container_t *container =
2005
0
                    get_copy_of_container(get_container(r, leaf), &typecode,
2006
0
                                          /*copy_on_write=*/false);
2007
0
                leaf_t new_leaf = add_container(answer, container, typecode);
2008
0
                art_insert(&answer->art, new_high48, (art_val_t)new_leaf);
2009
0
            }
2010
0
            art_iterator_next(&it);
2011
0
        }
2012
0
        return answer;
2013
0
    }
2014
2015
    // Track the most recently inserted hi container so that the next
2016
    // iteration's lo can merge with it without re-searching the ART.
2017
0
    leaf_t *prev_hi_leaf = NULL;
2018
0
    int64_t prev_hi_k = -1;
2019
2020
0
    while (it.value != NULL) {
2021
0
        leaf_t leaf = (leaf_t)*it.value;
2022
0
        int64_t k = (int64_t)(combine_key(it.key, 0) >> 16) + container_offset;
2023
2024
0
        container_t *lo = NULL, *hi = NULL;
2025
0
        container_t **lo_ptr = NULL, **hi_ptr = NULL;
2026
2027
0
        if ((uint64_t)k < (uint64_t)1 << 48) {
2028
0
            lo_ptr = &lo;
2029
0
        }
2030
0
        if ((uint64_t)(k + 1) < (uint64_t)1 << 48) {
2031
0
            hi_ptr = &hi;
2032
0
        }
2033
0
        if (lo_ptr == NULL && hi_ptr == NULL) {
2034
0
            art_iterator_next(&it);
2035
0
            continue;
2036
0
        }
2037
2038
0
        uint8_t typecode = get_typecode(leaf);
2039
0
        const container_t *c =
2040
0
            container_unwrap_shared(get_container(r, leaf), &typecode);
2041
0
        container_add_offset(c, typecode, lo_ptr, hi_ptr, in_offset);
2042
2043
0
        if (lo != NULL) {
2044
0
            if (prev_hi_leaf != NULL && prev_hi_k == k) {
2045
0
                uint8_t existing_type = get_typecode(*prev_hi_leaf);
2046
0
                container_t *existing_c = get_container(answer, *prev_hi_leaf);
2047
0
                uint8_t merged_type;
2048
0
                container_t *merged_c = container_ior(
2049
0
                    existing_c, existing_type, lo, typecode, &merged_type);
2050
0
                if (merged_c != existing_c) {
2051
0
                    container_free(existing_c, existing_type);
2052
0
                }
2053
0
                replace_container(answer, prev_hi_leaf, merged_c, merged_type);
2054
0
                container_free(lo, typecode);
2055
0
            } else {
2056
0
                uint8_t lo_high48[ART_KEY_BYTES];
2057
0
                split_key((uint64_t)k << 16, lo_high48);
2058
0
                leaf_t new_leaf = add_container(answer, lo, typecode);
2059
0
                art_insert(&answer->art, lo_high48, (art_val_t)new_leaf);
2060
0
            }
2061
0
        }
2062
2063
0
        prev_hi_leaf = NULL;
2064
0
        if (hi != NULL) {
2065
0
            uint8_t hi_high48[ART_KEY_BYTES];
2066
0
            split_key((uint64_t)(k + 1) << 16, hi_high48);
2067
0
            leaf_t new_leaf = add_container(answer, hi, typecode);
2068
0
            prev_hi_leaf = (leaf_t *)art_insert(&answer->art, hi_high48,
2069
0
                                                (art_val_t)new_leaf);
2070
0
            prev_hi_k = k + 1;
2071
0
        }
2072
2073
0
        art_iterator_next(&it);
2074
0
    }
2075
2076
    // Repair containers (e.g., convert low-cardinality bitset containers to
2077
    // array containers after lazy union operations).
2078
0
    art_iterator_t repair_it = art_init_iterator(&answer->art, /*first=*/true);
2079
0
    while (repair_it.value != NULL) {
2080
0
        leaf_t *leaf_ptr = (leaf_t *)repair_it.value;
2081
0
        uint8_t typecode = get_typecode(*leaf_ptr);
2082
0
        container_t *repaired = container_repair_after_lazy(
2083
0
            get_container(answer, *leaf_ptr), &typecode);
2084
0
        replace_container(answer, leaf_ptr, repaired, typecode);
2085
0
        art_iterator_next(&repair_it);
2086
0
    }
2087
2088
0
    return answer;
2089
0
}
2090
2091
// Returns the number of distinct high 32-bit entries in the bitmap.
2092
0
static inline uint64_t count_high32(const roaring64_bitmap_t *r) {
2093
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/true);
2094
0
    uint64_t high32_count = 0;
2095
0
    uint32_t prev_high32 = 0;
2096
0
    while (it.value != NULL) {
2097
0
        uint32_t current_high32 = (uint32_t)(combine_key(it.key, 0) >> 32);
2098
0
        if (high32_count == 0 || prev_high32 != current_high32) {
2099
0
            high32_count++;
2100
0
            prev_high32 = current_high32;
2101
0
        }
2102
0
        art_iterator_next(&it);
2103
0
    }
2104
0
    return high32_count;
2105
0
}
2106
2107
// Frees the (32-bit!) bitmap without freeing the containers.
2108
0
static inline void roaring_bitmap_free_without_containers(roaring_bitmap_t *r) {
2109
0
    ra_clear_without_containers(&r->high_low_container);
2110
0
    roaring_free(r);
2111
0
}
2112
2113
0
size_t roaring64_bitmap_portable_size_in_bytes(const roaring64_bitmap_t *r) {
2114
    // https://github.com/RoaringBitmap/RoaringFormatSpec#extension-for-64-bit-implementations
2115
0
    size_t size = 0;
2116
2117
    // Write as uint64 the distinct number of "buckets", where a bucket is
2118
    // defined as the most significant 32 bits of an element.
2119
0
    uint64_t high32_count;
2120
0
    size += sizeof(high32_count);
2121
2122
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/true);
2123
0
    uint32_t prev_high32 = 0;
2124
0
    roaring_bitmap_t *bitmap32 = NULL;
2125
2126
    // Iterate through buckets ordered by increasing keys.
2127
0
    while (it.value != NULL) {
2128
0
        uint32_t current_high32 = (uint32_t)(combine_key(it.key, 0) >> 32);
2129
0
        if (bitmap32 == NULL || prev_high32 != current_high32) {
2130
0
            if (bitmap32 != NULL) {
2131
                // Write as uint32 the most significant 32 bits of the
2132
                // bucket.
2133
0
                size += sizeof(prev_high32);
2134
2135
                // Write the 32-bit Roaring bitmaps representing the least
2136
                // significant bits of a set of elements.
2137
0
                size += roaring_bitmap_portable_size_in_bytes(bitmap32);
2138
0
                roaring_bitmap_free_without_containers(bitmap32);
2139
0
            }
2140
2141
            // Start a new 32-bit bitmap with the current high 32 bits.
2142
0
            art_iterator_t it2 = it;
2143
0
            uint32_t containers_with_high32 = 0;
2144
0
            while (it2.value != NULL && (uint32_t)(combine_key(it2.key, 0) >>
2145
0
                                                   32) == current_high32) {
2146
0
                containers_with_high32++;
2147
0
                art_iterator_next(&it2);
2148
0
            }
2149
0
            bitmap32 =
2150
0
                roaring_bitmap_create_with_capacity(containers_with_high32);
2151
2152
0
            prev_high32 = current_high32;
2153
0
        }
2154
0
        leaf_t leaf = (leaf_t)*it.value;
2155
0
        ra_append(&bitmap32->high_low_container,
2156
0
                  (uint16_t)(current_high32 >> 16), get_container(r, leaf),
2157
0
                  get_typecode(leaf));
2158
0
        art_iterator_next(&it);
2159
0
    }
2160
2161
0
    if (bitmap32 != NULL) {
2162
        // Write as uint32 the most significant 32 bits of the bucket.
2163
0
        size += sizeof(prev_high32);
2164
2165
        // Write the 32-bit Roaring bitmaps representing the least
2166
        // significant bits of a set of elements.
2167
0
        size += roaring_bitmap_portable_size_in_bytes(bitmap32);
2168
0
        roaring_bitmap_free_without_containers(bitmap32);
2169
0
    }
2170
2171
0
    return size;
2172
0
}
2173
2174
size_t roaring64_bitmap_portable_serialize(const roaring64_bitmap_t *r,
2175
0
                                           char *buf) {
2176
    // https://github.com/RoaringBitmap/RoaringFormatSpec#extension-for-64-bit-implementations
2177
0
    if (buf == NULL) {
2178
0
        return 0;
2179
0
    }
2180
0
    const char *initial_buf = buf;
2181
2182
    // Write as uint64 the distinct number of "buckets", where a bucket is
2183
    // defined as the most significant 32 bits of an element.
2184
0
    uint64_t high32_count = count_high32(r);
2185
0
    uint64_t high32_count_le = croaring_htole64(high32_count);
2186
0
    memcpy(buf, &high32_count_le, sizeof(high32_count_le));
2187
0
    buf += sizeof(high32_count);
2188
2189
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/true);
2190
0
    uint32_t prev_high32 = 0;
2191
0
    roaring_bitmap_t *bitmap32 = NULL;
2192
2193
    // Iterate through buckets ordered by increasing keys.
2194
0
    while (it.value != NULL) {
2195
0
        uint64_t current_high48 = combine_key(it.key, 0);
2196
0
        uint32_t current_high32 = (uint32_t)(current_high48 >> 32);
2197
0
        if (bitmap32 == NULL || prev_high32 != current_high32) {
2198
0
            if (bitmap32 != NULL) {
2199
                // Write as uint32 the most significant 32 bits of the
2200
                // bucket.
2201
0
                uint32_t prev_high32_le = croaring_htole32(prev_high32);
2202
0
                memcpy(buf, &prev_high32_le, sizeof(prev_high32_le));
2203
0
                buf += sizeof(prev_high32);
2204
2205
                // Write the 32-bit Roaring bitmaps representing the least
2206
                // significant bits of a set of elements.
2207
0
                buf += roaring_bitmap_portable_serialize(bitmap32, buf);
2208
0
                roaring_bitmap_free_without_containers(bitmap32);
2209
0
            }
2210
2211
            // Start a new 32-bit bitmap with the current high 32 bits.
2212
0
            art_iterator_t it2 = it;
2213
0
            uint32_t containers_with_high32 = 0;
2214
0
            while (it2.value != NULL &&
2215
0
                   (uint32_t)combine_key(it2.key, 0) == current_high32) {
2216
0
                containers_with_high32++;
2217
0
                art_iterator_next(&it2);
2218
0
            }
2219
0
            bitmap32 =
2220
0
                roaring_bitmap_create_with_capacity(containers_with_high32);
2221
2222
0
            prev_high32 = current_high32;
2223
0
        }
2224
0
        leaf_t leaf = (leaf_t)*it.value;
2225
0
        ra_append(&bitmap32->high_low_container,
2226
0
                  (uint16_t)(current_high48 >> 16), get_container(r, leaf),
2227
0
                  get_typecode(leaf));
2228
0
        art_iterator_next(&it);
2229
0
    }
2230
2231
0
    if (bitmap32 != NULL) {
2232
        // Write as uint32 the most significant 32 bits of the bucket.
2233
0
        uint32_t prev_high32_le = croaring_htole32(prev_high32);
2234
0
        memcpy(buf, &prev_high32_le, sizeof(prev_high32_le));
2235
0
        buf += sizeof(prev_high32);
2236
2237
        // Write the 32-bit Roaring bitmaps representing the least
2238
        // significant bits of a set of elements.
2239
0
        buf += roaring_bitmap_portable_serialize(bitmap32, buf);
2240
0
        roaring_bitmap_free_without_containers(bitmap32);
2241
0
    }
2242
2243
0
    return buf - initial_buf;
2244
0
}
2245
2246
size_t roaring64_bitmap_portable_deserialize_size(const char *buf,
2247
0
                                                  size_t maxbytes) {
2248
    // https://github.com/RoaringBitmap/RoaringFormatSpec#extension-for-64-bit-implementations
2249
0
    if (buf == NULL) {
2250
0
        return 0;
2251
0
    }
2252
0
    size_t read_bytes = 0;
2253
2254
    // Read as uint64 the distinct number of "buckets", where a bucket is
2255
    // defined as the most significant 32 bits of an element.
2256
0
    uint64_t buckets;
2257
0
    if (read_bytes + sizeof(buckets) > maxbytes) {
2258
0
        return 0;
2259
0
    }
2260
0
    memcpy(&buckets, buf, sizeof(buckets));
2261
0
    buckets = croaring_letoh64(buckets);
2262
0
    buf += sizeof(buckets);
2263
0
    read_bytes += sizeof(buckets);
2264
2265
    // Buckets should be 32 bits with 4 bits of zero padding.
2266
0
    if (buckets > UINT32_MAX) {
2267
0
        return 0;
2268
0
    }
2269
2270
    // Iterate through buckets ordered by increasing keys.
2271
0
    for (uint64_t bucket = 0; bucket < buckets; ++bucket) {
2272
        // Read as uint32 the most significant 32 bits of the bucket.
2273
0
        uint32_t high32;
2274
0
        if (read_bytes + sizeof(high32) > maxbytes) {
2275
0
            return 0;
2276
0
        }
2277
0
        buf += sizeof(high32);
2278
0
        read_bytes += sizeof(high32);
2279
2280
        // Read the 32-bit Roaring bitmaps representing the least
2281
        // significant bits of a set of elements.
2282
0
        size_t bitmap32_size = roaring_bitmap_portable_deserialize_size(
2283
0
            buf, maxbytes - read_bytes);
2284
0
        if (bitmap32_size == 0) {
2285
0
            return 0;
2286
0
        }
2287
0
        buf += bitmap32_size;
2288
0
        read_bytes += bitmap32_size;
2289
0
    }
2290
0
    return read_bytes;
2291
0
}
2292
2293
roaring64_bitmap_t *roaring64_bitmap_portable_deserialize_safe(
2294
0
    const char *buf, size_t maxbytes) {
2295
    // https://github.com/RoaringBitmap/RoaringFormatSpec#extension-for-64-bit-implementations
2296
0
    if (buf == NULL) {
2297
0
        return NULL;
2298
0
    }
2299
0
    size_t read_bytes = 0;
2300
2301
    // Read as uint64 the distinct number of "buckets", where a bucket is
2302
    // defined as the most significant 32 bits of an element.
2303
0
    uint64_t buckets;
2304
0
    if (read_bytes + sizeof(buckets) > maxbytes) {
2305
0
        return NULL;
2306
0
    }
2307
0
    memcpy(&buckets, buf, sizeof(buckets));
2308
0
    buckets = croaring_letoh64(buckets);
2309
0
    buf += sizeof(buckets);
2310
0
    read_bytes += sizeof(buckets);
2311
2312
    // Buckets should be 32 bits with 4 bits of zero padding.
2313
0
    if (buckets > UINT32_MAX) {
2314
0
        return NULL;
2315
0
    }
2316
2317
0
    roaring64_bitmap_t *r = roaring64_bitmap_create();
2318
    // Iterate through buckets ordered by increasing keys.
2319
0
    int64_t previous_high32 = -1;
2320
0
    for (uint64_t bucket = 0; bucket < buckets; ++bucket) {
2321
        // Read as uint32 the most significant 32 bits of the bucket.
2322
0
        uint32_t high32;
2323
0
        if (read_bytes + sizeof(high32) > maxbytes) {
2324
0
            roaring64_bitmap_free(r);
2325
0
            return NULL;
2326
0
        }
2327
0
        memcpy(&high32, buf, sizeof(high32));
2328
0
        high32 = croaring_letoh32(high32);
2329
0
        buf += sizeof(high32);
2330
0
        read_bytes += sizeof(high32);
2331
        // High 32 bits must be strictly increasing.
2332
0
        if (high32 <= previous_high32) {
2333
0
            roaring64_bitmap_free(r);
2334
0
            return NULL;
2335
0
        }
2336
0
        previous_high32 = high32;
2337
2338
        // Read the 32-bit Roaring bitmaps representing the least
2339
        // significant bits of a set of elements.
2340
0
        size_t bitmap32_size = roaring_bitmap_portable_deserialize_size(
2341
0
            buf, maxbytes - read_bytes);
2342
0
        if (bitmap32_size == 0) {
2343
0
            roaring64_bitmap_free(r);
2344
0
            return NULL;
2345
0
        }
2346
2347
0
        roaring_bitmap_t *bitmap32 = roaring_bitmap_portable_deserialize_safe(
2348
0
            buf, maxbytes - read_bytes);
2349
0
        if (bitmap32 == NULL) {
2350
0
            roaring64_bitmap_free(r);
2351
0
            return NULL;
2352
0
        }
2353
0
        buf += bitmap32_size;
2354
0
        read_bytes += bitmap32_size;
2355
2356
        // While we don't attempt to validate much, we must ensure that there
2357
        // is no duplication in the high 48 bits - inserting into the ART
2358
        // assumes (or UB) no duplicate keys. The top 32 bits must be unique
2359
        // because we check for strict increasing values of  high32, but we
2360
        // must also ensure the top 16 bits within each 32-bit bitmap are also
2361
        // at least unique (we ensure they're strictly increasing as well,
2362
        // which they must be for a _valid_ bitmap, since it's cheaper to check)
2363
0
        int32_t last_bitmap_key = -1;
2364
0
        for (int i = 0; i < bitmap32->high_low_container.size; i++) {
2365
0
            uint16_t key = bitmap32->high_low_container.keys[i];
2366
0
            if (key <= last_bitmap_key) {
2367
0
                roaring_bitmap_free(bitmap32);
2368
0
                roaring64_bitmap_free(r);
2369
0
                return NULL;
2370
0
            }
2371
0
            last_bitmap_key = key;
2372
0
        }
2373
2374
        // Insert all containers of the 32-bit bitmap into the 64-bit bitmap.
2375
0
        move_from_roaring32_offset(r, bitmap32, high32);
2376
0
        roaring_bitmap_free(bitmap32);
2377
0
    }
2378
0
    return r;
2379
0
}
2380
2381
// Returns an "element count" for the given container. This has a different
2382
// meaning for each container type, but the purpose is the minimal information
2383
// required to serialize the container metadata.
2384
static inline uint32_t container_get_element_count(const container_t *c,
2385
0
                                                   uint8_t typecode) {
2386
0
    switch (typecode) {
2387
0
        case BITSET_CONTAINER_TYPE: {
2388
0
            return ((bitset_container_t *)c)->cardinality;
2389
0
        }
2390
0
        case ARRAY_CONTAINER_TYPE: {
2391
0
            return ((array_container_t *)c)->cardinality;
2392
0
        }
2393
0
        case RUN_CONTAINER_TYPE: {
2394
0
            return ((run_container_t *)c)->n_runs;
2395
0
        }
2396
0
        default: {
2397
0
            assert(false);
2398
0
            roaring_unreachable;
2399
0
            return 0;
2400
0
        }
2401
0
    }
2402
0
}
2403
2404
static inline size_t container_get_frozen_size(const container_t *c,
2405
0
                                               uint8_t typecode) {
2406
0
    switch (typecode) {
2407
0
        case BITSET_CONTAINER_TYPE: {
2408
0
            return BITSET_CONTAINER_SIZE_IN_WORDS * sizeof(uint64_t);
2409
0
        }
2410
0
        case ARRAY_CONTAINER_TYPE: {
2411
0
            return container_get_element_count(c, typecode) * sizeof(uint16_t);
2412
0
        }
2413
0
        case RUN_CONTAINER_TYPE: {
2414
0
            return container_get_element_count(c, typecode) * sizeof(rle16_t);
2415
0
        }
2416
0
        default: {
2417
0
            assert(false);
2418
0
            roaring_unreachable;
2419
0
            return 0;
2420
0
        }
2421
0
    }
2422
0
}
2423
2424
0
uint64_t align_size(uint64_t size, uint64_t alignment) {
2425
0
    return (size + alignment - 1) & ~(alignment - 1);
2426
0
}
2427
2428
0
size_t roaring64_bitmap_frozen_size_in_bytes(const roaring64_bitmap_t *r) {
2429
0
    if (!is_shrunken(r)) {
2430
0
        return 0;
2431
0
    }
2432
    // Flags.
2433
0
    uint64_t size = sizeof(r->flags);
2434
    // Container count.
2435
0
    size += sizeof(r->capacity);
2436
    // Container element counts.
2437
0
    size += r->capacity * sizeof(uint16_t);
2438
    // Total container sizes.
2439
0
    size += 3 * sizeof(uint64_t);
2440
    // ART (8 byte aligned).
2441
0
    size = align_size(size, 8);
2442
0
    size += art_size_in_bytes(&r->art);
2443
2444
0
    uint64_t total_sizes[4] =
2445
0
        CROARING_ZERO_INITIALIZER;  // Indexed by typecode.
2446
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/true);
2447
0
    while (it.value != NULL) {
2448
0
        leaf_t leaf = (leaf_t)*it.value;
2449
0
        uint8_t typecode = get_typecode(leaf);
2450
0
        total_sizes[typecode] +=
2451
0
            container_get_frozen_size(get_container(r, leaf), typecode);
2452
0
        art_iterator_next(&it);
2453
0
    }
2454
    // Containers (aligned).
2455
0
    size = align_size(size, CROARING_BITSET_ALIGNMENT);
2456
0
    size += total_sizes[BITSET_CONTAINER_TYPE];
2457
0
    size = align_size(size, alignof(rle16_t));
2458
0
    size += total_sizes[ARRAY_CONTAINER_TYPE];
2459
0
    size = align_size(size, alignof(uint16_t));
2460
0
    size += total_sizes[RUN_CONTAINER_TYPE];
2461
    // Padding to make overall size a multiple of required alignment.
2462
0
    size = align_size(size, CROARING_BITSET_ALIGNMENT);
2463
0
    return size;
2464
0
}
2465
2466
static inline void container_frozen_serialize(const container_t *container,
2467
                                              uint8_t typecode,
2468
                                              uint64_t **bitsets,
2469
                                              uint16_t **arrays,
2470
0
                                              rle16_t **runs) {
2471
0
    size_t size = container_get_frozen_size(container, typecode);
2472
0
    switch (typecode) {
2473
0
        case BITSET_CONTAINER_TYPE: {
2474
0
            bitset_container_t *bitset = (bitset_container_t *)container;
2475
0
            memcpy(*bitsets, bitset->words, size);
2476
0
            *bitsets += BITSET_CONTAINER_SIZE_IN_WORDS;
2477
0
            break;
2478
0
        }
2479
0
        case ARRAY_CONTAINER_TYPE: {
2480
0
            array_container_t *array = (array_container_t *)container;
2481
0
            memcpy(*arrays, array->array, size);
2482
0
            *arrays += container_get_element_count(container, typecode);
2483
0
            break;
2484
0
        }
2485
0
        case RUN_CONTAINER_TYPE: {
2486
0
            run_container_t *run = (run_container_t *)container;
2487
0
            memcpy(*runs, run->runs, size);
2488
0
            *runs += container_get_element_count(container, typecode);
2489
0
            break;
2490
0
        }
2491
0
        default: {
2492
0
            assert(false);
2493
0
            roaring_unreachable;
2494
0
        }
2495
0
    }
2496
0
}
2497
2498
static inline char *pad_align(char *buf, const char *initial_buf,
2499
0
                              size_t alignment) {
2500
0
    uint64_t buf_size = buf - initial_buf;
2501
0
    uint64_t pad = align_size(buf_size, alignment) - buf_size;
2502
0
    memset(buf, 0, pad);
2503
0
    return buf + pad;
2504
0
}
2505
2506
size_t roaring64_bitmap_frozen_serialize(const roaring64_bitmap_t *r,
2507
0
                                         char *buf) {
2508
0
    if (buf == NULL) {
2509
0
        return 0;
2510
0
    }
2511
0
    if (!is_shrunken(r)) {
2512
0
        return 0;
2513
0
    }
2514
0
    const char *initial_buf = buf;
2515
2516
    // Flags.
2517
0
    memcpy(buf, &r->flags, sizeof(r->flags));
2518
0
    buf += sizeof(r->flags);
2519
2520
    // Container count.
2521
0
    memcpy(buf, &r->capacity, sizeof(r->capacity));
2522
0
    buf += sizeof(r->capacity);
2523
2524
    // Container element counts.
2525
0
    uint64_t total_sizes[4] =
2526
0
        CROARING_ZERO_INITIALIZER;  // Indexed by typecode.
2527
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/true);
2528
0
    while (it.value != NULL) {
2529
0
        leaf_t leaf = (leaf_t)*it.value;
2530
0
        uint8_t typecode = get_typecode(leaf);
2531
0
        container_t *container = get_container(r, leaf);
2532
2533
0
        uint32_t elem_count = container_get_element_count(container, typecode);
2534
0
        uint16_t compressed_elem_count = (uint16_t)(elem_count - 1);
2535
0
        memcpy(buf, &compressed_elem_count, sizeof(compressed_elem_count));
2536
0
        buf += sizeof(compressed_elem_count);
2537
2538
0
        total_sizes[typecode] += container_get_frozen_size(container, typecode);
2539
0
        art_iterator_next(&it);
2540
0
    }
2541
2542
    // Total container sizes.
2543
0
    memcpy(buf, &(total_sizes[BITSET_CONTAINER_TYPE]), sizeof(uint64_t));
2544
0
    buf += sizeof(uint64_t);
2545
0
    memcpy(buf, &(total_sizes[RUN_CONTAINER_TYPE]), sizeof(uint64_t));
2546
0
    buf += sizeof(uint64_t);
2547
0
    memcpy(buf, &(total_sizes[ARRAY_CONTAINER_TYPE]), sizeof(uint64_t));
2548
0
    buf += sizeof(uint64_t);
2549
2550
    // ART.
2551
0
    buf = pad_align(buf, initial_buf, 8);
2552
0
    buf += art_serialize(&r->art, buf);
2553
2554
    // Containers (aligned).
2555
    // Runs before arrays as run elements are larger than array elements and
2556
    // smaller than bitset elements.
2557
0
    buf = pad_align(buf, initial_buf, CROARING_BITSET_ALIGNMENT);
2558
0
    uint64_t *bitsets = (uint64_t *)buf;
2559
0
    buf += total_sizes[BITSET_CONTAINER_TYPE];
2560
0
    buf = pad_align(buf, initial_buf, alignof(rle16_t));
2561
0
    rle16_t *runs = (rle16_t *)buf;
2562
0
    buf += total_sizes[RUN_CONTAINER_TYPE];
2563
0
    buf = pad_align(buf, initial_buf, alignof(uint16_t));
2564
0
    uint16_t *arrays = (uint16_t *)buf;
2565
0
    buf += total_sizes[ARRAY_CONTAINER_TYPE];
2566
2567
0
    it = art_init_iterator((art_t *)&r->art, /*first=*/true);
2568
0
    while (it.value != NULL) {
2569
0
        leaf_t leaf = (leaf_t)*it.value;
2570
0
        uint8_t typecode = get_typecode(leaf);
2571
0
        container_t *container = get_container(r, leaf);
2572
0
        container_frozen_serialize(container, typecode, &bitsets, &arrays,
2573
0
                                   &runs);
2574
0
        art_iterator_next(&it);
2575
0
    }
2576
2577
    // Padding to make overall size a multiple of required alignment.
2578
0
    buf = pad_align(buf, initial_buf, CROARING_BITSET_ALIGNMENT);
2579
2580
0
    return buf - initial_buf;
2581
0
}
2582
2583
static container_t *container_frozen_view(uint8_t typecode, uint32_t elem_count,
2584
                                          const uint64_t **bitsets,
2585
                                          const uint16_t **arrays,
2586
0
                                          const rle16_t **runs) {
2587
0
    switch (typecode) {
2588
0
        case BITSET_CONTAINER_TYPE: {
2589
0
            bitset_container_t *c = (bitset_container_t *)roaring_malloc(
2590
0
                sizeof(bitset_container_t));
2591
0
            c->cardinality = elem_count;
2592
0
            c->words = (uint64_t *)*bitsets;
2593
0
            *bitsets += BITSET_CONTAINER_SIZE_IN_WORDS;
2594
0
            return (container_t *)c;
2595
0
        }
2596
0
        case ARRAY_CONTAINER_TYPE: {
2597
0
            array_container_t *c =
2598
0
                (array_container_t *)roaring_malloc(sizeof(array_container_t));
2599
0
            c->cardinality = elem_count;
2600
0
            c->capacity = elem_count;
2601
0
            c->array = (uint16_t *)*arrays;
2602
0
            *arrays += elem_count;
2603
0
            return (container_t *)c;
2604
0
        }
2605
0
        case RUN_CONTAINER_TYPE: {
2606
0
            run_container_t *c =
2607
0
                (run_container_t *)roaring_malloc(sizeof(run_container_t));
2608
0
            c->n_runs = elem_count;
2609
0
            c->capacity = elem_count;
2610
0
            c->runs = (rle16_t *)*runs;
2611
0
            *runs += elem_count;
2612
0
            return (container_t *)c;
2613
0
        }
2614
0
        default: {
2615
0
            assert(false);
2616
0
            roaring_unreachable;
2617
0
            return NULL;
2618
0
        }
2619
0
    }
2620
0
}
2621
2622
roaring64_bitmap_t *roaring64_bitmap_frozen_view(const char *buf,
2623
0
                                                 size_t maxbytes) {
2624
0
    if (buf == NULL) {
2625
0
        return NULL;
2626
0
    }
2627
0
    if ((uintptr_t)buf % CROARING_BITSET_ALIGNMENT != 0) {
2628
0
        return NULL;
2629
0
    }
2630
2631
0
    roaring64_bitmap_t *r = roaring64_bitmap_create();
2632
2633
    // Flags.
2634
0
    if (maxbytes < sizeof(r->flags)) {
2635
0
        roaring64_bitmap_free(r);
2636
0
        return NULL;
2637
0
    }
2638
0
    memcpy(&r->flags, buf, sizeof(r->flags));
2639
0
    buf += sizeof(r->flags);
2640
0
    maxbytes -= sizeof(r->flags);
2641
0
    r->flags |= ROARING_FLAG_FROZEN;
2642
2643
    // Container count.
2644
0
    if (maxbytes < sizeof(r->capacity)) {
2645
0
        roaring64_bitmap_free(r);
2646
0
        return NULL;
2647
0
    }
2648
0
    memcpy(&r->capacity, buf, sizeof(r->capacity));
2649
0
    buf += sizeof(r->capacity);
2650
0
    maxbytes -= sizeof(r->capacity);
2651
2652
0
    r->containers =
2653
0
        (container_t **)roaring_malloc(r->capacity * sizeof(container_t *));
2654
2655
    // Container element counts.
2656
0
    if (maxbytes < r->capacity * sizeof(uint16_t)) {
2657
0
        roaring64_bitmap_free(r);
2658
0
        return NULL;
2659
0
    }
2660
0
    const char *elem_counts = buf;
2661
0
    buf += r->capacity * sizeof(uint16_t);
2662
0
    maxbytes -= r->capacity * sizeof(uint16_t);
2663
2664
    // Total container sizes.
2665
0
    uint64_t total_sizes[4];
2666
0
    if (maxbytes < sizeof(uint64_t) * 3) {
2667
0
        roaring64_bitmap_free(r);
2668
0
        return NULL;
2669
0
    }
2670
0
    memcpy(&(total_sizes[BITSET_CONTAINER_TYPE]), buf, sizeof(uint64_t));
2671
0
    buf += sizeof(uint64_t);
2672
0
    maxbytes -= sizeof(uint64_t);
2673
0
    memcpy(&(total_sizes[RUN_CONTAINER_TYPE]), buf, sizeof(uint64_t));
2674
0
    buf += sizeof(uint64_t);
2675
0
    maxbytes -= sizeof(uint64_t);
2676
0
    memcpy(&(total_sizes[ARRAY_CONTAINER_TYPE]), buf, sizeof(uint64_t));
2677
0
    buf += sizeof(uint64_t);
2678
0
    maxbytes -= sizeof(uint64_t);
2679
2680
    // ART (8 byte aligned).
2681
0
    buf = CROARING_ALIGN_BUF(buf, 8);
2682
0
    size_t art_size = art_frozen_view(buf, maxbytes, &r->art);
2683
0
    if (art_size == 0) {
2684
0
        roaring64_bitmap_free(r);
2685
0
        return NULL;
2686
0
    }
2687
0
    buf += art_size;
2688
0
    maxbytes -= art_size;
2689
2690
    // Containers (aligned).
2691
0
    const char *before_containers = buf;
2692
0
    buf = CROARING_ALIGN_BUF(buf, CROARING_BITSET_ALIGNMENT);
2693
0
    const uint64_t *bitsets = (const uint64_t *)buf;
2694
0
    buf += total_sizes[BITSET_CONTAINER_TYPE];
2695
0
    buf = CROARING_ALIGN_BUF(buf, alignof(rle16_t));
2696
0
    const rle16_t *runs = (const rle16_t *)buf;
2697
0
    buf += total_sizes[RUN_CONTAINER_TYPE];
2698
0
    buf = CROARING_ALIGN_BUF(buf, alignof(uint16_t));
2699
0
    const uint16_t *arrays = (const uint16_t *)buf;
2700
0
    buf += total_sizes[ARRAY_CONTAINER_TYPE];
2701
0
    if (maxbytes < (uint64_t)(buf - before_containers)) {
2702
0
        roaring64_bitmap_free(r);
2703
0
        return NULL;
2704
0
    }
2705
0
    maxbytes -= buf - before_containers;
2706
2707
    // Deserialize in ART iteration order.
2708
0
    art_iterator_t it = art_init_iterator(&r->art, /*first=*/true);
2709
0
    for (size_t i = 0; it.value != NULL; ++i) {
2710
0
        leaf_t leaf = (leaf_t)*it.value;
2711
0
        uint8_t typecode = get_typecode(leaf);
2712
2713
0
        uint16_t compressed_elem_count;
2714
0
        memcpy(&compressed_elem_count, elem_counts + (i * sizeof(uint16_t)),
2715
0
               sizeof(compressed_elem_count));
2716
0
        uint32_t elem_count = (uint32_t)(compressed_elem_count) + 1;
2717
2718
        // The container index is unrelated to the iteration order.
2719
0
        uint64_t index = get_index(leaf);
2720
0
        r->containers[index] = container_frozen_view(typecode, elem_count,
2721
0
                                                     &bitsets, &arrays, &runs);
2722
2723
0
        art_iterator_next(&it);
2724
0
    }
2725
2726
    // Padding to make overall size a multiple of required alignment.
2727
0
    buf = CROARING_ALIGN_BUF(buf, CROARING_BITSET_ALIGNMENT);
2728
2729
0
    return r;
2730
0
}
2731
2732
bool roaring64_bitmap_iterate(const roaring64_bitmap_t *r,
2733
0
                              roaring_iterator64 iterator, void *ptr) {
2734
0
    art_iterator_t it = art_init_iterator((art_t *)&r->art, /*first=*/true);
2735
0
    while (it.value != NULL) {
2736
0
        uint64_t high48 = combine_key(it.key, 0);
2737
0
        uint64_t high32 = high48 & 0xFFFFFFFF00000000ULL;
2738
0
        uint32_t low32 = high48;
2739
0
        leaf_t leaf = (leaf_t)*it.value;
2740
0
        if (!container_iterate64(get_container(r, leaf), get_typecode(leaf),
2741
0
                                 low32, iterator, high32, ptr)) {
2742
0
            return false;
2743
0
        }
2744
0
        art_iterator_next(&it);
2745
0
    }
2746
0
    return true;
2747
0
}
2748
2749
void roaring64_bitmap_to_uint64_array(const roaring64_bitmap_t *r,
2750
0
                                      uint64_t *out) {
2751
0
    roaring64_iterator_t it;  // gets initialized in the next line
2752
0
    roaring64_iterator_init_at(r, &it, /*first=*/true);
2753
0
    roaring64_iterator_read(&it, out, UINT64_MAX);
2754
0
}
2755
2756
0
roaring64_iterator_t *roaring64_iterator_create(const roaring64_bitmap_t *r) {
2757
0
    roaring64_iterator_t *it =
2758
0
        (roaring64_iterator_t *)roaring_malloc(sizeof(roaring64_iterator_t));
2759
0
    return roaring64_iterator_init_at(r, it, /*first=*/true);
2760
0
}
2761
2762
roaring64_iterator_t *roaring64_iterator_create_last(
2763
0
    const roaring64_bitmap_t *r) {
2764
0
    roaring64_iterator_t *it =
2765
0
        (roaring64_iterator_t *)roaring_malloc(sizeof(roaring64_iterator_t));
2766
0
    return roaring64_iterator_init_at(r, it, /*first=*/false);
2767
0
}
2768
2769
void roaring64_iterator_reinit(const roaring64_bitmap_t *r,
2770
0
                               roaring64_iterator_t *it) {
2771
0
    roaring64_iterator_init_at(r, it, /*first=*/true);
2772
0
}
2773
2774
void roaring64_iterator_reinit_last(const roaring64_bitmap_t *r,
2775
0
                                    roaring64_iterator_t *it) {
2776
0
    roaring64_iterator_init_at(r, it, /*first=*/false);
2777
0
}
2778
2779
0
roaring64_iterator_t *roaring64_iterator_copy(const roaring64_iterator_t *it) {
2780
0
    roaring64_iterator_t *new_it =
2781
0
        (roaring64_iterator_t *)roaring_malloc(sizeof(roaring64_iterator_t));
2782
0
    memcpy(new_it, it, sizeof(*it));
2783
0
    return new_it;
2784
0
}
2785
2786
0
void roaring64_iterator_free(roaring64_iterator_t *it) { roaring_free(it); }
2787
2788
0
bool roaring64_iterator_has_value(const roaring64_iterator_t *it) {
2789
0
    return it->has_value;
2790
0
}
2791
2792
0
uint64_t roaring64_iterator_value(const roaring64_iterator_t *it) {
2793
0
    return it->value;
2794
0
}
2795
2796
0
bool roaring64_iterator_advance(roaring64_iterator_t *it) {
2797
0
    if (it->art_it.value == NULL) {
2798
0
        if (it->saturated_forward) {
2799
0
            return (it->has_value = false);
2800
0
        }
2801
0
        roaring64_iterator_init_at(it->r, it, /*first=*/true);
2802
0
        return it->has_value;
2803
0
    }
2804
0
    leaf_t leaf = (leaf_t)*it->art_it.value;
2805
0
    uint16_t low16 = (uint16_t)it->value;
2806
0
    if (container_iterator_next(get_container(it->r, leaf), get_typecode(leaf),
2807
0
                                &it->container_it, &low16)) {
2808
0
        it->value = it->high48 | low16;
2809
0
        return (it->has_value = true);
2810
0
    }
2811
0
    if (art_iterator_next(&it->art_it)) {
2812
0
        return roaring64_iterator_init_at_leaf_first(it);
2813
0
    }
2814
0
    it->saturated_forward = true;
2815
0
    return (it->has_value = false);
2816
0
}
2817
2818
0
bool roaring64_iterator_previous(roaring64_iterator_t *it) {
2819
0
    if (it->art_it.value == NULL) {
2820
0
        if (!it->saturated_forward) {
2821
            // Saturated backward.
2822
0
            return (it->has_value = false);
2823
0
        }
2824
0
        roaring64_iterator_init_at(it->r, it, /*first=*/false);
2825
0
        return it->has_value;
2826
0
    }
2827
0
    leaf_t leaf = (leaf_t)*it->art_it.value;
2828
0
    uint16_t low16 = (uint16_t)it->value;
2829
0
    if (container_iterator_prev(get_container(it->r, leaf), get_typecode(leaf),
2830
0
                                &it->container_it, &low16)) {
2831
0
        it->value = it->high48 | low16;
2832
0
        return (it->has_value = true);
2833
0
    }
2834
0
    if (art_iterator_prev(&it->art_it)) {
2835
0
        return roaring64_iterator_init_at_leaf_last(it);
2836
0
    }
2837
0
    it->saturated_forward = false;  // Saturated backward.
2838
0
    return (it->has_value = false);
2839
0
}
2840
2841
bool roaring64_iterator_move_equalorlarger(roaring64_iterator_t *it,
2842
0
                                           uint64_t val) {
2843
0
    uint8_t val_high48[ART_KEY_BYTES];
2844
0
    uint16_t val_low16 = split_key(val, val_high48);
2845
0
    if (!it->has_value || it->high48 != (val & 0xFFFFFFFFFFFF0000)) {
2846
        // The ART iterator is before or after the high48 bits of `val` (or
2847
        // beyond the ART altogether), so we need to move to a leaf with a
2848
        // key equal or greater.
2849
0
        if (!art_iterator_lower_bound(&it->art_it, val_high48)) {
2850
            // Only smaller keys found.
2851
0
            it->saturated_forward = true;
2852
0
            return (it->has_value = false);
2853
0
        }
2854
0
        it->high48 = combine_key(it->art_it.key, 0);
2855
        // Fall through to the next if statement.
2856
0
    }
2857
2858
0
    if (it->high48 == (val & 0xFFFFFFFFFFFF0000)) {
2859
        // We're at equal high bits, check if a suitable value can be found
2860
        // in this container.
2861
0
        leaf_t leaf = (leaf_t)*it->art_it.value;
2862
0
        uint16_t low16 = (uint16_t)it->value;
2863
0
        if (container_iterator_lower_bound(
2864
0
                get_container(it->r, leaf), get_typecode(leaf),
2865
0
                &it->container_it, &low16, val_low16)) {
2866
0
            it->value = it->high48 | low16;
2867
0
            return (it->has_value = true);
2868
0
        }
2869
        // Only smaller entries in this container, move to the next.
2870
0
        if (!art_iterator_next(&it->art_it)) {
2871
0
            it->saturated_forward = true;
2872
0
            return (it->has_value = false);
2873
0
        }
2874
0
    }
2875
2876
    // We're at a leaf with high bits greater than `val`, so the first entry
2877
    // in this container is our result.
2878
0
    return roaring64_iterator_init_at_leaf_first(it);
2879
0
}
2880
2881
uint64_t roaring64_iterator_read(roaring64_iterator_t *it, uint64_t *buf,
2882
0
                                 uint64_t count) {
2883
0
    uint64_t consumed = 0;
2884
0
    while (it->has_value && consumed < count) {
2885
0
        uint32_t container_consumed;
2886
0
        leaf_t leaf = (leaf_t)*it->art_it.value;
2887
0
        uint16_t low16 = (uint16_t)it->value;
2888
0
        uint32_t container_count = UINT32_MAX;
2889
0
        if (count - consumed < (uint64_t)UINT32_MAX) {
2890
0
            container_count = count - consumed;
2891
0
        }
2892
0
        bool has_value = container_iterator_read_into_uint64(
2893
0
            get_container(it->r, leaf), get_typecode(leaf), &it->container_it,
2894
0
            it->high48, buf, container_count, &container_consumed, &low16);
2895
0
        consumed += container_consumed;
2896
0
        buf += container_consumed;
2897
0
        if (has_value) {
2898
0
            it->has_value = true;
2899
0
            it->value = it->high48 | low16;
2900
0
            assert(consumed == count);
2901
0
            return consumed;
2902
0
        }
2903
0
        it->has_value = art_iterator_next(&it->art_it);
2904
0
        if (it->has_value) {
2905
0
            roaring64_iterator_init_at_leaf_first(it);
2906
0
        } else {
2907
0
            it->saturated_forward = true;
2908
0
        }
2909
0
    }
2910
0
    return consumed;
2911
0
}
2912
2913
uint64_t roaring64_iterator_read_backward(roaring64_iterator_t *it,
2914
0
                                          uint64_t *buf, uint64_t count) {
2915
0
    uint64_t consumed = 0;
2916
0
    while (it->has_value && consumed < count) {
2917
0
        uint32_t container_consumed;
2918
0
        leaf_t leaf = *it->art_it.value;
2919
0
        uint16_t low16 = (uint16_t)it->value;
2920
0
        uint32_t container_count = UINT32_MAX;
2921
0
        if (count - consumed < (uint64_t)UINT32_MAX) {
2922
0
            container_count = count - consumed;
2923
0
        }
2924
0
        bool has_value = container_iterator_read_backward_into_uint64(
2925
0
            get_container(it->r, leaf), get_typecode(leaf), &it->container_it,
2926
0
            it->high48, buf, container_count, &container_consumed, &low16);
2927
0
        consumed += container_consumed;
2928
0
        buf += container_consumed;
2929
0
        if (has_value) {
2930
0
            it->has_value = true;
2931
0
            it->value = it->high48 | low16;
2932
0
            assert(consumed == count);
2933
0
            return consumed;
2934
0
        }
2935
0
        it->has_value = art_iterator_prev(&it->art_it);
2936
0
        if (it->has_value) {
2937
0
            roaring64_iterator_init_at_leaf_last(it);
2938
0
        } else {
2939
0
            it->saturated_forward = false;
2940
0
        }
2941
0
    }
2942
0
    return consumed;
2943
0
}
2944
2945
size_t roaring64_iterator_read_ranges(roaring64_iterator_t *it,
2946
                                      roaring64_range_closed_t *buf,
2947
0
                                      size_t count) {
2948
0
    size_t ret = 0;
2949
0
    while (it->has_value && ret < count) {
2950
0
        buf[ret].min = it->value;
2951
0
        for (;;) {
2952
0
            uint16_t low16 = (uint16_t)it->value;
2953
0
            leaf_t leaf = (leaf_t)*it->art_it.value;
2954
0
            bool container_has_more;
2955
0
            uint16_t run_end_low16 = container_iterator_find_run_end(
2956
0
                get_container(it->r, leaf), get_typecode(leaf),
2957
0
                &it->container_it, &low16, &container_has_more);
2958
0
            buf[ret].max = it->high48 | run_end_low16;
2959
2960
0
            if (container_has_more) {
2961
0
                it->value = it->high48 | low16;
2962
0
                break;
2963
0
            }
2964
            // Move to next leaf
2965
0
            it->has_value = art_iterator_next(&it->art_it);
2966
0
            if (it->has_value) {
2967
0
                roaring64_iterator_init_at_leaf_first(it);
2968
0
            } else {
2969
0
                it->saturated_forward = true;
2970
0
                break;
2971
0
            }
2972
            // Continue merging only if the run reached the container
2973
            // boundary and the next leaf starts exactly at max+1.
2974
0
            if (run_end_low16 != UINT16_MAX || it->value != buf[ret].max + 1) {
2975
0
                break;
2976
0
            }
2977
0
        }
2978
0
        ret++;
2979
0
    }
2980
0
    return ret;
2981
0
}
2982
2983
size_t roaring64_iterator_read_prev_ranges(roaring64_iterator_t *it,
2984
                                           roaring64_range_closed_t *buf,
2985
0
                                           size_t count) {
2986
0
    size_t ret = 0;
2987
0
    while (it->has_value && ret < count) {
2988
0
        buf[ret].max = it->value;
2989
0
        for (;;) {
2990
0
            uint16_t low16 = (uint16_t)it->value;
2991
0
            leaf_t leaf = (leaf_t)*it->art_it.value;
2992
0
            bool container_has_more;
2993
0
            uint16_t run_start_low16 = container_iterator_find_run_start(
2994
0
                get_container(it->r, leaf), get_typecode(leaf),
2995
0
                &it->container_it, &low16, &container_has_more);
2996
0
            buf[ret].min = it->high48 | run_start_low16;
2997
2998
0
            if (container_has_more) {
2999
0
                it->value = it->high48 | low16;
3000
0
                break;
3001
0
            }
3002
            // Move to previous leaf
3003
0
            it->has_value = art_iterator_prev(&it->art_it);
3004
0
            if (it->has_value) {
3005
0
                roaring64_iterator_init_at_leaf_last(it);
3006
0
            } else {
3007
0
                it->saturated_forward = false;
3008
0
                break;
3009
0
            }
3010
            // Continue merging only if the run reached the container
3011
            // boundary and the previous leaf ends exactly at min-1.
3012
0
            if (run_start_low16 != 0 || it->value != buf[ret].min - 1) {
3013
0
                break;
3014
0
            }
3015
0
        }
3016
0
        ret++;
3017
0
    }
3018
0
    return ret;
3019
0
}
3020
3021
#ifdef __cplusplus
3022
}  // extern "C"
3023
}  // namespace roaring
3024
}  // namespace api
3025
#endif