fastbit 0.11.1

A fast, efficient, and pure Rust bitset implementation for high-performance data indexing and analytics.
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
use std::{
    marker::PhantomData,
    ops::{BitAndAssign, BitOrAssign, BitXorAssign},
    ptr::NonNull,
};

use crate::{
    BitRead, Iter,
    traits::{BitWord, BitWrite},
    util::{
        bitset_all, bitset_any, bitset_clear, bitset_count_ones, bitset_fill, bitset_flip,
        bitset_reset, bitset_set, bitset_test, bitset_test_and_set,
    },
};

/// A read-only view into a bit set stored in memory.
///
/// `BitView` provides a safe interface for accessing bits in an existing memory region
/// without taking ownership of the underlying data. It's similar to a slice (`&[T]`) but
/// operates at the bit level rather than the element level.
///
/// The view is parameterized by:
/// - A lifetime `'a` that ties it to the lifetime of the referenced data
/// - A word type `T` that implements the `BitWord` trait, which defines the storage unit
///
/// # Safety
///
/// This type uses raw pointers internally and relies on the caller to ensure:
/// - The pointer is valid for the entire lifetime `'a`
/// - The pointer points to a properly aligned instance of `T`
/// - The memory region contains at least enough bits to cover the specified length
/// - The memory is not mutated through other references while this view exists
///
/// # Examples
///
/// ```
/// use fastbit::BitView;
/// use fastbit::BitRead;
///
/// // Create a bit pattern in a byte array
/// let data: [u8; 2] = [0b10101010, 0b01010101];
///
/// // Create a BitView over the data (unsafe because we're working with raw pointers)
/// let view = unsafe { BitView::from_raw_parts(data.as_ptr(), 16) };
///
/// // Now we can safely read bits
/// assert!(!view.test(0));
/// assert!(view.test(1));
/// assert_eq!(view.count_ones(), 8);
/// ```
pub struct BitView<'a, T: BitWord> {
    ptr: NonNull<T>,
    len: usize,
    _marker: PhantomData<&'a T>,
}

/// A mutable view into a bit set stored in memory.
///
/// `BitViewMut` provides a safe interface for accessing and modifying bits in an existing memory region
/// without taking ownership of the underlying data. It's similar to a mutable slice (`&mut [T]`) but
/// operates at the bit level rather than the element level.
///
/// The view is parameterized by:
/// - A lifetime `'a` that ties it to the lifetime of the referenced data
/// - A word type `T` that implements the `BitWord` trait, which defines the storage unit
///
/// # Safety
///
/// This type uses raw pointers internally and relies on the caller to ensure:
/// - The pointer is valid for the entire lifetime `'a`
/// - The pointer points to a properly aligned instance of `T`
/// - The memory region contains at least enough bits to cover the specified length
/// - The memory is not mutated through other references while this view exists
/// - The caller has exclusive access to the memory region for the duration of the view
///
/// # Examples
///
/// ```
/// use fastbit::{BitViewMut, BitRead, BitWrite};
///
/// // Create a mutable bit pattern in a byte array
/// let mut data: [u8; 2] = [0b10101010, 0b01010101];
///
/// // Create a BitViewMut over the data (unsafe because we're working with raw pointers)
/// let mut view = unsafe { BitViewMut::from_raw_parts(data.as_mut_ptr(), 16) };
///
/// // Now we can safely read and modify bits
/// assert!(!view.test(0));
/// view.set(0);
/// assert!(view.test(0));
/// view.clear();
/// assert_eq!(view.count_ones(), 0);
/// ```
pub struct BitViewMut<'a, T: BitWord> {
    ptr: NonNull<T>,
    len: usize,
    _marker: PhantomData<&'a mut T>,
}

impl<'a, T: BitWord> BitViewMut<'a, T> {
    /// Creates a new `BitViewMut` from a non-null pointer and length.
    ///
    /// This is a crate-internal constructor used by other data structures.
    ///
    /// # Arguments
    ///
    /// * `ptr` - A non-null pointer to the start of the bit storage
    /// * `len` - The number of bits in the view
    #[inline]
    pub(crate) fn new(ptr: NonNull<T>, len: usize) -> Self {
        Self {
            ptr,
            len,
            _marker: PhantomData,
        }
    }

    /// Creates a new `BitViewMut` from raw parts.
    ///
    /// # Arguments
    ///
    /// * `ptr` - A pointer to the start of the bit storage
    /// * `len` - The number of bits in the view
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    /// - The pointer is valid for reads and writes for the entire lifetime `'a`
    /// - The pointer points to a properly aligned instance of `T`
    /// - The memory region contains at least enough bits to cover the specified length
    /// - The caller has exclusive access to the memory region for the duration of the view
    #[inline]
    pub unsafe fn from_raw_parts(ptr: *const T, len: usize) -> Self {
        Self {
            ptr: NonNull::new(ptr as *mut T).unwrap(),
            len,
            _marker: PhantomData,
        }
    }
}

