Expand description
Length-prefixed UTF-8 strings — a CountPrefix integer
counting the bytes, then that many bytes of UTF-8.
Generic over the prefix type: any type the
#[brw(count_prefix = …)] directive accepts, including the
arbitrary-width uNs (a u12 prefix is 12 bits on the wire). Pick it with a
turbofish — the cursor parameter stays inferred:
use bnb::bin;
#[bin(big)]
#[derive(Debug, PartialEq)]
struct Label {
#[br(parse_with = bnb::codecs::prefixed::parse_string::<_, u16>)]
#[bw(write_with = bnb::codecs::prefixed::write_string::<_, u16>)]
title: String,
}
let l = Label { title: "hi".into() };
let bytes = l.to_bytes().unwrap();
assert_eq!(bytes, [0x00, 0x02, b'h', b'i']); // u16 byte length, then UTF-8
assert_eq!(Label::decode_exact(&bytes).unwrap(), l);For length-prefixed bytes (Vec<u8>), use the
#[brw(count_prefix = …)] directive instead — same wire form,
one attribute. Write is checked: a string longer than the prefix’s range is a
BitError, never a wrapped length. (On 32-bit targets a u64/
u128 prefix narrows through usize on read — see
CountPrefix::to_count.)
Functions§
- parse_
string - Reads a
Pbyte-length prefix, then that many bytes, UTF-8-validated. - write_
string - Writes the
Pbyte-length prefix, then the string’s UTF-8 bytes.