Sub topic 12
Handling invalid UTF-8
This chapter assumes you know that String and &str always hold valid UTF-8, that you can use Result and match, and that you have read the earlier chapters on creating strings and slicing on byte offsets. Here you will see where invalid bytes come from, how to detect them, and which recovery strategy to choose.
Why invalid UTF-8 shows up
The type system guarantees that a str is valid UTF-8. Code can slice it, call chars() on it, and pass it around without re-checking. That guarantee has to be enforced at the boundary where untrusted bytes become text. Bytes enter a program from many places, and none of them promise UTF-8:
- Files written by other programs, or in legacy encodings such as Latin-1 or Shift-JIS.
- Network sockets and HTTP bodies with a wrong or missing charset.
- Binary formats with a text field that was truncated or corrupted.
- Chunked reads that cut a multi-byte character in half.
Rust does not let you build a String from such bytes without a check. The standard library gives you three families of tools: validate and fail, validate and repair, or skip validation and take responsibility yourself.
Validating with from_utf8
String::from_utf8 takes ownership of a Vec<u8> and returns Result<String, FromUtf8Error>. On success it reuses the same heap buffer, so no copy happens.
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 bytes = e.into_bytes();
println!("recovered {} bytes", bytes.len());
}
}
}The error does not throw your data away. FromUtf8Error::into_bytes hands the original Vec<u8> back, so you can try a different decoding. utf8_error() gives you the inner Utf8Error, which describes where and how validation failed.
If you only have a borrowed slice, use std::str::from_utf8. It returns Result<&str, Utf8Error> and allocates nothing. The &str points into the original bytes.
use std::str;
fn main() {
let data: &[u8] = b"caf\xc3\xa9";
let s = str::from_utf8(data).unwrap();
println!("{s} {}", s.len());
}This prints café 5. The \xc3\xa9 escapes are the two UTF-8 bytes of é.
Reading the Utf8Error
Utf8Error has two methods that matter in practice.
| Method | Returns | Meaning |
|---|---|---|
| `valid_up_to()` | `usize` | Number of leading bytes that are valid UTF-8. |
| `error_len()` | `Option<usize>` | `Some(n)`: an invalid sequence of `n` bytes starts at `valid_up_to()`. `None`: the input ended unexpectedly in the middle of a character. |
Everything before valid_up_to() is guaranteed valid. That lets you salvage the good prefix without unsafe:
fn main() {
let bytes = b"abc\xffdef";
match std::str::from_utf8(bytes) {
Ok(s) => println!("{s}"),
Err(e) => {
let good = e.valid_up_to();
let prefix = std::str::from_utf8(&bytes[..good]).unwrap();
println!("prefix: {prefix}");
println!("error_len: {:?}", e.error_len());
}
}
}The output is prefix: abc and error_len: Some(1). The unwrap cannot fail because the standard library already proved those bytes valid. The second validation is a cheap re-scan of a short prefix.
The None case is the one people miss. A buffer ending in b"ab\xe2\x82" holds the first two bytes of the three-byte character €. It is not necessarily corrupt, because the last byte may arrive in the next read.
Repairing with from_utf8_lossy
When you would rather have approximate text than an error, use String::from_utf8_lossy. It takes &[u8] and returns a Cow<str>. Each invalid sequence is replaced by the replacement character U+FFFD (�).
use std::borrow::Cow;
fn main() {
let bytes = b"ok\xff\xfeend";
let text = String::from_utf8_lossy(bytes);
println!("{text}");
println!("{}", text.chars().filter(|&c| c == '\u{FFFD}').count());
let clean = String::from_utf8_lossy(b"all fine");
println!("{}", matches!(clean, Cow::Borrowed(_)));
}The first line prints ok��end, and the count is 2 because 0xff and 0xfe are two separate invalid bytes. The last line prints true: valid input comes back as Cow::Borrowed, so the happy path allocates nothing. Call .into_owned() if you need a String.
The replacement follows the "maximal subpart" rule from the Unicode standard. A truncated three-byte sequence such as \xe2\x82 followed by a yields one �, not two. Do not assume one bad byte equals one replacement character.
Reading files that may not be UTF-8
fs::read_to_string and Read::read_to_string fail with an io::Error whose kind is InvalidData when the content is not valid UTF-8. Reading the bytes first gives you the choice.
use std::{env, fs, io};
fn main() -> io::Result<()> {
let path = env::temp_dir().join("invalid_utf8_demo.txt");
fs::write(&path, b"line one\xff\n")?;
match fs::read_to_string(&path) {
Ok(text) => println!("{text}"),
Err(e) => println!("read_to_string failed: {:?}", e.kind()),
}
let bytes = fs::read(&path)?;
let text = String::from_utf8_lossy(&bytes);
println!("{}", text.trim_end());
fs::remove_file(&path)?;
Ok(())
}The program prints read_to_string failed: InvalidData, then line one�. Note that BufRead::lines() also yields an InvalidData error for any line that is not valid UTF-8. If you process log files of unknown origin, read with read_until(b'\n', &mut buf) or split(b'\n') and decode each line yourself.
Decoding streams and chunk boundaries
A fixed-size read can end in the middle of a character. Decoding each chunk independently with from_utf8_lossy would turn that valid character into one or two replacement characters. The fix is to keep the incomplete tail and prepend it to the next chunk. error_len() tells you which case you are in.
fn decode_chunks(chunks: &[&[u8]]) -> String {
let mut out = String::new();
let mut pending: Vec<u8> = Vec::new();
for chunk in chunks {
pending.extend_from_slice(chunk);
loop {
match std::str::from_utf8(&pending) {
Ok(s) => {
out.push_str(s);
pending.clear();
break;
}
Err(e) => {
let good = e.valid_up_to();
out.push_str(std::str::from_utf8(&pending[..good]).unwrap());
match e.error_len() {
Some(n) => {
out.push('\u{FFFD}');
pending.drain(..good + n);
}
None => {
pending.drain(..good);
break;
}
}
}
}
}
}
if !pending.is_empty() {
out.push('\u{FFFD}');
}
out
}
fn main() {
let split_euro: [&[u8]; 2] = [b"ab\xe2\x82", b"\xacc"];
println!("{}", decode_chunks(&split_euro));
let with_garbage: [&[u8]; 2] = [b"x\xffy", b"z\xe2"];
println!("{}", decode_chunks(&with_garbage));
}The first call prints ab€c, because the euro sign is reassembled across the chunk boundary. The second prints x�yz�. The 0xff is a definite error (Some(1)), and the trailing 0xe2 is still incomplete when the stream ends, so it becomes one replacement character.
The unsafe escape hatch
String::from_utf8_unchecked and str::from_utf8_unchecked skip validation. If the bytes are not valid UTF-8, you have undefined behavior. Methods such as chars() and slicing assume validity and may read out of bounds or produce nonsense. Use these only when you have already proved validity by other means, and a profiler shows the check is a real cost. Validation is a fast linear scan, so this is rarely true.
Choosing a strategy
| Situation | Tool | Trade-off |
|---|---|---|
| Input must be valid, such as a config file or JSON | `from_utf8`, propagate the error | Strict, and you get precise error positions. |
| Display only, such as logging unknown bytes | `from_utf8_lossy` | Never fails, but loses data. |
| Known legacy encoding | A decoding crate such as `encoding_rs` | Correct text, but an extra dependency. |
| Data is not really text, such as file names or binary protocols | Keep `Vec<u8>`, `OsString`, or `Path` | No loss, but no `str` methods. |
| Streaming input | Buffer the tail using `error_len()` | More code, but correct at chunk boundaries. |
Common mistakes:
- Calling
unwrap()onfrom_utf8for data from outside your program. One bad byte then crashes the process. - Using
from_utf8_lossyon data you later need to match byte-for-byte. - Treating
error_len() == Noneas corruption when more input may follow. - Converting file paths through
String. Operating system paths need not be UTF-8, which the last chapter in this tutorial covers withOsStringandPath.
Exercise
A network reader fills a 4-byte buffer and calls String::from_utf8_lossy on each read separately. The stream contains the text "a€b" (the euro sign € is the three bytes E2 82 AC). The first read returns 61 E2 82 AC, and the second returns 62. A second stream has the same text, but the first read returns only 61 E2 82 and the second returns AC 62. What does the per-read lossy approach produce for each stream, and how would you fix the second case?
Show answer
The first stream decodes correctly as "a€" followed by "b", because each chunk is valid on its own. In the second stream the first read ends mid-character, so from_utf8_lossy turns E2 82 into one �. The second read starts with a lone continuation byte AC, which becomes another �, so the result is "a��b" instead of "a€b". To fix it, decode with std::str::from_utf8 on a pending buffer. When the error has error_len() == None, keep the bytes after valid_up_to() and prepend them to the next read, as decode_chunks does. Replace with � only for Some(n) errors or when the stream ends with leftover bytes.