impl<'a, T: BitWord> BitView<'a, T> {
    /// Creates a new `BitView` from a non-null pointer and length.
    ///
    /// This is a crate-internal constructor used by other data structures.
    ///
    /// # Arguments
    ///
    /// * `ptr` - A non-null pointer to the start of the bit storage
    /// * `len` - The number of bits in the view
    #[inline]
    pub(crate) fn new(ptr: NonNull<T>, len: usize) -> Self {
        Self {
            ptr,
            len,
            _marker: PhantomData,
        }
    }

    /// Creates a new `BitView` from raw parts.
    ///
    /// # Arguments
    ///
    /// * `ptr` - A pointer to the start of the bit storage
    /// * `len` - The number of bits in the view
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    /// - The pointer is valid for reads for the entire lifetime `'a`
    /// - The pointer points to a properly aligned instance of `T`
    /// - The memory region contains at least enough bits to cover the specified length
    /// - The memory is not mutated through other references while this view exists
    #[inline]
    pub unsafe fn from_raw_parts(ptr: *const T, len: usize) -> Self {
        Self {
            ptr: NonNull::new(ptr as *mut T).unwrap(),
            len,
            _marker: PhantomData,
        }
    }
}

impl<'a, W: BitWord> BitRead for BitView<'a, W> {
    /// The iterator type returned by the `iter` method.
    ///
    /// This iterator yields the indices of all set bits (1s) in the bit view.
    type Iter<'b>
        = Iter<'b, W>
    where
        Self: 'b;

    /// Returns the number of bits in this bit view.
    #[inline]
    fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if this bit view contains no bits.
    #[inline]
    fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Tests if the bit at the specified index is set (1).
    ///
    /// # Arguments
    ///
    /// * `idx` - The index of the bit to test
    ///
    /// # Panics
    ///
    /// Panics if `idx` is out of bounds (>= `self.len()`).
    #[inline]
    fn test(&self, idx: usize) -> bool {
        unsafe { bitset_test(self.ptr, self.len, idx) }
    }

    /// Counts the number of set bits (1s) in this bit view.
    #[inline]
    fn count_ones(&self) -> usize {
        unsafe { bitset_count_ones(self.ptr, self.len) }
    }

    /// Returns `true` if all bits in this view are set (1).
    ///
    /// Returns `true` for empty bit views.
    #[inline]
    fn all(&self) -> bool {
        unsafe { bitset_all(self.ptr, self.len) }
    }

    /// Returns `true` if any bit in this view is set (1).
    ///
    /// Returns `false` for empty bit views.
    #[inline]
    fn any(&self) -> bool {
        unsafe { bitset_any(self.ptr, self.len) }
    }

    /// Returns an iterator over the indices of all set bits (1s) in this bit view.
    ///
    /// The iterator yields the indices in ascending order.
    #[inline]
    fn iter(&self) -> Self::Iter<'_> {
        Iter::from_raw_parts(self.ptr.as_ptr(), self.len)
    }
}

impl<'a, T: BitWord> BitRead for BitViewMut<'a, T> {
    /// The iterator type returned by the `iter` method.
    ///
    /// This iterator yields the indices of all set bits (1s) in the bit view.
    type Iter<'b>
        = Iter<'b, T>
    where
        Self: 'b;

    /// Returns the number of bits in this bit view.
    #[inline]
    fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if this bit view contains no bits.
    #[inline]
    fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Tests if the bit at the specified index is set (1).
    ///
    /// # Arguments
    ///
    /// * `idx` - The index of the bit to test
    ///
    /// # Panics
    ///
    /// Panics if `idx` is out of bounds (>= `self.len()`).
    #[inline]
    fn test(&self, idx: usize) -> bool {
        unsafe { bitset_test(self.ptr, self.len, idx) }
    }

    /// Counts the number of set bits (1s) in this bit view.
    #[inline]
    fn count_ones(&self) -> usize {
        unsafe { bitset_count_ones(self.ptr, self.len) }
    }

    /// Returns `true` if all bits in this view are set (1).
    ///
    /// Returns `true` for empty bit views.
    #[inline]
    fn all(&self) -> bool {
        unsafe { bitset_all(self.ptr, self.len) }
    }

