Skip to main content

BitBuf

Struct BitBuf 

Source
pub struct BitBuf { /* private fields */ }
Expand description

A push/pull, bit-aware decode buffer for incremental framing.

Feed bytes with push as they arrive — from a socket, a channel, a callback, anything that delivers bytes — and take whole messages off the front with pull, which returns Ok(None) when it needs more bytes (push more and call again).

Unlike a byte cursor (bytes::BytesMut::advance), BitBuf tracks a bit position, so a stream of messages that don’t end on byte boundaries (bit-packed frames) reassembles cleanly: pull advances past the consumed whole bytes and retains any partial trailing byte for the next message. It’s the pushable, in-memory counterpart to BufSource (which pulls from a Read). no_std-compatible (alloc only).

Reclaim is deferred and in place. pull doesn’t drain consumed bytes — the next push/try_push reclaims them in place (one memmove, only when it avoids a reallocation), so a steady push/pull loop reuses the same allocation without per-message churn. For a guaranteed-fixed footprint (real-time / no_std), construct a bounded buffer: it allocates once, try_push refuses bytes past the cap instead of growing, and grow is the only thing that reallocates.

BitBuf is also a SeekSource, so it reads through the same decode entry points as every other cursor: Type::decode(&mut bitbuf) advances its cursor (then call compact to reclaim). For streaming, prefer pull — it bakes the message’s own LAYOUT (so little/lsb messages are always correct), decodes and reclaims, and reports “need more bytes” as Ok(None). The bare Source path instead uses the buffer’s own with_layout order (default msb/big).

use bnb::{bin, BitBuf};
#[bin(big)]
#[derive(Debug, PartialEq, Eq)]
struct Ping { seq: u16 }

let mut bb = BitBuf::new();
bb.push(&[0x00]);                                  // only half of the first message
assert_eq!(bb.pull::<Ping>().unwrap(), None);      // not a whole message yet
bb.push(&[0x01, 0x00, 0x02]);                      // rest of msg 1 + all of msg 2
assert_eq!(bb.pull::<Ping>().unwrap(), Some(Ping { seq: 1 }));
assert_eq!(bb.pull::<Ping>().unwrap(), Some(Ping { seq: 2 }));
assert_eq!(bb.pull::<Ping>().unwrap(), None);      // drained

Implementations§

Source§

impl BitBuf

Source

pub fn new() -> Self

An empty auto-growing buffer (msb/big order for the Source path).

Source

pub fn with_capacity(cap: usize) -> Self

An empty auto-growing buffer with room for cap bytes before reallocating. Like new but pre-reserved; it still grows past cap on demand (use bounded for a hard cap).

Source

pub fn bounded(cap: usize) -> Self

An empty bounded buffer: it allocates cap bytes once and never reallocates on its own. try_push refuses bytes that would exceed cap (reclaiming consumed bytes first), and grow is the only thing that allocates again — so a real-time / no_std caller can guarantee a fixed footprint.

Source

pub fn with_layout(self, layout: Layout) -> Self

Set the byte/bit order used by the Source impl (the decode(&mut bitbuf) path). pull ignores this — it always bakes the message’s own LAYOUT.

Source

pub fn capacity(&self) -> Option<usize>

The buffer’s hard capacity in bytes for a bounded buffer, or None if it auto-grows.

Source

pub fn push(&mut self, bytes: &[u8])

Append freshly-received bytes to the back of the buffer, growing (reallocating) if needed. Consumed bytes are reclaimed in place first when that avoids a reallocation. For a hard, alloc-free cap, use bounded + try_push.

Source

pub fn try_push(&mut self, bytes: &[u8]) -> Result<(), CapacityError>

Append bytes without reallocating, reclaiming consumed bytes in place to make room.

§Errors

CapacityError if the bytes don’t fit a bounded buffer’s capacity (the live bytes plus the new bytes exceed cap). On an unbounded buffer it always succeeds (growing if needed), so prefer push there.

