eta-algorithms 1.20.0

Low overhead data structures focused on performance
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use std::alloc::Layout;
use std::ptr;

use crate::data_structs::bitmap::consts::{BIT_END_OFFSET, BIT_MASK, DIV_SHIFT};
use crate::data_structs::bitmap::handle::Handle;

pub mod atomic_bitmap;
pub mod handle;

#[cfg(target_pointer_width = "64")]
pub(crate) mod consts {
    pub(crate) const DIV_SHIFT: usize = 6; // Divide by 64 => 2^6
    pub(crate) const BIT_END_OFFSET: usize = 63;
    pub(crate) const BIT_MASK: usize = 0xFFFFFFFFFFFFFFFF;
}

#[cfg(target_pointer_width = "32")]
pub(self) mod consts {
    pub(crate) const DIV_SHIFT: usize = 5;
    pub(crate) const BIT_END_OFFSET: usize = 31;
    pub(crate) const BIT_MASK: usize = 0xFFFFFFFF;
}

#[cfg(target_pointer_width = "16")]
pub(self) mod consts {
    pub(crate) const DIV_SHIFT: usize = 4;
    pub(crate) const BIT_END_OFFSET: usize = 15;
    pub(crate) const BIT_MASK: usize = 0xFFFF;
}

pub struct Bitmap {
    data: *mut usize,
    bit_capacity: usize,
    capacity: usize,
    layout: Layout,
}

impl Bitmap {
    pub fn new(bit_count: usize) -> Self {
        let size = (bit_count >> DIV_SHIFT) + 1;
        let layout = Layout::array::<usize>(size).expect("Failed to create layout");
        let data = unsafe { std::alloc::alloc(layout) as *mut usize };
        unsafe { ptr::write_bytes(data, 0, size) };
        Bitmap {
            data,
            capacity: size,
            bit_capacity: bit_count,
            layout,
        }
    }

    #[inline(always)]
    pub fn count_zeros(&self, lower_bound: usize, upper_bound: usize) -> usize {
        if upper_bound == 0 {
            panic!("Upper bound cannot be zero");
        }

        if lower_bound > upper_bound {
            panic!("Lower bound cannot be greater than upper bound");
        }

        if lower_bound >= self.bit_capacity {
            panic!("Bit index out of bounds");
        }
        if upper_bound > self.bit_capacity {
            panic!("Upper bound out of bounds");
        }

        if lower_bound == upper_bound {
            return 0;
        }

        unsafe { self.count_zeros_unchecked(lower_bound, upper_bound - 1) }
    }
    #[inline(always)]
    pub fn count_ones(&self, lower_bound: usize, upper_bound: usize) -> usize {
        if upper_bound == 0 {
            panic!("Upper bound cannot be zero");
        }

        if lower_bound > upper_bound {
            panic!("Lower bound cannot be greater than upper bound");
        }

        if lower_bound >= self.bit_capacity {
            panic!("Bit index out of bounds");
        }

        if upper_bound > self.bit_capacity {
            panic!("Upper bound out of bounds");
        }

        if lower_bound == upper_bound {
            return 0;
        }

        unsafe { self.count_ones_unchecked(lower_bound, upper_bound - 1) }
    }

    pub unsafe fn count_zeros_unchecked(&self, lower_bound: usize, upper_bound: usize) -> usize {
        let lower_offset = lower_bound >> DIV_SHIFT;
        let lower_bit_offset = lower_bound & BIT_END_OFFSET;
        let upper_offset = upper_bound >> DIV_SHIFT;
        let upper_bit_offset = upper_bound & BIT_END_OFFSET;
        let mut data_ptr = self.data.add(lower_offset);
        let mut data = if lower_offset != upper_offset {
            *data_ptr | ((1 << lower_bit_offset) - 1)
        } else {
            (*data_ptr | ((1 << lower_bit_offset) - 1)) | !(((1 << upper_bit_offset) - 1) | (1 << upper_bit_offset))
            // + 1 because inclusive and we need to do upper and lower bound masking
        };
        let mut counter = data.count_zeros() as usize;
        let end = self.data.add(upper_offset);
        loop {
            data_ptr = data_ptr.add(1);
            data = *data_ptr;
            if data_ptr >= end {
                break;
            }
            counter += data.count_zeros() as usize;
        }
        // The remainder
        if upper_offset != lower_offset {
            let data_end_ptr = data_ptr;
            // The other OR is there to add 1 because upper_bound is inclusive
            let data_end = *data_end_ptr | !(((1 << upper_bit_offset) - 1) | (1 << upper_bit_offset)); // + 1 because inclusive
            counter += data_end.count_zeros() as usize;
        }

        counter
    }

