Skip to main content

blues_lsp/util/data/
bitset.rs

1#[derive(Debug, Clone, Copy)]
2pub struct BitSet<const N: usize> {
3    words: [u128; N],
4}
5
6impl<const N: usize> Default for BitSet<N> {
7    fn default() -> Self {
8        Self::new()
9    }
10}
11
12impl<const N: usize> BitSet<N> {
13    pub const fn new() -> Self {
14        Self { words: [0; N] }
15    }
16
17    const fn word_at(&self, bit: usize) -> &u128 {
18        &self.words[bit / u128::BITS as usize]
19    }
20
21    const fn word_at_mut(&mut self, bit: usize) -> &mut u128 {
22        &mut self.words[bit / u128::BITS as usize]
23    }
24
25    const fn bit_word(&self, bit: usize) -> u128 {
26        1 << (bit % u128::BITS as usize)
27    }
28
29    pub const fn add(&mut self, bit: usize) {
30        *self.word_at_mut(bit) |= self.bit_word(bit);
31    }
32
33    pub const fn remove(&mut self, bit: usize) {
34        *self.word_at_mut(bit) &= !self.bit_word(bit);
35    }
36
37    pub const fn contains(&self, bit: usize) -> bool {
38        (*self.word_at(bit) & self.bit_word(bit)) != 0
39    }
40
41    pub const fn union(&mut self, other: BitSet<N>) {
42        let mut i = 0;
43        while i < N {
44            self.words[i] |= other.words[i];
45            i += 1;
46        }
47    }
48}
49
50#[cfg(test)]
51mod test {
52    use super::BitSet;
53
54    #[test]
55    fn test() {
56        let mut set = BitSet::<2>::new();
57
58        set.add(0);
59        set.add(1);
60        set.add(10);
61        set.add(20);
62        set.add(30);
63        set.add(60);
64        set.add(100);
65        set.add(200);
66        set.add(255);
67
68        assert!(set.contains(0));
69        assert!(set.contains(1));
70        assert!(set.contains(10));
71        assert!(set.contains(20));
72        assert!(set.contains(30));
73        assert!(set.contains(60));
74        assert!(set.contains(100));
75        assert!(set.contains(200));
76        assert!(set.contains(255));
77
78        assert!(!set.contains(2));
79        assert!(!set.contains(3));
80        assert!(!set.contains(11));
81        assert!(!set.contains(21));
82        assert!(!set.contains(31));
83        assert!(!set.contains(61));
84        assert!(!set.contains(101));
85        assert!(!set.contains(201));
86        assert!(!set.contains(254));
87
88        assert!(!set.contains(32));
89        assert!(!set.contains(64));
90        assert!(!set.contains(128));
91    }
92}