Expand description
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.
Generic over the field’s integer width via [Varint]: the declared field type pins
the width, so the same parse/write pair serves u16 and u64 fields alike.
Decoding is bounded and overflow-checked — a value too large for the field or a
continuation run longer than the width allows is a clean BitError, never a panic
or a silent wrap. Non-minimal encodings (e.g. 0x80 0x00 for zero) are accepted:
permissive parse, canonical (minimal) write.
use bnb::bin;
#[bin(big)]
#[derive(Debug, PartialEq)]
struct Record {
#[br(parse_with = bnb::codecs::leb128::parse)]
#[bw(write_with = bnb::codecs::leb128::write)]
length: u32, // width inferred from the field type
#[br(parse_with = bnb::codecs::leb128::parse)]
#[bw(write_with = bnb::codecs::leb128::write)]
timestamp: u64,
}
let r = Record { length: 300, timestamp: 1 };
let bytes = r.to_bytes().unwrap();
assert_eq!(bytes, [0xAC, 0x02, 0x01]); // 300 = 0b10_0101100 → AC 02; 1 → 01
assert_eq!(Record::decode_exact(&bytes).unwrap(), r);Traits§
- Varint
- The integer widths readable/writable as LEB128 —
u8,u16,u32,u64,u128. Sealed: LEB128 is byte-granular, so the primitive widths are the whole set (auNfield wants the next wider primitive).