    pub unsafe fn count_ones_unchecked(&self, lower_bound: usize, upper_bound: usize) -> usize {
        let lower_offset = lower_bound >> DIV_SHIFT;
        let lower_bit_offset = lower_bound & BIT_END_OFFSET;
        let upper_offset = upper_bound >> DIV_SHIFT;
        let upper_bit_offset = upper_bound & BIT_END_OFFSET;
        let mut data_ptr = self.data.add(lower_offset);
        let mut data = if lower_offset != upper_offset {
            *data_ptr & (!((1 << lower_bit_offset) - 1))
        } else {
            (*data_ptr & (!((1 << lower_bit_offset) - 1))) & (((1 << upper_bit_offset) - 1) | (1 << upper_bit_offset))
            // + 1 because inclusive and we need to do upper and lower bound masking
        };
        let mut counter = data.count_ones() as usize;
        let end = self.data.add(upper_offset);
        loop {
            data_ptr = data_ptr.add(1);
            data = *data_ptr;
            if data_ptr >= end {
                break;
            }
            counter += data.count_ones() as usize;
        }
        // The remainder
        if upper_offset != lower_offset {
            let data_end_ptr = data_ptr;
            // The other OR is there to add 1 because upper_bound is inclusive
            let data_end = *data_end_ptr & (((1 << upper_bit_offset) - 1) | (1 << upper_bit_offset));
            counter += data_end.count_ones() as usize;
        }
        counter
    }
    #[inline(always)]
    pub fn first_one_bounds(&self, lower_bound: usize, upper_bound: usize) -> Option<usize> {
        if upper_bound == 0 {
            panic!("Upper bound cannot be zero");
        }

        if lower_bound > upper_bound {
            panic!("Lower bound cannot be greater than upper bound");
        }

        if lower_bound >= self.bit_capacity {
            panic!("Bit index out of bounds");
        }
        if upper_bound > self.bit_capacity {
            panic!("Upper bound out of bounds");
        }
        let index = unsafe { self.first_one_unchecked(lower_bound) };
        if index >= upper_bound {
            None
        } else {
            Some(index)
        }
    }
    #[inline(always)]
    pub fn first_zero_bounds(&self, lower_bound: usize, upper_bound: usize) -> Option<usize> {
        if upper_bound == 0 {
            panic!("Upper bound cannot be zero");
        }

        if lower_bound > upper_bound {
            panic!("Lower bound cannot be greater than upper bound");
        }

        if lower_bound >= self.bit_capacity {
            panic!("Bit index out of bounds");
        }
        if upper_bound > self.bit_capacity {
            panic!("Upper bound out of bounds");
        }
        let index = unsafe { self.first_zero_unchecked(lower_bound) };
        if index >= upper_bound {
            None
        } else {
            Some(index)
        }
    }
    #[inline(always)]
    pub fn first_zero(&self, bit_index: usize) -> Option<usize> {
        if bit_index >= self.bit_capacity {
            panic!("Bit index out of bounds");
        }

        let index = unsafe { self.first_zero_unchecked(bit_index) };
        if index >= self.bit_capacity {
            None
        } else {
            Some(index)
        }
    }
    #[inline(always)]
    pub fn first_one(&self, bit_index: usize) -> Option<usize> {
        if bit_index >= self.bit_capacity {
            panic!("Bit index out of bounds");
        }

        let index = unsafe { self.first_one_unchecked(bit_index) };
        if index >= self.bit_capacity {
            None
        } else {
            Some(index)
        }
    }
    /// Returns higher > bit_capacity in case of not found
    pub unsafe fn first_zero_unchecked(&self, bit_index: usize) -> usize {
        let offset = bit_index >> DIV_SHIFT;
        let bit_offset = bit_index & BIT_END_OFFSET;

        //We scan the last chunk with trailing, if it fails it shall return the max
        let last_chunk = self.data.add(self.capacity - 1);
        let mut data_ptr = self.data.add(offset);
        let mut counter = offset * (BIT_END_OFFSET + 1);
        let mut data = *data_ptr | ((1 << bit_offset) - 1);

        while data & BIT_MASK == BIT_MASK {
            if data_ptr != last_chunk {
                data_ptr = data_ptr.add(1);
                data = *data_ptr;
                counter += BIT_END_OFFSET + 1;
                continue;
            }
            break;
        }
        counter += data.trailing_ones() as usize;
        counter
    }

