Skip to main content

rten_base/
bit_set.rs

1/// Wraps an integer type `B` to treat it as a set of bit flags.
2#[derive(Copy, Clone, Default, PartialEq)]
3pub struct BitSet<B: BitOps = u32>(B);
4
5impl<B: BitOps> BitSet<B> {
6    /// Return a bit set with all positions cleared.
7    pub fn new() -> Self {
8        Self(B::ZERO)
9    }
10
11    /// Return a bit set with the first `n` positions set.
12    pub fn ones(n: u32) -> Self {
13        let bits = if n >= B::BITS {
14            B::MAX
15        } else {
16            B::nth(n) - B::ONE
17        };
18        Self(bits)
19    }
20
21    /// Return a bit set with given indices set.
22    pub fn from_indices<I: IntoIterator<Item = u32>>(indices: I) -> Self {
23        let mut bits = Self(B::ZERO);
24        for pos in indices {
25            bits.set(pos);
26        }
27        bits
28    }
29
30    /// Unset the bit at position `pos`.
31    pub fn delete(&mut self, pos: u32) {
32        self.0 &= !B::nth(pos)
33    }
34
35    /// Set the bit at position `pos`.
36    pub fn set(&mut self, pos: u32) {
37        self.0 |= B::nth(pos);
38    }
39
40    /// Return true if position `pos` is set.
41    pub fn get(&self, pos: u32) -> bool {
42        self.0 & B::nth(pos) != B::ZERO
43    }
44
45    /// Return the number of bits set.
46    pub fn count_true(&self) -> u32 {
47        self.0.count_ones()
48    }
49
50    /// Return true if no bits are set.
51    pub fn is_empty(&self) -> bool {
52        self.0 == B::ZERO
53    }
54
55    /// Return an iterator over the indices of set positions.
56    pub fn iter(&self) -> impl Iterator<Item = u32> {
57        (0..B::BITS).filter(|pos| self.get(*pos))
58    }
59}
60
61impl<B: BitOps> std::fmt::Debug for BitSet<B> {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        write!(f, "{:b}", self.0)
64    }
65}
66
67/// Operations needed for types that can be used as a [`BitSet`].
68pub trait BitOps:
69    Copy
70    + Default
71    + Eq
72    + std::fmt::Binary
73    + std::ops::BitAnd<Self, Output = Self>
74    + std::ops::BitAndAssign
75    + std::ops::BitOr<Self, Output = Self>
76    + std::ops::BitOrAssign
77    + std::ops::Not<Output = Self>
78    + std::ops::Sub<Self, Output = Self>
79{
80    /// Number of bits in this type.
81    const BITS: u32;
82
83    /// Maximum value of this type.
84    const MAX: Self;
85
86    const ZERO: Self;
87    const ONE: Self;
88
89    /// Return the number of bits set to one.
90    fn count_ones(self) -> u32;
91
92    /// Return `Self` with bit `idx` set to one.
93    fn nth(idx: u32) -> Self;
94}
95
96macro_rules! impl_bitops {
97    ($ty:ty) => {
98        impl BitOps for $ty {
99            const BITS: u32 = <$ty>::BITS;
100            const MAX: $ty = <$ty>::MAX;
101            const ZERO: $ty = 0;
102            const ONE: $ty = 1;
103
104            fn count_ones(self) -> u32 {
105                <$ty>::count_ones(self)
106            }
107
108            fn nth(idx: u32) -> Self {
109                (1 << idx) as Self
110            }
111        }
112    };
113}
114
115impl_bitops!(u8);
116impl_bitops!(u16);
117impl_bitops!(u32);
118impl_bitops!(u64);
119impl_bitops!(u128);
120impl_bitops!(usize);
121
122#[cfg(test)]
123mod tests {
124    use super::BitSet;
125
126    #[test]
127    fn test_bit_set() {
128        let mut set = BitSet::<u32>::ones(5);
129        assert_eq!(set.count_true(), 5);
130        assert!(!set.is_empty());
131        for i in 0..5 {
132            assert!(set.get(i));
133            set.delete(i);
134            assert!(!set.get(i));
135        }
136        assert_eq!(set.count_true(), 0);
137        assert!(set.is_empty());
138
139        let all_zeros = BitSet::<u32>::default();
140        assert_eq!(all_zeros.count_true(), 0);
141        assert_eq!(BitSet::<u32>::new(), all_zeros);
142    }
143
144    #[test]
145    fn test_bit_set_ones() {
146        for i in 0..=32 {
147            let all_ones = BitSet::<u32>::ones(i);
148            assert_eq!(all_ones.count_true(), i);
149        }
150    }
151
152    #[test]
153    fn test_bit_set_iter() {
154        let mut set = BitSet::<u32>::ones(6);
155        set.delete(0);
156        set.delete(5);
157
158        let positions: Vec<_> = set.iter().collect();
159        assert_eq!(positions, [1, 2, 3, 4]);
160    }
161
162    #[test]
163    fn test_bit_set_from_indices() {
164        let set = BitSet::<u32>::from_indices([0, 3]);
165        for i in 0..u32::BITS {
166            assert_eq!(set.get(i), i == 0 || i == 3);
167        }
168    }
169}