const BUF_SIZE: i32 = 16;
pub(crate) struct BitWriter {
pub(crate) out: Vec<u8>,
pub(crate) bi_buf: u16,
pub(crate) bi_valid: i32,
}
impl BitWriter {
pub(crate) fn new() -> Self {
Self {
out: Vec::new(),
bi_buf: 0,
bi_valid: 0,
}
}
#[inline]
pub(crate) fn put_byte(&mut self, b: u8) {
self.out.push(b);
}
#[inline]
pub(crate) fn put_short(&mut self, w: u16) {
self.out.push((w & 0xff) as u8);
self.out.push((w >> 8) as u8);
}
#[inline]
pub(crate) fn send_bits(&mut self, value: i32, length: i32) {
let v = (value as u32) & 0xffff;
if self.bi_valid > BUF_SIZE - length {
self.bi_buf |= (v << (self.bi_valid as u32)) as u16;
self.put_short(self.bi_buf);
self.bi_buf = (v >> ((BUF_SIZE - self.bi_valid) as u32)) as u16;
self.bi_valid += length - BUF_SIZE;
} else {
self.bi_buf |= (v << (self.bi_valid as u32)) as u16;
self.bi_valid += length;
}
}
pub(crate) fn bi_windup(&mut self) {
if self.bi_valid > 8 {
self.put_short(self.bi_buf);
} else if self.bi_valid > 0 {
self.put_byte(self.bi_buf as u8);
}
self.bi_buf = 0;
self.bi_valid = 0;
}
}