    /// Returns `true` if any bit in this view is set (1).
    ///
    /// Returns `false` for empty bit views.
    #[inline]
    fn any(&self) -> bool {
        unsafe { bitset_any(self.ptr, self.len) }
    }

    /// Returns an iterator over the indices of all set bits (1s) in this bit view.
    ///
    /// The iterator yields the indices in ascending order.
    #[inline]
    fn iter(&self) -> Self::Iter<'_> {
        Iter::from_raw_parts(self.ptr.as_ptr(), self.len)
    }
}

impl<'a, T: BitWord> BitWrite for BitViewMut<'a, T> {
    /// Sets the bit at the specified index to 1.
    ///
    /// # Arguments
    ///
    /// * `idx` - The index of the bit to set
    ///
    /// # Panics
    ///
    /// Panics if `idx` is out of bounds (>= `self.len()`).
    #[inline]
    fn set(&mut self, idx: usize) {
        unsafe { bitset_set(self.ptr, self.len, idx) };
    }

    /// Sets the bit at the specified index to 0.
    ///
    /// # Arguments
    ///
    /// * `idx` - The index of the bit to reset
    ///
    /// # Panics
    ///
    /// Panics if `idx` is out of bounds (>= `self.len()`).
    #[inline]
    fn reset(&mut self, idx: usize) {
        unsafe { bitset_reset(self.ptr, self.len, idx) };
    }

    /// Flips the bit at the specified index (0 becomes 1, 1 becomes 0).
    ///
    /// # Arguments
    ///
    /// * `idx` - The index of the bit to flip
    ///
    /// # Panics
    ///
    /// Panics if `idx` is out of bounds (>= `self.len()`).
    #[inline]
    fn flip(&mut self, idx: usize) {
        unsafe { bitset_flip(self.ptr, self.len, idx) };
    }

    /// Tests the bit at the specified index and then sets it to 1.
    ///
    /// # Arguments
    ///
    /// * `idx` - The index of the bit to test and set
    ///
    /// # Returns
    ///
    /// The previous value of the bit (true if it was 1, false if it was 0).
    ///
    /// # Panics
    ///
    /// Panics if `idx` is out of bounds (>= `self.len()`).
    #[inline]
    fn test_and_set(&mut self, idx: usize) -> bool {
        unsafe { bitset_test_and_set(self.ptr, self.len, idx) }
    }

    /// Sets all bits in this view to 1.
    #[inline]
    fn fill(&mut self) {
        unsafe { bitset_fill(self.ptr, self.len) };
    }

    /// Sets all bits in this view to 0.
    #[inline]
    fn clear(&mut self) {
        unsafe { bitset_clear(self.ptr, self.len) };
    }
}

impl<'a, 'b, T: BitWord> BitAndAssign<&'b BitView<'b, T>> for BitViewMut<'a, T> {
    fn bitand_assign(&mut self, rhs: &'b BitView<'b, T>) {
        for index in self.iter().collect::<Vec<_>>() {
            if !rhs.test(index) {
                self.reset(index);
            }
        }
    }
}

impl<'a, 'b, T: BitWord> BitOrAssign<&'b BitView<'b, T>> for BitViewMut<'a, T> {
    fn bitor_assign(&mut self, rhs: &'b BitView<'b, T>) {
        for index in rhs.iter() {
            self.set(index);
        }
    }
}

