simple-bitset 0.1.5

Simple no-std compatible 64-bit and 128-bit bitsets for embedded applications
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
use core::fmt;
use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Index};
#[cfg(feature = "serde")]
use {
    sequential_storage::map::PostcardValue,
    serde::{Deserialize, Serialize},
};

/// A memory-efficient 64-bit set for embedded environments.
// Note that it data is a singlet: this makes comparison with `BitSet128` duplet clearer.
#[derive(Clone, Copy, Debug, Ord, PartialOrd, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BitSet64(u64);

impl BitSet64 {
    /// Create a new empty bitset.
    #[must_use]
    pub const fn new() -> Self {
        Self(0)
    }
}

#[cfg(feature = "serde")]
impl PostcardValue<'_> for BitSet64 {}

impl Default for BitSet64 {
    fn default() -> Self {
        Self::new()
    }
}

impl BitSet64 {
    /// Resets all bits to 0.
    #[inline]
    pub fn reset_all(&mut self) {
        self.0 = 0;
    }

    /// Resets the bit at `index` to 0. Does nothing if the index is out of bounds.
    #[inline]
    pub fn reset(&mut self, index: u8) {
        if index < 64 {
            self.0 &= !(1u64 << index);
        }
    }

    /// Sets all bits to 1.
    #[inline]
    pub fn set_all(&mut self) {
        self.0 = u64::MAX;
    }

    /// Sets the bit at `index` to 1. Does nothing if the index is out of bounds.
    #[inline]
    pub fn set(&mut self, index: u8) {
        if index < 64 {
            self.0 |= 1u64 << index;
        }
    }

    /// Flips the bit at `index`. Does nothing if the index is out of bounds.
    #[inline]
    pub fn flip(&mut self, index: u8) {
        if index < 64 {
            self.0 ^= 1u64 << index;
        }
    }

    /// Flips all bits in the bitset (0s become 1s, and 1s become 0s).
    #[inline]
    pub fn flip_all(&mut self) {
        self.0 = !self.0;
    }

    /// In-place Difference / Mask-Clear. Clears any bits that are set in `other`.
    /// This represents the mathematical operation: `self = self AND NOT other`.
    #[inline]
    pub fn and_not(&mut self, other: Self) {
        self.0 &= !other.0;
    }

    /// Tests if the bit at `index` is 1.
    /// Returns false if the bit is 0 or index is out of bounds.
    #[inline]
    #[must_use]
    pub fn test(&self, index: u8) -> bool {
        if index < 64 {
            (self.0 & (1u64 << index)) != 0
        } else {
            false
        }
    }

    /// Returns bits 0 to 31.
    #[allow(clippy::cast_possible_truncation)]
    #[inline]
    #[must_use]
    pub fn bits_0_31(&self) -> u32 {
        self.0 as u32
    }

    /// Returns bits 32 to 63.
    #[inline]
    #[must_use]
    pub fn bits_32_63(&self) -> u32 {
        (self.0 >> 32) as u32
    }

    /// Returns the number of set bits (population count).
    #[inline]
    #[must_use]
    pub const fn count_ones(&self) -> u32 {
        self.0.count_ones()
    }

    /// Returns the number of leading zeros in the bitset,
    /// counting from the most significant bit (index 63).
    #[inline]
    #[must_use]
    pub const fn leading_zeros(&self) -> u32 {
        self.0.leading_zeros()
    }

