pub struct BitWriter<'a> { /* private fields */ }Expand description
Writes packed bits to a caller-supplied byte slice, most-significant-bit first.
Every bit inside the prefix reported by BitWriter::finish is written
explicitly: field bits by BitWriter::write_bits, padding bits as zero
by BitWriter::align_to_byte and BitWriter::finish. A reused buffer
holding stale data therefore produces the same output as a zeroed one.
Bytes past that prefix are left untouched.
§Example
use wire_codec::BitWriter;
let mut storage = [0u8; 1];
let mut w = BitWriter::new(&mut storage);
w.write_bits(0b101, 3).unwrap();
w.write_bits(0b01100, 5).unwrap();
assert_eq!(w.finish(), 1);
assert_eq!(storage[0], 0xAC);Implementations§
Source§impl<'a> BitWriter<'a>
impl<'a> BitWriter<'a>
Sourcepub fn new(bytes: &'a mut [u8]) -> Self
pub fn new(bytes: &'a mut [u8]) -> Self
Wrap bytes in a new bit cursor. Existing contents of bytes are
overwritten as bits are written.
Sourcepub fn bits_written(&self) -> usize
pub fn bits_written(&self) -> usize
Number of bits written so far.
Sourcepub fn align_to_byte(&mut self) -> Result<()>
pub fn align_to_byte(&mut self) -> Result<()>
Pad the cursor with zero bits up to the next byte boundary.
Has no effect when the cursor is already byte-aligned.
§Errors
Never fails in practice: a partially written byte always lies inside
the backing slice, so rounding up to its end cannot run out of room.
The Result return type is kept for API stability.
Sourcepub fn write_bits(&mut self, value: u64, n: u32) -> Result<()>
pub fn write_bits(&mut self, value: u64, n: u32) -> Result<()>
Write the low n bits of value into the buffer.
§Errors
Error::BitOverflowifnis0, greater thanMAX_BIT_WIDTH, orvaluehas bits set above positionn.Error::BufferFullif fewer thannbits remain in the buffer.
Sourcepub fn write_bool(&mut self, value: bool) -> Result<()>
pub fn write_bool(&mut self, value: bool) -> Result<()>
Write one bit: 1 for true, 0 for false.
§Errors
Returns Error::BufferFull if no bits remain in the buffer.
§Example
use wire_codec::BitWriter;
let mut storage = [0u8; 1];
let mut w = BitWriter::new(&mut storage);
w.write_bool(true).unwrap();
w.write_bool(false).unwrap();
w.write_bool(true).unwrap();
assert_eq!(w.finish(), 1);
assert_eq!(storage[0], 0b1010_0000);Sourcepub fn write_signed_bits(&mut self, value: i64, n: u32) -> Result<()>
pub fn write_signed_bits(&mut self, value: i64, n: u32) -> Result<()>
Write value as an n-bit two’s-complement field.
§Errors
Error::BitOverflowifnis0, greater thanMAX_BIT_WIDTH, orvalueis outside-(2^(n-1))..2^(n-1).Error::BufferFullif fewer thannbits remain in the buffer.
§Example
use wire_codec::{BitReader, BitWriter, Error};
let mut storage = [0u8; 1];
let mut w = BitWriter::new(&mut storage);
w.write_signed_bits(-3, 3).unwrap();
assert_eq!(w.write_signed_bits(4, 3), Err(Error::BitOverflow));
assert_eq!(w.finish(), 1);
assert_eq!(BitReader::new(&storage).read_signed_bits(3).unwrap(), -3);