impl<'a, 'b, T: BitWord> BitXorAssign<&'b BitView<'b, T>> for BitViewMut<'a, T> {
    fn bitxor_assign(&mut self, rhs: &'b BitView<'b, T>) {
        for index in self.iter().collect::<Vec<_>>() {
            if rhs.test(index) {
                self.reset(index);
            }
        }
        for index in rhs.iter() {
            if self.test(index) {
                self.reset(index);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Tests basic functionality of BitView including bit testing, counting ones,
    /// and checking all/any/is_empty methods.
    #[test]
    fn test_bitview_basic() {
        let data: [u8; 2] = [0b10101010, 0b01010101];
        let bv = unsafe { BitView::from_raw_parts(data.as_ptr(), 16) };
        // Test individual bits
        assert_eq!(bv.test(0), false);
        assert_eq!(bv.test(1), true);
        assert_eq!(bv.test(2), false);
        assert_eq!(bv.test(3), true);
        assert_eq!(bv.test(8), true);
        assert_eq!(bv.test(9), false);
        // Test count_ones
        assert_eq!(bv.count_ones(), 8);
        // Test all/any/is_empty
        assert!(!bv.all());
        assert!(bv.any());
        assert!(!bv.is_empty());
    }

    /// Tests that an empty BitView (with length 0) behaves correctly:
    /// - len() returns 0
    /// - is_empty() returns true
    /// - any() returns false
    /// - all() returns true (vacuously true for empty sets)
    /// - count_ones() returns 0
    #[test]
    fn test_bitview_empty() {
        let data: [u8; 1] = [0];
        let bv = BitView {
            ptr: NonNull::new(data.as_ptr() as *const u8 as *mut u8).unwrap(),
            len: 0,
            _marker: PhantomData,
        };
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());
        assert!(!bv.any());
        assert!(bv.all());
        assert_eq!(bv.count_ones(), 0);
    }

    /// Tests a BitView where all bits are set to 1:
    /// - all() returns true
    /// - any() returns true
    /// - count_ones() returns the total number of bits
    #[test]
    fn test_bitview_all_ones() {
        let data: [u8; 2] = [0xFF, 0xFF];
        let bv = BitView {
            ptr: NonNull::new(data.as_ptr() as *const u8 as *mut u8).unwrap(),
            len: 16,
            _marker: PhantomData,
        };
        assert!(bv.all());
        assert!(bv.any());
        assert_eq!(bv.count_ones(), 16);
    }

    /// Tests a BitView with a partial last word (not using all bits in the last storage unit).
    /// Ensures that operations correctly handle the bit length rather than the underlying storage size.
    #[test]
    fn test_bitview_partial_last_word() {
        let data: [u8; 2] = [0xFF, 0x0F]; // 0x0F = 00001111
        let bv = BitView {
            ptr: NonNull::new(data.as_ptr() as *const u8 as *mut u8).unwrap(),
            len: 12, // Only 12 bits used
            _marker: PhantomData,
        };
        assert!(bv.all());
        assert!(bv.any());
        assert_eq!(bv.count_ones(), 12);
    }

    /// Tests that the iterator correctly yields the indices of set bits in ascending order.
    #[test]
    fn test_bitview_iter() {
        let data: [u8; 1] = [0b10110010];
        let bv = BitView {
            ptr: NonNull::new(data.as_ptr() as *const u8 as *mut u8).unwrap(),
            len: 8,
            _marker: PhantomData,
        };
        let bits: Vec<_> = bv.iter().collect();
        assert_eq!(bits, vec![1, 4, 5, 7]);
    }

    /// Tests a BitView with only a single bit set, verifying:
    /// - count_ones() returns 1
    /// - test() returns true only for the set bit
    /// - test() returns false for all other bits
    #[test]
    fn test_bitview_single_bit() {
        let data: [u8; 1] = [0b00000010];
        let bv = unsafe { BitView::from_raw_parts(data.as_ptr(), 8) };
        assert_eq!(bv.count_ones(), 1);
        assert!(bv.test(1));
        for i in 0..8 {
            if i != 1 {
                assert!(!bv.test(i));
            }
        }
    }

    /// Tests a BitView with zero length (different from empty, which has storage but no bits).
    /// Verifies the same properties as test_bitview_empty.
    #[test]
    fn test_bitview_zero_bits() {
        let data: [u8; 1] = [0];
        let bv = unsafe { BitView::from_raw_parts(data.as_ptr(), 0) };
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());
        assert!(!bv.any());
        assert!(bv.all());
        assert_eq!(bv.count_ones(), 0);
    }

    /// Tests that the iterator for an empty BitView yields no elements.
    #[test]
    fn test_bitview_iter_empty() {
        let data: [u8; 1] = [0];
        let bv = unsafe { BitView::from_raw_parts(data.as_ptr(), 0) };
        let bits: Vec<_> = bv.iter().collect();
        assert!(bits.is_empty());
    }

    /// Tests that the iterator correctly handles a BitView with a partial last word,
    /// yielding only the indices of set bits within the specified length.
    #[test]
    fn test_bitview_iter_partial_word() {
        let data: [u8; 2] = [0b11110000, 0b00001111];
        let bv = unsafe { BitView::from_raw_parts(data.as_ptr(), 12) };
        let bits: Vec<_> = bv.iter().collect();
        assert_eq!(bits, vec![4, 5, 6, 7, 8, 9, 10, 11]);
    }

    /// Tests the mutable operations of BitViewMut:
    /// - set() correctly sets bits
    /// - clear() resets all bits to 0
    #[test]
    fn test_bitview_mut() {
        let mut v = [123, 0, 1, usize::MAX];
        let len = v.len() * usize::BITS as usize - 3;
        let mut r = unsafe { BitViewMut::from_raw_parts(v.as_mut_ptr(), len) };
        r.set(0);
        r.set(1);
        r.set(7);
        assert_eq!(v, [251, 0, 1, usize::MAX]);
        r.clear();
        assert_eq!(v, [0, 0, 0, 0]);
    }
}