    /// Returns true if no bits are set.
    #[inline]
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.0 == 0
    }

    /// Returns the highest index set, or None if the bitset is empty.
    /// Useful for finding the "top" of a priority queue or resource map.
    #[inline]
    #[must_use]
    pub const fn last_set(&self) -> Option<u8> {
        if self.is_empty() {
            None
        } else {
            // Cast is safe as (63 - leading) is guaranteed to be between 0 and 63.
            #[allow(clippy::cast_possible_truncation)]
            Some(63 - self.0.leading_zeros() as u8)
        }
    }

    /// Returns true if this bitset contains all the bits set in `other`.
    #[inline]
    #[must_use]
    pub const fn is_superset(&self, other: BitSet64) -> bool {
        // A bitset is a superset if clearing any bits not present in self
        // results in exactly the other bitset configuration for both halves.
        (self.0 & other.0) == other.0
    }

    /// Returns true if this bitset is a subset of `other`.
    #[inline]
    #[must_use]
    pub const fn is_subset(&self, other: BitSet64) -> bool {
        other.is_superset(*self)
    }

    /// Returns true if this bitset shares at least one common set bit with `other`.
    /// Returns false if there is no overlap or if either bitset is empty.
    #[inline]
    #[must_use]
    pub const fn intersects(&self, other: Self) -> bool {
        // Run a bitwise AND between bitsets.
        // If the result is non-zero, an intersection exists.
        self.0 & other.0 != 0
    }

    /// Returns an iterator over the indices of the set bits.
    #[inline]
    #[must_use]
    pub fn iter(&self) -> BitSet64Iter {
        self.into_iter()
    }
}

// **** Bit operations ****

impl BitOr for BitSet64 {
    type Output = Self;
    fn bitor(self, other: Self) -> Self::Output {
        Self(self.0 | other.0)
    }
}

impl BitAnd for BitSet64 {
    type Output = Self;
    fn bitand(self, other: Self) -> Self::Output {
        Self(self.0 & other.0)
    }
}

impl BitXor for BitSet64 {
    type Output = Self;
    fn bitxor(self, other: Self) -> Self::Output {
        Self(self.0 ^ other.0)
    }
}

impl BitOrAssign for BitSet64 {
    fn bitor_assign(&mut self, other: Self) {
        self.0 |= other.0;
    }
}

impl BitAndAssign for BitSet64 {
    fn bitand_assign(&mut self, other: Self) {
        self.0 &= other.0;
    }
}

impl BitXorAssign for BitSet64 {
    fn bitxor_assign(&mut self, other: Self) {
        self.0 ^= other.0;
    }
}

impl Index<u8> for BitSet64 {
    type Output = bool;

    fn index(&self, index: u8) -> &Self::Output {
        // We use static booleans because we must return a reference
        if self.test(index) { &true } else { &false }
    }
}

impl Index<usize> for BitSet64 {
    type Output = bool;

    #[allow(clippy::cast_possible_truncation)]
    fn index(&self, index: usize) -> &Self::Output {
        // We use static booleans because we must return a reference
        if self.test(index as u8) { &true } else { &false }
    }
}

/// `BitSet64` from `u32`.
impl From<u32> for BitSet64 {
    #[inline]
    fn from(a: u32) -> Self {
        Self(u64::from(a))
    }
}

/// `BitSet64` from `(u32,u32)`.
impl From<(u32, u32)> for BitSet64 {
    #[inline]
    fn from((a, b): (u32, u32)) -> Self {
        Self(u64::from(a) << 32 | u64::from(b))
    }
}

/// `BitSet64` from `u64`.
impl From<u64> for BitSet64 {
    #[inline]
    fn from(a: u64) -> Self {
        Self(a)
    }
}

// **** Iter ****

/// Iterator for `BitSet64`.
#[derive(Debug, Default, Eq, PartialEq)]
pub struct BitSet64Iter(u64);

/// Consuming iterator.
impl Iterator for BitSet64Iter {
    type Item = u8;

    fn next(&mut self) -> Option<Self::Item> {
        if self.0 == 0 {
            None
        } else {
            // Find the index of the least significant bit set to 1
            #[allow(clippy::cast_possible_truncation)]
            let index = self.0.trailing_zeros() as u8;
            // Clear the least significant bit to prep for next iteration
            self.0 &= self.0 - 1;
            Some(index)
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        // We know exactly how many bits are left to yield at any moment!
        let len = self.0.count_ones() as usize;
        (len, Some(len))
    }
}

// Implementing ExactSizeIterator unlocks additional optimizations automatically
impl ExactSizeIterator for BitSet64Iter {}
impl core::iter::FusedIterator for BitSet64Iter {}

/// Non-consuming iterator for bitset reference.
impl IntoIterator for &BitSet64 {
    type Item = u8;
    type IntoIter = BitSet64Iter;

