| 1 |
use std::io; |
| 2 |
|
| 3 |
use bitstream_io::{BigEndian, BitWrite, BitWriter, Integer}; |
| 4 |
|
| 5 |
use crate::signed_to_unsigned; |
| 6 |
|
| 7 |
pub struct BitstreamIoWriter(BitWriter<Vec<u8>, BigEndian>); |
| 8 |
|
| 9 |
impl BitstreamIoWriter { |
| 10 |
pub fn with_capacity(capacity: usize) -> Self { |
| 11 |
let write = Vec::with_capacity(capacity); |
| 12 |
|
| 13 |
Self(BitWriter::new(write)) |
| 14 |
} |
| 15 |
|
| 16 |
#[inline(always)] |
| 17 |
pub fn write_bit(&mut self, bit: bool) -> io::Result<()> { |
| 18 |
self.0.write_bit(bit) |
| 19 |
} |
| 20 |
|
| 21 |
#[inline(always)] |
| 22 |
pub fn write<const BITS: u32, I: Integer>(&mut self, value: I) -> io::Result<()> { |
| 23 |
self.0.write::<BITS, I>(value) |
| 24 |
} |
| 25 |
|
| 26 |
#[inline(always)] |
| 27 |
pub fn write_const<const BITS: u32, const VALUE: u32>(&mut self) -> io::Result<()> { |
| 28 |
self.0.write_const::<BITS, VALUE>() |
| 29 |
} |
| 30 |
|
| 31 |
#[inline(always)] |
| 32 |
pub fn write_var<I: Integer>(&mut self, bits: u32, value: I) -> io::Result<()> { |
| 33 |
self.0.write_var(bits, value) |
| 34 |
} |
| 35 |
|
| 36 |
#[inline(always)] |
| 37 |
pub fn write_ue(&mut self, v: u64) -> io::Result<()> { |
| 38 |
if v == 0 { |
| 39 |
self.write_bit(true) |
| 40 |
} else { |
| 41 |
let mut tmp = v + 1; |
| 42 |
let mut leading_zeroes: i64 = -1; |
| 43 |
|
| 44 |
while tmp > 0 { |
| 45 |
tmp >>= 1; |
| 46 |
leading_zeroes += 1; |
| 47 |
} |
| 48 |
|
| 49 |
let leading_zeroes = leading_zeroes as u32; |
| 50 |
self.0.write_unary::<1>(leading_zeroes)?; |
| 51 |
|
| 52 |
let remaining = v + 1 - (1 << leading_zeroes); |
| 53 |
self.write_var(leading_zeroes, remaining) |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
#[inline(always)] |
| 58 |
pub fn write_se(&mut self, v: i64) -> io::Result<()> { |
| 59 |
self.write_ue(signed_to_unsigned(v)) |
| 60 |
} |
| 61 |
|
| 62 |
#[inline(always)] |
| 63 |
pub fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> { |
| 64 |
self.0.write_bytes(buf) |
| 65 |
} |
| 66 |
|
| 67 |
#[inline(always)] |
| 68 |
pub fn byte_aligned(&self) -> bool { |
| 69 |
self.0.byte_aligned() |
| 70 |
} |
| 71 |
|
| 72 |
#[inline(always)] |
| 73 |
pub fn byte_align(&mut self) -> io::Result<()> { |
| 74 |
self.0.byte_align() |
| 75 |
} |
| 76 |
|
| 77 |
#[inline(always)] |
| 78 |
pub fn pad(&mut self, bits: u32) -> io::Result<()> { |
| 79 |
self.0.pad(bits) |
| 80 |
} |
| 81 |
|
| 82 |
|
| 83 |
pub fn as_slice(&mut self) -> Option<&[u8]> { |
| 84 |
self.0.writer().map(|e| e.as_slice()) |
| 85 |
} |
| 86 |
|
| 87 |
pub fn into_inner(self) -> Vec<u8> { |
| 88 |
self.0.into_writer() |
| 89 |
} |
| 90 |
} |