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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use crate::BitWrite;

// FileBitWriter
pub struct FileBitWriter {
    scratch: u8,
    scratch_index: u8,
    buffer: Vec<u8>,
}

impl FileBitWriter {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self {
            scratch: 0,
            scratch_index: 0,
            buffer: Vec::new(),
        }
    }

    fn finalize(&mut self) {
        if self.scratch_index > 0 {
            let value = (self.scratch << (8 - self.scratch_index)).reverse_bits();
            self.buffer.push(value);
        }
    }

    pub fn to_bytes(mut self) -> Box<[u8]> {
        self.finalize();
        Box::from(self.buffer)
    }

    pub fn to_vec(mut self) -> Vec<u8> {
        self.finalize();
        self.buffer
    }
}

impl BitWrite for FileBitWriter {
    fn write_bit(&mut self, bit: bool) {
        self.scratch <<= 1;

        if bit {
            self.scratch |= 1;
        }

        self.scratch_index += 1;

        if self.scratch_index >= 8 {
            let value = self.scratch.reverse_bits();
            self.buffer.push(value);
            self.scratch_index -= 8;
            self.scratch = 0;
        }
    }

    fn write_byte(&mut self, byte: u8) {
        let mut temp = byte;
        for _ in 0..8 {
            self.write_bit(temp & 1 != 0);
            temp >>= 1;
        }
    }

    fn count_bits(&mut self, _: u32) {
        panic!("This method should not be called for FileBitWriter!");
    }

    fn is_counter(&self) -> bool {
        panic!("This method should not be called for FileBitWriter!");
    }
}