pawkit_bitarray/
lib.rs

1pub struct BitArray {
2    data: Box<[u8]>,
3}
4
5impl BitArray {
6    pub fn new(len: usize) -> Self {
7        return Self {
8            data: vec![0; (len + 7) >> 3].into_boxed_slice(),
9        };
10    }
11
12    pub fn len(&self) -> usize {
13        return self.data.len() * 8;
14    }
15
16    pub fn get(&self, index: usize) -> Option<bool> {
17        if index >= self.len() {
18            return None;
19        }
20
21        // SAFETY: We just bounds checked.
22        // The Rust compiler doesn't understand enough about our code to know that the size of the data is self.len() >> 3.
23        unsafe {
24            let value = self.data.get_unchecked(index >> 3);
25
26            return Some((*value & (1 << (index & 7))) != 0);
27        }
28    }
29
30    pub fn set(&mut self, index: usize) {
31        if index >= self.len() {
32            return;
33        }
34
35        // SAFETY: We just bounds checked.
36        // The Rust compiler doesn't understand enough about our code to know that the size of the data is self.len() >> 3.
37        unsafe {
38            let value = self.data.get_unchecked_mut(index >> 3);
39
40            *value |= 1 << (index & 7);
41        }
42    }
43
44    pub fn reset(&mut self, index: usize) {
45        if index >= self.len() {
46            return;
47        }
48
49        // SAFETY: We just bounds checked.
50        // The Rust compiler doesn't understand enough about our code to know that the size of the data is self.len() >> 3.
51        unsafe {
52            let value = self.data.get_unchecked_mut(index >> 3);
53
54            *value &= !(1 << (index & 7));
55        }
56    }
57
58    pub fn clear(&mut self) {
59        for byte in self.data.iter_mut() {
60            *byte = 0;
61        }
62    }
63
64    pub fn fill(&mut self) {
65        for byte in self.data.iter_mut() {
66            *byte = 0xFF;
67        }
68    }
69}