Skip to main content

simple_ring/
bitwriting.rs

1pub struct BitWriter {
2    buf: Vec<u8>,
3    acc: u8,
4    filled: u8,
5}
6
7impl BitWriter {
8    pub fn new(capacity_bytes: usize) -> Self {
9        Self {
10            buf: Vec::with_capacity(capacity_bytes),
11            acc: 0,
12            filled: 0,
13        }
14    }
15
16    pub fn write_bit(&mut self, bit: u8) {
17        self.acc |= (bit & 1) << self.filled;
18        self.filled += 1;
19
20        if self.filled == 8 {
21            self.buf.push(self.acc);
22            self.acc = 0;
23            self.filled = 0;
24        }
25    }
26
27    pub fn write_bits(&mut self, mut value: u64, bits: usize) {
28        for _ in 0..bits {
29            self.write_bit((value & 1) as u8);
30            value >>= 1;
31        }
32    }
33
34    pub fn finish(mut self) -> Vec<u8> {
35        if self.filled > 0 {
36            self.buf.push(self.acc);
37        }
38        self.buf
39    }
40}