Skip to main content

leodos_protocols/transport/srspp/machine/receiver/utils/
bitset.rs

1/// Fixed-size bitset backed by a single `u32` (max 32 bits).
2#[derive(Clone, Copy)]
3pub struct Bitset<const N: usize> {
4    /// Underlying bit storage.
5    bits: u32,
6}
7
8impl<const N: usize> Bitset<N> {
9    /// Create a new empty bitset.
10    pub const fn new() -> Self {
11        Self { bits: 0 }
12    }
13
14    /// Set bit `i`.
15    pub fn set(&mut self, i: usize) {
16        debug_assert!(i < N);
17        self.bits |= 1 << i;
18    }
19
20    /// Clear bit `i`.
21    pub fn clear(&mut self, i: usize) {
22        debug_assert!(i < N);
23        self.bits &= !(1 << i);
24    }
25
26    /// Returns true if bit `i` is set.
27    pub fn is_set(&self, i: usize) -> bool {
28        debug_assert!(i < N);
29        self.bits & (1 << i) != 0
30    }
31
32    /// Returns true if any bit is set.
33    pub fn any(&self) -> bool {
34        self.bits & ((1u32 << N) - 1) != 0
35    }
36
37    /// Clear all bits.
38    pub fn clear_all(&mut self) {
39        self.bits = 0;
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn bitset_basic() {
49        let mut bs = Bitset::<8>::new();
50        assert!(!bs.is_set(0));
51        assert!(!bs.any());
52
53        bs.set(3);
54        assert!(bs.is_set(3));
55        assert!(!bs.is_set(2));
56        assert!(bs.any());
57
58        bs.clear(3);
59        assert!(!bs.is_set(3));
60        assert!(!bs.any());
61    }
62}