pub struct BitWriter { /* private fields */ }Expand description
A growable, MSB-first bit buffer.
Uses a bit cache: bits accumulate in the low nbits positions of a 64-bit
cache (the most-recently-written bit is least-significant within the valid
region), and whole bytes are flushed off the top. A multi-bit write is a shift
- OR + a short byte-flush loop — not one operation per bit. After every public
write the invariant
nbits < 8and “bits abovenbitsare zero” hold.
Implementations§
Source§impl BitWriter
impl BitWriter
Sourcepub fn with_capacity(bytes: usize) -> Self
pub fn with_capacity(bytes: usize) -> Self
Creates a writer with bytes pre-reserved — for the per-frame slice writer,
so the CAVLC hot loop never pays a Vec realloc mid-frame.
Sourcepub fn is_byte_aligned(&self) -> bool
pub fn is_byte_aligned(&self) -> bool
true if the writer is on a byte boundary.
Sourcepub fn write_bits(&mut self, value: u32, n: u32)
pub fn write_bits(&mut self, value: u32, n: u32)
Writes the low n bits of value, most-significant first (u(n)). n <= 32.
Keeps up to 31 pending bits in cache and flushes a whole u32 word (4
bytes) at a time, like openh264’s BsWriteBits (WRITE_BE_32) — a quarter
the Vec writes of byte-at-a-time flushing.
Sourcepub fn append(&mut self, other: &BitWriter)
pub fn append(&mut self, other: &BitWriter)
Appends every bit of other, in order, at this writer’s current position.
Neither writer need be byte-aligned. This is what lets a macroblock be
encoded into a scratch writer before the syntax that must precede it is
known (mb_skip_run is only decided once the macroblock’s own cost is), so
the encoder can commit one encode rather than trialing and repeating it.
Sound for CAVLC because a macroblock’s Exp-Golomb/VLC syntax does not depend
on its bit position; an arithmetic coder (CABAC) could NOT be spliced this
way, since its state is carried across the whole slice.
Sourcepub fn write_se(&mut self, value: i32)
pub fn write_se(&mut self, value: i32)
Signed Exp-Golomb code se(v): 0->0, 1->1, -1->2, 2->3, -2->4, ....
Sourcepub fn rbsp_trailing_bits(&mut self)
pub fn rbsp_trailing_bits(&mut self)
Writes the rbsp_trailing_bits(): a stop bit 1 then zero-pad to a byte.
Sourcepub fn align_zero(&mut self)
pub fn align_zero(&mut self)
Pads with zero bits to the next byte boundary (no stop bit), then flushes
the pending whole bytes from the cache (the word-flush in write_bits can
leave up to 31 pending bits).
Sourcepub fn into_bytes(self) -> Vec<u8> ⓘ
pub fn into_bytes(self) -> Vec<u8> ⓘ
Consumes the writer, returning the byte buffer. Flushes any whole bytes
still pending in the cache; panics if a sub-byte remainder is left (call
rbsp_trailing_bits or
align_zero first).