Sub topic 12
Handling invalid UTF-8
This chapter assumes you know the difference between &str and String, that both always hold valid UTF-8, and how Result and match work.
Where invalid bytes come from
Safe Rust never lets you build a String or &str that holds invalid UTF-8. Text from outside your program has no such guarantee. Files, sockets, and old encodings such as Latin-1 can all produce bytes that are not valid UTF-8. These arrive as Vec<u8> or &[u8], and you must convert them explicitly. The conversion checks every byte and tells you if the data is bad.
Strict conversion with from_utf8
String::from_utf8 takes ownership of a Vec<u8>. It returns Ok(String) without copying if the bytes are valid. Otherwise it returns a FromUtf8Error.
fn main() {
let bytes = vec![b'h', b'i', 0xff, b'!'];
match String::from_utf8(bytes) {
Ok(s) => println!("valid: {s}"),
Err(e) => {
println!("error: {e}");
println!("valid up to: {}", e.utf8_error().valid_up_to());
let recovered = e.into_bytes();
println!("bytes kept: {}", recovered.len());
}
}
}The error does not throw your data away. into_bytes gives the original Vec<u8> back, and utf8_error() returns a Utf8Error that says where the problem is.
If you only need to read the text, use std::str::from_utf8. It borrows a &[u8] and returns a &str without allocating.
Locating the problem
Utf8Error has two methods:
valid_up_to()is the number of leading bytes that are valid UTF-8.error_len()isSome(n)whennbytes are definitely invalid. It isNonewhen the input ended in the middle of a character.
The None case matters when you read data in chunks. A multi-byte character can be split across two reads. That is a truncated sequence, not corruption.
use std::str;
fn main() {
// "é" is 0xC3 0xA9, but the second byte is missing.
let chunk = [b'a', 0xC3];
match str::from_utf8(&chunk) {
Ok(s) => println!("ok: {s}"),
Err(e) => {
let (good, rest) = chunk.split_at(e.valid_up_to());
let good = str::from_utf8(good).unwrap();
println!("good={good:?} rest={rest:?} error_len={:?}", e.error_len());
}
}
}This prints error_len=None. A streaming reader can keep rest and prepend it to the next chunk. The unwrap is safe because valid_up_to marks a prefix that was already checked.
Lossy conversion
When you would rather have approximate text than an error, use String::from_utf8_lossy. It replaces each invalid sequence with the replacement character U+FFFD (�).
fn main() {
let bytes = [b'h', b'i', 0xff, b'!'];
let text = String::from_utf8_lossy(&bytes);
println!("{text}");
}It returns a Cow<str>. If the input is valid, you get a borrowed &str with no allocation. If not, you get a new String with replacements. Call .into_owned() when you need a String in both cases.
Choosing an approach
Common mistakes
- Unwrapping on external input.
String::from_utf8(data).unwrap()panics on the first bad byte. Reserveunwrapfor data you built yourself. - Using
from_utf8_uncheckedto skip the check. It isunsafe. Invalid bytes in astrare undefined behavior, not just a logic bug. The check is fast, so skip it only after measuring. - Treating a truncated tail as an error. In streaming code, check
error_len()before rejecting the input.
Exercise
A socket delivers [0x68, 0x69, 0xE2, 0x82], which is the start of a three-byte character. You call std::str::from_utf8 on it. What do valid_up_to() and error_len() return, and what should a streaming reader do next?
Show answer
valid_up_to() returns 2, because "hi" is valid. error_len() returns None, because the input ends in the middle of a character. The reader should keep bytes [0xE2, 0x82] and prepend them to the next chunk before converting again. It should not report an error.