    /// Returns higher > bit_capacity in case of not found
    pub unsafe fn first_one_unchecked(&self, bit_index: usize) -> usize {
        let offset = bit_index >> DIV_SHIFT;
        let bit_offset = bit_index & BIT_END_OFFSET;

        //We scan the last chunk with trailing, if it fails it shall return the max
        let last_chunk = self.data.add(self.capacity - 1);
        let mut data_ptr = self.data.add(offset);
        let mut counter = offset * (BIT_END_OFFSET + 1);
        let mut data = *data_ptr & !((1 << bit_offset) - 1);

        while !data & BIT_MASK == BIT_MASK {
            if data_ptr != last_chunk {
                data_ptr = data_ptr.add(1);
                data = *data_ptr;
                counter += BIT_END_OFFSET + 1;
                continue;
            }
            break;
        }
        counter += data.trailing_zeros() as usize;
        counter
    }
    pub fn check_batch(&self, handles: &[Handle]) -> bool {
        for handle in handles {
            let val = unsafe { *self.data.add(handle.chunk as usize) };
            if (val & handle.bit_mask) != handle.bit_mask {
                return false;
            }
        }
        true
    }

    pub fn to_indices_true(&self) -> Vec<usize> {
        let mut indices = Vec::new();
        for i in 0..self.bit_capacity {
            if unsafe { self.get_unchecked(i) } {
                indices.push(i);
            }
        }
        indices
    }

    pub fn to_indices_true_bounded(&self, start: usize, end: usize) -> Vec<usize> {
        if start >= end {
            panic!("Start must be less than end");
        }
        if end > self.bit_capacity {
            panic!("End must be less than or equal to bit capacity");
        }

        let mut indices = Vec::new();
        for i in start..end {
            if unsafe { self.get_unchecked(i) } {
                indices.push(i);
            }
        }
        indices
    }

    pub fn to_indices_false(&self) -> Vec<usize> {
        let mut indices = Vec::new();
        for i in 0..self.bit_capacity {
            if unsafe { self.get_unchecked(i) == false } {
                indices.push(i);
            }
        }
        indices
    }

    pub fn to_indices_false_bounded(&self, start: usize, end: usize) -> Vec<usize> {
        if start >= end {
            panic!("Start must be less than end");
        }
        if end > self.bit_capacity {
            panic!("End must be less than or equal to bit capacity");
        }

        let mut indices = Vec::new();
        for i in start..end {
            if unsafe { self.get_unchecked(i) == false } {
                indices.push(i);
            }
        }
        indices
    }

    #[inline(always)]
    pub fn bit_capacity(&self) -> usize {
        self.bit_capacity
    }
    #[inline(always)]
    pub fn capacity(&self) -> usize {
        self.capacity
    }
    #[inline(always)]
    pub fn set(&mut self, bit_index: usize, value: bool) {
        if bit_index >= self.bit_capacity {
            panic!("Bit index out of bounds");
        }

        let offset = bit_index >> DIV_SHIFT;
        let bit_offset = bit_index & BIT_END_OFFSET;
        unsafe {
            let ptr = self.data.add(offset);
            *ptr = (*ptr & !(1 << bit_offset)) | ((value as usize) << bit_offset);
        }
    }
    #[inline(always)]
    pub fn get(&self, bit_index: usize) -> Option<bool> {
        if bit_index >= self.bit_capacity {
            return None;
        }

        let offset = bit_index >> DIV_SHIFT;
        let bit_offset = bit_index & (BIT_END_OFFSET);
        unsafe {
            let ptr = self.data.add(offset);
            Some((*ptr & (1 << bit_offset)) != 0)
        }
    }
    #[inline(always)]
    pub unsafe fn set_unchecked(&mut self, bit_index: usize, value: bool) {
        let offset = bit_index >> DIV_SHIFT;
        let bit_offset = bit_index & (BIT_END_OFFSET);
        unsafe {
            let ptr = self.data.add(offset);
            *ptr = (*ptr & !(1 << bit_offset)) | ((value as usize) << bit_offset);
        }
    }
    #[inline(always)]
    pub unsafe fn get_unchecked(&self, bit_index: usize) -> bool {
        let offset = bit_index >> DIV_SHIFT;
        let bit_offset = bit_index & (BIT_END_OFFSET);
        unsafe {
            let ptr = self.data.add(offset);
            (*ptr & (1 << bit_offset)) != 0
        }
    }
}

impl Drop for Bitmap {
    fn drop(&mut self) {
        unsafe {
            std::alloc::dealloc(self.data as *mut u8, self.layout);
        }
    }
}