use alloc::vec::Vec;
pub(super) struct BitWriter {
out: Vec<u8>,
container: u64,
bits: u32,
}
impl BitWriter {
pub(super) fn new() -> Self {
Self {
out: Vec::new(),
container: 0,
bits: 0,
}
}
pub(super) fn push(&mut self, value: u32, nbits: u32) {
debug_assert!(nbits <= 28);
debug_assert!(nbits == 0 || u64::from(value) < (1u64 << nbits));
self.container |= u64::from(value) << self.bits;
self.bits += nbits;
while self.bits >= 8 {
self.out.push(self.container as u8);
self.container >>= 8;
self.bits -= 8;
}
}
pub(super) fn finish_forward(mut self) -> Vec<u8> {
if self.bits > 0 {
self.out.push(self.container as u8);
}
self.out
}
pub(super) fn finish(mut self) -> Vec<u8> {
self.push(1, 1);
if self.bits > 0 {
self.out.push(self.container as u8);
}
self.out
}
}