pub fn decode(input: &[u8]) -> Result<&str, DecodeError<'_>>Expand description
Decode a byte slice as UTF-8, returning the valid prefix on error.
Unlike std::str::from_utf8(), this distinguishes between invalid and
incomplete byte sequences so that callers can request more input.
use utf8_zero::{decode, DecodeError};
// Fully valid input.
assert_eq!(decode(b"hello").unwrap(), "hello");
// Invalid byte — returns the valid prefix and the bad sequence.
match decode(b"hello\xC0world") {
Err(DecodeError::Invalid { valid_prefix, .. }) => {
assert_eq!(valid_prefix, "hello");
}
_ => unreachable!(),
}
// Input ends mid-codepoint — returns Incomplete so the caller can
// supply more bytes.
match decode(b"\xC3") {
Err(DecodeError::Incomplete { valid_prefix, incomplete_suffix }) => {
assert_eq!(valid_prefix, "");
assert_eq!(incomplete_suffix.buffer_len, 1);
}
_ => unreachable!(),
}