Skip to main content

Module codecs

Module codecs 

Source
Expand description

Ready-made field codecs for parse_with/write_with — LEB128 varints, NUL-terminated C strings, and length-prefixed strings.

Reference them by path from a #[bin] field instead of hand-rolling the read/write pair:

codecwire formfield typeattributes
leb1287-bit groups, high-bit continuationu8u128parse_with = bnb::codecs::leb128::parse, write_with = bnb::codecs::leb128::write
cstringbytes, 0x00 terminatorVec<u8> / Stringparse_with = bnb::codecs::cstring::parse (or parse_utf8), write_with = …::write (or write_utf8)
prefixedlength prefix, then UTF-8 bytesStringparse_with = bnb::codecs::prefixed::parse_string::<_, u16>, write_with = …::write_string::<_, u16>

Every codec follows the crate’s dual-use doctrine: parse rejects only the unrepresentable (an overflowing varint, invalid UTF-8 destined for a String) and write refuses only what could not round-trip (an embedded NUL in a C string, a length exceeding its prefix). Nothing here validates meaning — that stays with validate at construction.

The fn contract (what a hand-rolled codec must also satisfy): a parse fn is fn(&mut impl Source) -> Result<T, BitError>, a write fn is fn(&T, &mut impl Sink) -> Result<(), BitError> — see the guide::directives parse_with section for rolling your own.

Using the same codec on many fields? Wrap it once as a per-type newtype — #[bin(codec = bnb::codecs::leb128)] struct Varint(pub u64); — and use the type as a plain field everywhere (see the guide’s “Per-type codecs” section).

Naming note: this is not the codec module — that one (under the tokio feature) is the async Decoder/Encoder adapter for framed transports; this module is the library of ready-made field codecs.

Modules§

cstring
NUL-terminated C strings — bytes until (and consuming) a 0x00 terminator.
leb128
Unsigned LEB128 (varint) — 7 payload bits per byte, low group first, high bit set while more bytes follow. The wire format of protobuf varint, WebAssembly, DWARF.
prefixed
Length-prefixed UTF-8 strings — a CountPrefix integer counting the bytes, then that many bytes of UTF-8.