    fn into_iter(self) -> Self::IntoIter {
        // Since `BitSet64` is `Copy` and just a `(u64)`,
        // we just pass the underlying value to the iterator.
        BitSet64Iter(self.0)
    }
}

/// Non-consuming iterator for bitset.
impl IntoIterator for BitSet64 {
    type Item = u8;
    type IntoIter = BitSet64Iter;

    fn into_iter(self) -> Self::IntoIter {
        // Since `BitSet64` is `Copy` and just a `(u64)`,
        // we just pass the underlying value to the iterator.
        BitSet64Iter(self.0)
    }
}

/// From iterator for bitset.
impl FromIterator<u8> for BitSet64 {
    fn from_iter<I: IntoIterator<Item = u8>>(iter: I) -> Self {
        let mut bitset = Self::new();
        for index in iter {
            bitset.set(index);
        }
        bitset
    }
}

impl Extend<u8> for BitSet64 {
    fn extend<I: IntoIterator<Item = u8>>(&mut self, iter: I) {
        for index in iter {
            self.set(index);
        }
    }
}

// **** fmt ****

impl fmt::Binary for BitSet64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Handle the "0b" prefix if requested via {:#b}
        if f.alternate() {
            f.write_str("0b")?;
        }
        // Print from high bits to low bits (left-to-right)
        for i in (0..64).rev() {
            let val = (self.0 >> i) & 1;
            write!(f, "{val}")?;
        }

        Ok(())
    }
}

