From Utf8 Errors Hand Back The Bytes
String::from_utf8 on failure returns the original Vec<u8> inside the error, so callers keep ownership of the data and can repair and retry it.
Code
fn main() {
// Build invalid UTF-8: 0xFF is not a legal lead byte for anything
let payload: Vec<u8> = vec![b'o', b'k', 0xFF, b'!'];
match String::from_utf8(payload) {
Ok(text) => println!("decoded: {text}"),
Err(err) => {
// The error carries validation facts: the first valid_up_to bytes are valid UTF-8
println!("valid up to {}", err.utf8_error().valid_up_to());
// into_bytes hands the original Vec<u8> back: ownership returns to the caller
let raw: Vec<u8> = err.into_bytes();
println!("invalid byte at {}", raw.iter().position(|b| !b.is_ascii()).unwrap());
// Fix the bad byte and retry with the same allocation
let repaired: Vec<u8> = raw.iter().map(|b| if *b < 0x80 { *b } else { b'?' }).collect();
let text = String::from_utf8(repaired).expect("all-ascii now");
println!("repaired: {text}");
}
}
}How the snippet works
From Utf8 Errors Hand Back The Bytes is built around the function main.
Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Applying it
The demo output is labeled (decoded:, valid up to, invalid byte at), so every printed line maps back to its originating operation.
Statements that matter
let repaired: Vec<u8> = raw.iter().map(|b| if *b < 0x80 { *b } else { b'?' }).collect();
Interactive Tools for This Topic
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does From Utf8 Errors Hand Back The Bytes print when run?
- The script runs standalone; its 4 labeled outputs include `decoded:`, `valid up to`, `invalid byte at`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.