Source

pub fn grow(&mut self, additional: usize)

Grow a bounded buffer’s capacity by additional bytes (raising the cap and reserving the space — the one operation that reallocates a bounded buffer). On an unbounded buffer it just reserves.

Source

pub fn bit_len(&self) -> usize

The number of unconsumed bits currently buffered.

Source

pub fn is_empty(&self) -> bool

Whether no unconsumed bits remain.

Source

pub fn clear(&mut self)

Drop all buffered bytes and reset the cursor (keeps the allocation and any bound).

Source

pub fn compact(&mut self)

Physically reclaim the fully-consumed whole bytes now (drop everything before the cursor’s byte), keeping any partial trailing byte. pull defers this; call it yourself when consuming via the Source path (decode(&mut bitbuf)) to bound the buffer.

Source

pub fn pull<T: BitDecode + BitEncode>(&mut self) -> Result<Option<T>, BitError>

Decode the next complete message off the front, advancing past the bytes it consumed.

Returns Ok(None) when the buffer doesn’t yet hold a whole message — push more bytes and call again; the cursor is left untouched, so the retry is free. A malformed message is an Err. The byte/bit order is taken from T’s LAYOUT, so it decodes little/lsb messages correctly regardless of with_layout.

Consumed bytes are not drained here — they are reclaimed in place by the next push/try_push (or an explicit compact), so a steady push/pull loop reuses the same allocation without per-message memmoves.

§Errors

A codec BitError for a malformed message.

Trait Implementations§

Source§

impl Clone for BitBuf

Source§

fn clone(&self) -> BitBuf

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for BitBuf

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for BitBuf

Source§

fn default() -> BitBuf

Returns the “default value” for a type. Read more
Source§

impl SeekSource for BitBuf

Source§

impl Source for BitBuf

Source§

fn read_bits(&mut self, n: u32) -> Result<u128, BitError>

Reads n (<= 128) bits into the low bits of a u128, in the source’s bit order (MSB-first by default). Read more
Source§

fn bit_pos(&self) -> usize

The current absolute bit offset (for position-aware errors).
Source§

fn byte_order(&self) -> ByteOrder

The byte order applied to a byte-multiple value (default big-endian).
Source§

fn bit_order(&self) -> BitOrder

The bit order this source reads in (default MSB-first). Paired with byte_order to decide whether a byte-multiple value needs its bytes swapped — each bit order has a natural byte layout (big-endian under MSB, little-endian under LSB), and only the opposite declaration swaps.
Source§

fn seek_to_bit(&mut self, pos: usize) -> Result<(), BitError>

Moves the cursor to absolute bit pos. The default — for a forward-only source — fails with ErrorKind::NotSeekable; seekable sources (the slice BitReader) override it. A SeekSource guarantees this works. Read more
Source§

fn read<T: Bits>(&mut self) -> Result<T, BitError>

Reads one Bits value of its declared width, applying the byte order. Read more
Source§

fn read_bytes(&mut self, n: usize) -> Result<Vec<u8>, BitError>

Reads n bytes into a fresh Vec (at any bit offset — the bytes need not be aligned). The bulk form of the per-byte read::<u8>() loop, for blob/payload reads in custom codecs and container formats. Read more
Source§

fn read_into(&mut self, buf: &mut [u8]) -> Result<(), BitError>

Fills buf with bytes from the source — the no-alloc dual of read_bytes, for fixed scratch buffers and tight no_std paths. Read more
Source§

fn as_read(&mut self) -> SourceReader<'_, Self>
where Self: Sized,

Available on crate feature std only.
Borrows this source as a std::io::Read over its bytes — for handing the cursor to std::io-based code from a #[br(parse_with = …)] (e.g. a decoder, or a Read-based parser). Reads 8 bits per byte; see SourceReader. Only with the std feature.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more