Skip to main content

Module cstring

Module cstring 

Source
Expand description

NUL-terminated C strings — bytes until (and consuming) a 0x00 terminator.

Two forms: raw bytes (parse/write over Vec<u8> — permissive, pairs with #[try_str] for display) and UTF-8 (parse_utf8/write_utf8 over String — decode errors on invalid UTF-8, which a String physically cannot hold). The terminator is excluded from the value; write appends it, and errors on an embedded NUL — the wire image would decode back truncated, so it cannot round-trip.

use bnb::bin;

#[bin(big)]
#[derive(Debug, PartialEq)]
struct Entry {
    id: u8,
    #[br(parse_with = bnb::codecs::cstring::parse)]
    #[bw(write_with = bnb::codecs::cstring::write)]
    #[try_str]
    name: Vec<u8>,
}

let e = Entry { id: 7, name: b"alpha".to_vec() };
let bytes = e.to_bytes().unwrap();
assert_eq!(bytes, [7, b'a', b'l', b'p', b'h', b'a', 0]);
assert_eq!(Entry::decode_exact(&bytes).unwrap(), e);

Functions§

parse
Reads bytes until a 0x00 terminator (consumed, excluded from the value). Permissive: any byte sequence is accepted.
parse_utf8
parse, then UTF-8-validates into a String.
write
Writes the bytes followed by the 0x00 terminator.
write_utf8
Writes the string’s UTF-8 bytes followed by the terminator (via [write], so an embedded '\0' is rejected the same way).