aboutsummaryrefslogtreecommitdiffstats
path: root/src/bitset.rs
blob: 90dc2c5fedd5b25b0a1c9fc450cb424df79bc118 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#[derive(Clone, PartialEq, Eq)]
pub struct BitSet {
    data: Vec<u32>,
    size: usize,
}

const BITS: usize = 32;

impl BitSet {
    pub fn new(size: usize) -> Self {
        Self {
            size,
            data: vec![0; size.div_ceil(32)],
        }
    }

    pub fn set(&mut self, bit: usize, val: bool) {
        assert!(bit < self.size);
        let idx = bit / BITS;
        let bit = bit % BITS;

        if val {
            self.data[idx] |= 1 << bit;
        } else {
            self.data[idx] &= !(1 << bit);
        }
    }

    pub fn get(&self, bit: usize) -> bool {
        assert!(bit < self.size);
        let idx = bit / BITS;
        let bit = bit % BITS;

        (self.data[idx] & (1 << bit)) != 0
    }

    pub fn set_all(&mut self, val: bool) {
        let val = if val { !0 } else { 0 };
        for d in self.data.iter_mut() {
            *d = val;
        }
    }
}

impl std::fmt::Debug for BitSet {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for i in 0..self.size {
            if self.get(i) {
                write!(f, "1")?;
            } else {
                write!(f, "0")?;
            }
        }
        Ok(())
    }
}