Skip to main content

azalea_protocol/common/
bitset.rs

1use azalea_buf::AzBuf;
2use azalea_core::bitset::JavaBitSet;
3
4/// A bitset that's transmitted over the protocol.
5///
6/// This should be converted into a [`JavaBitSet`] before use, although note
7/// that this can be a lossy process if the number of bits isn't a multiple of
8/// 8.
9#[derive(AzBuf, Clone, Debug, Default, PartialEq)]
10pub struct BitSet {
11    pub data: Box<[u8]>,
12}
13
14impl From<BitSet> for JavaBitSet {
15    fn from(bitset: BitSet) -> Self {
16        // this is unlikely to be a bottleneck in a real program, so the
17        // implementation is deliberately prioritizes readability over
18        // performance. if it does end up needing to be optimized at at some
19        // point, we should also add tests for this then
20        let num_bits = bitset.data.len() * 8;
21        let mut result = JavaBitSet::new(num_bits);
22        for index in 0..num_bits {
23            if bitset.get(index).unwrap_or_default() {
24                result.set(index);
25            }
26        }
27        result
28    }
29}
30impl From<JavaBitSet> for BitSet {
31    fn from(bitset: JavaBitSet) -> Self {
32        let num_bits = bitset.len();
33        let mut result = BitSet {
34            data: vec![0; num_bits / 8].into(),
35        };
36        for index in 0..num_bits {
37            if bitset.get(index).unwrap_or_default() {
38                result.set(index);
39            }
40        }
41        result
42    }
43}
44
45impl BitSet {
46    // this is private because the user should convert to a javabitset before
47    // use
48    fn get(&self, index: usize) -> Option<bool> {
49        self.data
50            .get(index / 8)
51            .map(|word| (word & (1u8 << (index % 8))) != 0)
52    }
53    pub fn set(&mut self, bit_index: usize) {
54        self.data[bit_index / 8] |= 1u8 << (bit_index % 8);
55    }
56}