Skip to main content

simple_bitset/
bitset64.rs

1use core::fmt;
2use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Index};
3#[cfg(feature = "serde")]
4use {
5    sequential_storage::map::PostcardValue,
6    serde::{Deserialize, Serialize},
7};
8
9/// A memory-efficient 64-bit set for embedded environments.
10// Note that it data is a singlet: this makes comparison with `BitSet128` duplet clearer.
11#[derive(Clone, Copy, Debug, Ord, PartialOrd, Eq, PartialEq)]
12#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
13pub struct BitSet64(u64);
14
15impl BitSet64 {
16    /// Create a new empty bitset.
17    #[must_use]
18    pub const fn new() -> Self {
19        Self(0)
20    }
21}
22
23#[cfg(feature = "serde")]
24impl PostcardValue<'_> for BitSet64 {}
25
26impl Default for BitSet64 {
27    fn default() -> Self {
28        Self::new()
29    }
30}
31
32impl BitSet64 {
33    /// Resets all bits to 0.
34    #[inline]
35    pub fn reset_all(&mut self) {
36        self.0 = 0;
37    }
38
39    /// Resets the bit at `index` to 0. Does nothing if the index is out of bounds.
40    #[inline]
41    pub fn reset(&mut self, index: u8) {
42        if index < 64 {
43            self.0 &= !(1u64 << index);
44        }
45    }
46
47    /// Sets all bits to 1.
48    #[inline]
49    pub fn set_all(&mut self) {
50        self.0 = u64::MAX;
51    }
52
53    /// Sets the bit at `index` to 1. Does nothing if the index is out of bounds.
54    #[inline]
55    pub fn set(&mut self, index: u8) {
56        if index < 64 {
57            self.0 |= 1u64 << index;
58        }
59    }
60
61    /// Flips the bit at `index`. Does nothing if the index is out of bounds.
62    #[inline]
63    pub fn flip(&mut self, index: u8) {
64        if index < 64 {
65            self.0 ^= 1u64 << index;
66        }
67    }
68
69    /// Flips all bits in the bitset (0s become 1s, and 1s become 0s).
70    #[inline]
71    pub fn flip_all(&mut self) {
72        self.0 = !self.0;
73    }
74
75    /// In-place Difference / Mask-Clear. Clears any bits that are set in `other`.
76    /// This represents the mathematical operation: `self = self AND NOT other`.
77    #[inline]
78    pub fn and_not(&mut self, other: Self) {
79        self.0 &= !other.0;
80    }
81
82    /// Tests if the bit at `index` is 1.
83    /// Returns false if the bit is 0 or index is out of bounds.
84    #[inline]
85    #[must_use]
86    pub fn test(&self, index: u8) -> bool {
87        if index < 64 {
88            (self.0 & (1u64 << index)) != 0
89        } else {
90            false
91        }
92    }
93
94    /// Returns the number of set bits (population count).
95    #[inline]
96    #[must_use]
97    pub const fn count_ones(&self) -> u32 {
98        self.0.count_ones()
99    }
100
101    /// Returns the number of leading zeros in the bitset,
102    /// counting from the most significant bit (index 63).
103    #[inline]
104    #[must_use]
105    pub const fn leading_zeros(&self) -> u32 {
106        self.0.leading_zeros()
107    }
108
109    /// Returns true if no bits are set.
110    #[inline]
111    #[must_use]
112    pub const fn is_empty(&self) -> bool {
113        self.0 == 0
114    }
115
116    /// Returns the highest index set, or None if the bitset is empty.
117    /// Useful for finding the "top" of a priority queue or resource map.
118    #[inline]
119    #[must_use]
120    pub const fn last_set(&self) -> Option<u8> {
121        if self.is_empty() {
122            None
123        } else {
124            // Cast is safe as (63 - leading) is guaranteed to be between 0 and 63.
125            #[allow(clippy::cast_possible_truncation)]
126            Some(63 - self.0.leading_zeros() as u8)
127        }
128    }
129
130    /// Returns true if this bitset contains all the bits set in `other`.
131    #[inline]
132    #[must_use]
133    pub const fn is_superset(&self, other: &BitSet64) -> bool {
134        // A bitset is a superset if clearing any bits not present in self
135        // results in exactly the other bitset configuration for both halves.
136        (self.0 & other.0) == other.0
137    }
138
139    /// Returns true if this bitset is a subset of `other`.
140    #[inline]
141    #[must_use]
142    pub const fn is_subset(&self, other: &BitSet64) -> bool {
143        other.is_superset(self)
144    }
145
146    /// Returns true if this bitset shares at least one common set bit with `other`.
147    /// Returns false if there is no overlap or if either bitset is empty.
148    #[inline]
149    #[must_use]
150    pub const fn intersects(&self, other: &Self) -> bool {
151        // Run a bitwise AND between bitsets.
152        // If the result is non-zero, an intersection exists.
153        self.0 & other.0 != 0
154    }
155
156    /// Returns an iterator over the indices of the set bits.
157    #[inline]
158    #[must_use]
159    pub fn iter(&self) -> BitSet64Iter {
160        self.into_iter()
161    }
162}
163
164// **** Bit operations ****
165
166impl BitOr for BitSet64 {
167    type Output = Self;
168    fn bitor(self, rhs: Self) -> Self::Output {
169        Self(self.0 | rhs.0)
170    }
171}
172
173impl BitAnd for BitSet64 {
174    type Output = Self;
175    fn bitand(self, rhs: Self) -> Self::Output {
176        Self(self.0 & rhs.0)
177    }
178}
179
180impl BitXor for BitSet64 {
181    type Output = Self;
182    fn bitxor(self, rhs: Self) -> Self::Output {
183        Self(self.0 ^ rhs.0)
184    }
185}
186
187impl BitOrAssign for BitSet64 {
188    fn bitor_assign(&mut self, rhs: Self) {
189        self.0 |= rhs.0;
190    }
191}
192
193impl BitAndAssign for BitSet64 {
194    fn bitand_assign(&mut self, rhs: Self) {
195        self.0 &= rhs.0;
196    }
197}
198
199impl BitXorAssign for BitSet64 {
200    fn bitxor_assign(&mut self, rhs: Self) {
201        self.0 ^= rhs.0;
202    }
203}
204
205impl Index<u8> for BitSet64 {
206    type Output = bool;
207
208    fn index(&self, index: u8) -> &Self::Output {
209        // We use static booleans because we must return a reference
210        if self.test(index) { &true } else { &false }
211    }
212}
213
214impl Index<usize> for BitSet64 {
215    type Output = bool;
216
217    #[allow(clippy::cast_possible_truncation)]
218    fn index(&self, index: usize) -> &Self::Output {
219        // We use static booleans because we must return a reference
220        if self.test(index as u8) { &true } else { &false }
221    }
222}
223
224/// `BitSet64` from `u32`.
225impl From<u32> for BitSet64 {
226    #[inline]
227    fn from(a: u32) -> Self {
228        Self(u64::from(a))
229    }
230}
231
232/// `BitSet64` from `(u32,u32)`.
233impl From<(u32, u32)> for BitSet64 {
234    #[inline]
235    fn from((a, b): (u32, u32)) -> Self {
236        Self(u64::from(a) << 32 | u64::from(b))
237    }
238}
239
240// **** Iter ****
241
242/// Iterator for `BitSet64`.
243#[derive(Debug, Default, Eq, PartialEq)]
244pub struct BitSet64Iter(u64);
245
246/// Consuming iterator.
247impl Iterator for BitSet64Iter {
248    type Item = u8;
249
250    fn next(&mut self) -> Option<Self::Item> {
251        if self.0 == 0 {
252            None
253        } else {
254            // Find the index of the least significant bit set to 1
255            #[allow(clippy::cast_possible_truncation)]
256            let index = self.0.trailing_zeros() as u8;
257            // Clear the least significant bit to prep for next iteration
258            self.0 &= self.0 - 1;
259            Some(index)
260        }
261    }
262
263    #[inline]
264    fn size_hint(&self) -> (usize, Option<usize>) {
265        // We know exactly how many bits are left to yield at any moment!
266        let len = self.0.count_ones() as usize;
267        (len, Some(len))
268    }
269}
270
271// Implementing ExactSizeIterator unlocks additional optimizations automatically
272impl ExactSizeIterator for BitSet64Iter {}
273impl core::iter::FusedIterator for BitSet64Iter {}
274
275/// Non-consuming iterator for bitset reference.
276impl IntoIterator for &BitSet64 {
277    type Item = u8;
278    type IntoIter = BitSet64Iter;
279
280    fn into_iter(self) -> Self::IntoIter {
281        // Since `BitSet64` is `Copy` and just a `(u64)`,
282        // we just pass the underlying value to the iterator.
283        BitSet64Iter(self.0)
284    }
285}
286
287/// Non-consuming iterator for bitset.
288impl IntoIterator for BitSet64 {
289    type Item = u8;
290    type IntoIter = BitSet64Iter;
291
292    fn into_iter(self) -> Self::IntoIter {
293        // Since `BitSet64` is `Copy` and just a `(u64)`,
294        // we just pass the underlying value to the iterator.
295        BitSet64Iter(self.0)
296    }
297}
298
299/// From iterator for bitset.
300impl FromIterator<u8> for BitSet64 {
301    fn from_iter<I: IntoIterator<Item = u8>>(iter: I) -> Self {
302        let mut bitset = Self::new();
303        for index in iter {
304            bitset.set(index);
305        }
306        bitset
307    }
308}
309
310impl Extend<u8> for BitSet64 {
311    fn extend<I: IntoIterator<Item = u8>>(&mut self, iter: I) {
312        for index in iter {
313            self.set(index);
314        }
315    }
316}
317
318// **** fmt ****
319
320impl fmt::Binary for BitSet64 {
321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322        // Handle the "0b" prefix if requested via {:#b}
323        if f.alternate() {
324            f.write_str("0b")?;
325        }
326        // Print from high bits to low bits (left-to-right)
327        for i in (0..64).rev() {
328            let val = (self.0 >> i) & 1;
329            write!(f, "{val}")?;
330        }
331
332        Ok(())
333    }
334}
335
336impl fmt::UpperHex for BitSet64 {
337    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338        if f.alternate() {
339            f.write_str("0x")?;
340        }
341        write!(f, "{:016X}", self.0)
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348
349    fn is_normal<T: Sized + Send + Sync + Unpin>() {}
350    fn is_full<T: Sized + Send + Sync + Unpin + Copy + Clone + Default + PartialEq>() {}
351    #[cfg(feature = "serde")]
352    fn is_config<T: Serialize + for<'a> Deserialize<'a>>() {}
353
354    #[test]
355    fn normal_types() {
356        is_full::<BitSet64>();
357        #[cfg(feature = "serde")]
358        is_config::<BitSet64>();
359        is_normal::<BitSet64Iter>();
360    }
361
362    #[test]
363    fn new() {
364        let mut bits = BitSet64::new();
365        bits.set(42);
366        assert!(bits[42u8]);
367        assert!(bits.test(42));
368    }
369
370    #[test]
371    fn const_new() {
372        const FLAGS: BitSet64 = BitSet64::new();
373        const EMPTY_CHECK: bool = FLAGS.is_empty(); // Evaluated at compile time
374        assert_eq!(0, FLAGS.0);
375        #[allow(clippy::assertions_on_constants)]
376        {
377            assert!(EMPTY_CHECK);
378        }
379    }
380
381    #[test]
382    fn assign() {
383        let mut bits = BitSet64::new();
384        bits.set(42);
385        assert!(bits[42u8]);
386        assert!(bits.test(42));
387        let mask = bits;
388        assert!(mask.test(42));
389    }
390
391    #[test]
392    fn from() {
393        let _bits = BitSet64::from((0xab_u32, 0x12_u32));
394    }
395
396    #[test]
397    fn flip_all() {
398        let mut bitset = BitSet64::new();
399
400        // Alternating pattern test
401        bitset.set(0);
402        bitset.set(32);
403
404        bitset.flip_all();
405
406        // Bit 0 and 64 should now be 0, others should be 1
407        assert!(!bitset.test(0));
408        assert!(!bitset.test(32));
409        assert!(bitset.test(1));
410        assert!(bitset.test(33));
411
412        // Full cycle test (Empty -> Full -> Empty)
413        let mut empty_set = BitSet64::new();
414        empty_set.flip_all(); // Should become full
415
416        let mut full_set = BitSet64::new();
417        full_set.set_all();
418
419        assert_eq!(empty_set, full_set);
420
421        empty_set.flip_all(); // Should return to completely empty
422        assert!(empty_set.is_empty());
423    }
424
425    #[test]
426    fn inplace_logical_ops() {
427        let mut set_a = BitSet64::new();
428        let mut set_b = BitSet64::new();
429
430        // Setup overlapping patterns crossing 64-bit boundaries
431        set_a.set(10);
432        set_a.set(50);
433
434        set_b.set(10);
435        set_b.set(60);
436
437        // Test BitAndAssign (&=)
438        let mut result = set_a;
439        result &= set_b;
440        assert!(result.test(10));
441        assert!(!result.test(50));
442        assert!(!result.test(60));
443
444        // Test BitOrAssign (|=)
445        let mut result = set_a;
446        result |= set_b;
447        assert!(result.test(10));
448        assert!(result.test(50));
449        assert!(result.test(60));
450
451        // Test BitXorAssign (^=)
452        let mut result = set_a;
453        result ^= set_b;
454        assert!(!result.test(10)); // Both were 1, turns to 0
455        assert!(result.test(50));
456        assert!(result.test(60));
457
458        // Test and_not
459        let mut result = set_a;
460        result.and_not(set_b);
461        assert!(!result.test(10)); // Cleared by mask
462        assert!(result.test(50)); // Preserved
463        assert!(!result.test(60)); // Never present in set_a
464    }
465
466    #[test]
467    fn exercise() {
468        let mut system_flags = BitSet64::new();
469        let error_mask = BitSet64::new(); // imagine this has error bits set
470
471        // Combine with OR-assign
472        system_flags |= error_mask;
473
474        // Toggle bits with XOR-assign
475        system_flags ^= error_mask;
476
477        // Mask out bits with AND-assign
478        system_flags &= BitSet64(0x0000_FFFF_FFFF_FFFF);
479
480        let mut set_a = BitSet64::new();
481        set_a.set(10);
482        set_a.set(20);
483
484        let mut set_b = BitSet64::new();
485        set_b.set(20);
486        set_b.set(30);
487
488        // Intersection (AND): only bit 20 remains
489        let common = set_a & set_b;
490        assert!(!common.test(10));
491        assert!(common.test(20));
492        assert!(!common.test(30));
493
494        // Union (OR): bits 10, 20, and 30 are set
495        let all = set_a | set_b;
496        assert!(all.test(10));
497        assert!(all.test(20));
498        assert!(all.test(30));
499
500        // Difference (XOR): bits 10 and 30 are set (20 is cancelled out)
501        let diff = set_a ^ set_b;
502        assert!(diff.test(10));
503        assert!(!diff.test(20));
504        assert!(diff.test(30));
505    }
506
507    #[test]
508    fn iterator_consuming() {
509        let mut bits = BitSet64::new();
510        bits.set(2);
511        bits.set(10);
512
513        let mut sum = 0;
514        let mut count = 0;
515        for bit in &bits {
516            sum += bit;
517            count += 1;
518        }
519        assert_eq!(2, count);
520        assert_eq!(12, sum);
521    }
522
523    #[test]
524    fn into_iter_consuming() {
525        let mut bits = BitSet64::new();
526        bits.set(0);
527        bits.set(10);
528        bits.set(63);
529
530        // Consuming iterator
531        let mut iter = bits.into_iter();
532
533        assert_eq!(iter.next(), Some(0));
534        assert_eq!(iter.next(), Some(10));
535        assert_eq!(iter.next(), Some(63));
536        assert_eq!(iter.next(), None);
537
538        // bits is moved here and can no longer be used
539    }
540
541    #[test]
542    fn non_consuming_iterator() {
543        let bits = BitSet64(0b1101); // Bits 0, 2, and 3 are set
544
545        let mut sum = 0;
546        let mut count = 0;
547
548        // Use reference to bits rather than bits.iter()
549        for bit in &bits {
550            sum += bit;
551            count += 1;
552        }
553        assert_eq!(3, count);
554        assert_eq!(5, sum);
555
556        let mut sum = 0;
557        let mut count = 0;
558        // Using a reference in a loop
559        for bit in &bits {
560            sum += bit;
561            count += 1;
562        }
563        assert_eq!(3, count);
564        assert_eq!(5, sum);
565    }
566
567    #[test]
568    fn non_consuming_iterator2() {
569        let mut bits = BitSet64::new();
570        bits.set(5);
571        bits.set(12);
572
573        // Test using the .iter() method
574        let count = bits.iter().count();
575        assert_eq!(count, 2);
576
577        // Test using & reference in a for-loop
578        let mut last_val = 0;
579        for bit in &bits {
580            last_val = bit;
581        }
582        assert_eq!(last_val, 12);
583
584        // test original bits is still valid
585        assert!(bits.test(5));
586    }
587
588    #[test]
589    fn from_iterator() {
590        let indices = [1, 3, 5];
591        // collect() uses FromIterator
592        let bits: BitSet64 = indices.iter().copied().collect();
593
594        assert!(bits.test(1));
595        assert!(bits.test(3));
596        assert!(bits.test(5));
597        assert!(!bits.test(2));
598    }
599
600    #[test]
601    fn empty_and_full() {
602        let empty = BitSet64::new();
603        assert_eq!(empty.iter().count(), 0);
604
605        let mut full = BitSet64::new();
606        full.set_all();
607        assert_eq!(full.iter().count(), 64);
608    }
609}