pixie_anim_lib/
bits.rs

1//! Bit-level reading and writing utilities.
2
3/// A writer that packs variable-length bits into a byte stream.
4pub struct BitWriter<'a> {
5    buffer: &'a mut Vec<u8>,
6    current_byte: u8,
7    bit_count: u8,
8}
9
10impl<'a> BitWriter<'a> {
11    /// Creates a new BitWriter wrapping the provided byte buffer.
12    pub fn new(buffer: &'a mut Vec<u8>) -> Self {
13        Self {
14            buffer,
15            current_byte: 0,
16            bit_count: 0,
17        }
18    }
19
20    /// Writes `count` bits from `value` to the stream.
21    pub fn write_bits(&mut self, value: u16, count: u8) {
22        let mut remaining_bits = count;
23        let mut val = value as u32;
24
25        while remaining_bits > 0 {
26            let bits_to_write = std::cmp::min(remaining_bits, 8 - self.bit_count);
27            let mask = (1 << bits_to_write) - 1;
28
29            self.current_byte |= ((val & mask) as u8) << self.bit_count;
30
31            self.bit_count += bits_to_write;
32            val >>= bits_to_write;
33            remaining_bits -= bits_to_write;
34
35            if self.bit_count == 8 {
36                self.buffer.push(self.current_byte);
37                self.current_byte = 0;
38                self.bit_count = 0;
39            }
40        }
41    }
42
43    /// Flushes any remaining bits to the buffer, padding with zeros if necessary.
44    pub fn flush(&mut self) {
45        if self.bit_count > 0 {
46            self.buffer.push(self.current_byte);
47            self.current_byte = 0;
48            self.bit_count = 0;
49        }
50    }
51}