Skip to main content

steel_utils/codec/
bit_set.rs

1use std::io::{Cursor, Result, Write};
2
3use crate::serial::{PrefixedRead, PrefixedWrite, ReadFrom, WriteTo};
4
5use super::VarInt;
6
7/// A simple bit set implementation.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct BitSet(pub Box<[u64]>);
10
11impl BitSet {
12    /// Sets the bit at the given index.
13    pub fn set(&mut self, index: usize, value: bool) {
14        let u64_index = index / 64;
15        let bit_index = index % 64;
16
17        if u64_index >= self.0.len() {
18            return;
19        }
20
21        if value {
22            self.0[u64_index] |= 1 << bit_index;
23        } else {
24            self.0[u64_index] &= !(1 << bit_index);
25        }
26    }
27}
28
29impl ReadFrom for BitSet {
30    fn read(data: &mut Cursor<&[u8]>) -> Result<Self> {
31        Ok(Self(Vec::read_prefixed::<VarInt>(data)?.into_boxed_slice()))
32    }
33}
34
35impl WriteTo for BitSet {
36    fn write(&self, writer: &mut impl Write) -> Result<()> {
37        self.0.write_prefixed::<VarInt>(writer)
38    }
39}