impl fmt::UpperHex for BitSet64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            f.write_str("0x")?;
        }
        write!(f, "{:016X}", self.0)
    }
}

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

    fn is_normal<T: Sized + Send + Sync + Unpin>() {}
    fn is_full<T: Sized + Send + Sync + Unpin + Copy + Clone + Default + PartialEq>() {}
    #[cfg(feature = "serde")]
    fn is_config<T: Serialize + for<'a> Deserialize<'a>>() {}

    #[test]
    fn normal_types() {
        is_full::<BitSet64>();
        #[cfg(feature = "serde")]
        is_config::<BitSet64>();
        is_normal::<BitSet64Iter>();
    }

    #[test]
    fn new() {
        let mut bits = BitSet64::new();
        bits.set(42);
        assert!(bits[42u8]);
        assert!(bits.test(42));
    }

    #[test]
    fn const_new() {
        const FLAGS: BitSet64 = BitSet64::new();
        const EMPTY_CHECK: bool = FLAGS.is_empty(); // Evaluated at compile time
        assert_eq!(0, FLAGS.0);
        #[allow(clippy::assertions_on_constants)]
        {
            assert!(EMPTY_CHECK);
        }
    }

    #[test]
    fn assign() {
        let mut bits = BitSet64::new();
        bits.set(42);
        assert!(bits[42u8]);
        assert!(bits.test(42));
        let mask = bits;
        assert!(mask.test(42));
    }

    #[test]
    fn from() {
        let _bits = BitSet64::from((0xab_u32, 0x12_u32));
    }

    #[test]
    fn flip_all() {
        let mut bitset = BitSet64::new();

        // Alternating pattern test
        bitset.set(0);
        bitset.set(32);

        bitset.flip_all();

        // Bit 0 and 64 should now be 0, others should be 1
        assert!(!bitset.test(0));
        assert!(!bitset.test(32));
        assert!(bitset.test(1));
        assert!(bitset.test(33));

        // Full cycle test (Empty -> Full -> Empty)
        let mut empty_set = BitSet64::new();
        empty_set.flip_all(); // Should become full

        let mut full_set = BitSet64::new();
        full_set.set_all();

        assert_eq!(empty_set, full_set);

        empty_set.flip_all(); // Should return to completely empty
        assert!(empty_set.is_empty());
    }

    #[test]
    fn leading_zeros() {
        let mut bitset = BitSet64::new();

        // Completely empty set should return 64 zeros
        assert_eq!(bitset.leading_zeros(), 64);

        // Setting the absolute most significant bit (index 63) leaves 0 leading zeros
        bitset.set(63);
        assert_eq!(bitset.leading_zeros(), 0);

        // Setting index 62 leaves exactly 1 leading zero
        bitset.reset_all();
        bitset.set(62);
        assert_eq!(bitset.leading_zeros(), 1);
    }

    #[test]
    fn last_set() {
        let mut bitset = BitSet64::new();

        // Empty set should return None
        assert_eq!(bitset.last_set(), None);

        // Single lowest bit set
        bitset.set(0);
        assert_eq!(bitset.last_set(), Some(0));

        // Multiple bits set, should return the highest one
        bitset.set(10);
        bitset.set(45);
        assert_eq!(bitset.last_set(), Some(45));

        // Boundary verification at the top of the lower u64
        bitset.reset_all();
        bitset.set(63);
        assert_eq!(bitset.last_set(), Some(63));
    }

    #[test]
    fn is_superset() {
        let mut set_a = BitSet64::new();
        let mut set_b = BitSet64::new();

        // An empty set is always a superset of another empty set
        assert!(set_a.is_superset(set_b));

        // Setup indices spanning across the 64-bit boundary
        set_a.set(10);
        set_a.set(60);

        set_b.set(10);

        // set_a has [10, 60], set_b has [10] -> Should be true
        assert!(set_a.is_superset(set_b));
        // set_b is missing 80 -> Should be false
        assert!(!set_b.is_superset(set_a));

        // Test exact match
        set_b.set(60);
        assert!(set_a.is_superset(set_b));

        // Test failure where lower matches but higher fails (Catches the original bug)
        let mut set_c = BitSet64::new();
        let mut set_d = BitSet64::new();
        set_c.set(15); // Higher element (.1) is 0

        set_d.set(15);
        set_d.set(55); // Higher element (.1) is non-zero

        // Lower halves match, but set_c is missing bit 95.
        // Your old function would mistakenly return true here.
        assert!(!set_c.is_superset(set_d));
    }

    #[test]
    fn intersects() {
        let mut set_a = BitSet64::new();
        let mut set_b = BitSet64::new();

        // Empty sets should never intersect
        assert!(!set_a.intersects(set_b));

        // Add an item to set_a only
        set_a.set(15);
        assert!(!set_a.intersects(set_b));

        // Match the item in set_b (Intersection in the lower u64 block)
        set_b.set(15);
        assert!(set_a.intersects(set_b));
        assert!(set_b.intersects(set_a));

        // Test disjoint sets across the 64-bit split boundary
        set_a.reset_all();
        set_b.reset_all();
        set_a.set(10);
        set_b.set(60);
        assert!(!set_a.intersects(set_b));

        // Test intersection purely inside the higher u64 block (index >= 64)
        set_a.set(60);
        assert!(set_a.intersects(set_b));
    }

    #[test]
    fn inplace_logical_ops() {
        let mut set_a = BitSet64::new();
        let mut set_b = BitSet64::new();

        // Setup overlapping patterns crossing 64-bit boundaries
        set_a.set(10);
        set_a.set(50);

        set_b.set(10);
        set_b.set(60);

        // Test BitAndAssign (&=)
        let mut result = set_a;
        result &= set_b;
        assert!(result.test(10));
        assert!(!result.test(50));
        assert!(!result.test(60));

        // Test BitOrAssign (|=)
        let mut result = set_a;
        result |= set_b;
        assert!(result.test(10));
        assert!(result.test(50));
        assert!(result.test(60));

        // Test BitXorAssign (^=)
        let mut result = set_a;
        result ^= set_b;
        assert!(!result.test(10)); // Both were 1, turns to 0
        assert!(result.test(50));
        assert!(result.test(60));

        // Test and_not
        let mut result = set_a;
        result.and_not(set_b);
        assert!(!result.test(10)); // Cleared by mask
        assert!(result.test(50)); // Preserved
        assert!(!result.test(60)); // Never present in set_a
    }

    #[test]
    fn exercise() {
        let mut system_flags = BitSet64::new();
        let error_mask = BitSet64::new(); // imagine this has error bits set

        // Combine with OR-assign
        system_flags |= error_mask;

        // Toggle bits with XOR-assign
        system_flags ^= error_mask;

        // Mask out bits with AND-assign
        system_flags &= BitSet64(0x0000_FFFF_FFFF_FFFF);

        let mut set_a = BitSet64::new();
        set_a.set(10);
        set_a.set(20);

        let mut set_b = BitSet64::new();
        set_b.set(20);
        set_b.set(30);

        // Intersection (AND): only bit 20 remains
        let common = set_a & set_b;
        assert!(!common.test(10));
        assert!(common.test(20));
        assert!(!common.test(30));

        // Union (OR): bits 10, 20, and 30 are set
        let all = set_a | set_b;
        assert!(all.test(10));
        assert!(all.test(20));
        assert!(all.test(30));

        // Difference (XOR): bits 10 and 30 are set (20 is cancelled out)
        let diff = set_a ^ set_b;
        assert!(diff.test(10));
        assert!(!diff.test(20));
        assert!(diff.test(30));
    }

    #[test]
    fn iterator_consuming() {
        let mut bits = BitSet64::new();
        bits.set(2);
        bits.set(10);

        let mut sum = 0;
        let mut count = 0;
        for bit in &bits {
            sum += bit;
            count += 1;
        }
        assert_eq!(2, count);
        assert_eq!(12, sum);
    }

    #[test]
    fn into_iter_consuming() {
        let mut bits = BitSet64::new();
        bits.set(0);
        bits.set(10);
        bits.set(63);

        // Consuming iterator
        let mut iter = bits.into_iter();

        assert_eq!(iter.next(), Some(0));
        assert_eq!(iter.next(), Some(10));
        assert_eq!(iter.next(), Some(63));
        assert_eq!(iter.next(), None);

        // bits is moved here and can no longer be used
    }

    #[test]
    fn non_consuming_iterator() {
        let bits = BitSet64(0b1101); // Bits 0, 2, and 3 are set

        let mut sum = 0;
        let mut count = 0;

        // Use reference to bits rather than bits.iter()
        for bit in &bits {
            sum += bit;
            count += 1;
        }
        assert_eq!(3, count);
        assert_eq!(5, sum);

        let mut sum = 0;
        let mut count = 0;
        // Using a reference in a loop
        for bit in &bits {
            sum += bit;
            count += 1;
        }
        assert_eq!(3, count);
        assert_eq!(5, sum);
    }

    #[test]
    fn non_consuming_iterator2() {
        let mut bits = BitSet64::new();
        bits.set(5);
        bits.set(12);

        // Test using the .iter() method
        let count = bits.iter().count();
        assert_eq!(count, 2);

        // Test using & reference in a for-loop
        let mut last_val = 0;
        for bit in &bits {
            last_val = bit;
        }
        assert_eq!(last_val, 12);

        // test original bits is still valid
        assert!(bits.test(5));
    }

    #[test]
    fn from_iterator() {
        let indices = [1, 3, 5];
        // collect() uses FromIterator
        let bits: BitSet64 = indices.iter().copied().collect();

        assert!(bits.test(1));
        assert!(bits.test(3));
        assert!(bits.test(5));
        assert!(!bits.test(2));
    }

    #[test]
    fn empty_and_full() {
        let empty = BitSet64::new();
        assert_eq!(empty.iter().count(), 0);

        let mut full = BitSet64::new();
        full.set_all();
        assert_eq!(full.iter().count(), 64);
    }
}