Answer#
Python, Java and C# decode text when you open a file with an encoding name, and each has a default that varies by platform. Rust's String and &str guarantee UTF-8, so fs::read_to_string returns an error for a file that is not. When you port code that reads old files, find out which encoding the data really has, then pick the tool:
| Situation | Tool |
|---|---|
| Should be UTF-8; bad data is an error | String::from_utf8(bytes); the error says where the first bad byte is |
| Should be UTF-8; bad data is tolerable | String::from_utf8_lossy(&bytes) replaces bad bytes with U+FFFD |
| A known legacy encoding (Windows-1252, Shift JIS, ...) | the encoding_rs crate: WINDOWS_1252.decode(bytes) |
| UTF-16 with a byte order mark | encoding_rs::Encoding::for_bom then decode |
| File names and environment values on Windows | OsString, which may hold unpaired surrogates |
This program (rustc 1.93.0, encoding_rs 0.8.44, Windows only because of the last block) tries each:
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
fn main() {
// bytes that are not UTF-8: "café" in Windows-1252 ends with 0xE9
let bytes = b"caf\xe9 \x80 ok";
match String::from_utf8(bytes.to_vec()) {
Ok(s) => println!("valid: {s}"),
Err(e) => println!("not UTF-8; valid up to byte {}", e.utf8_error().valid_up_to()),
}
println!("{}", String::from_utf8_lossy(bytes).escape_default());
let (text, _, had_errors) = encoding_rs::WINDOWS_1252.decode(bytes);
println!("windows-1252: {} (errors: {had_errors})", text.escape_default());
// UTF-16 with a byte order mark, as a Windows tool may write it
let utf16le: Vec<u8> = [0xFF, 0xFE].into_iter().chain("naïve".encode_utf16().flat_map(|u| u.to_le_bytes())).collect();
let (text, enc, _) = encoding_rs::Encoding::for_bom(&utf16le).map(|(e, n)| { let (t, _) = e.decode_without_bom_handling(&utf16le[n..]); (t.into_owned(), e, 0) }).unwrap();
println!("{} detected {}", text, enc.name());
// a Windows file name can contain an unpaired surrogate, which is not valid Unicode
let name = OsString::from_wide(&[0x61, 0xD800, 0x62]);
println!("{:?} {}", name.to_str(), name.to_string_lossy().escape_default());
}not UTF-8; valid up to byte 3
caf\u{fffd} \u{fffd} ok
windows-1252: caf\u{e9} \u{20ac} ok (errors: false)
naïve detected UTF-16LE
None a\u{fffd}bReading it: the strict decoder stops at byte 3, the first 0xE9. The lossy decoder keeps going and replaces both bad bytes. Decoding as Windows-1252 gives the intended é, and turns the byte 0x80 into € (in that encoding as encoding_rs defines it), which shows that the right answer depends on knowing the encoding. The BOM identified the UTF-16 data. The unpaired surrogate in the file name is valid for Windows but cannot be a Rust &str, so to_str is None and the lossy conversion substitutes U+FFFD.
How to do it#
- Find out the encoding of each input from its source (a specification, a header, a database setting). Do not guess from content when you can ask.
- Read files as bytes (
fs::read), then decode in one place, so the rest of the program only seesString. - Decide per input what a decoding error means: reject the file, or replace and continue. Log the decision.
- For output, encode on the way out if the receiver needs a legacy encoding (
encoding_rscan encode too); UTF-8 is the default everywhere else. - Keep file names and paths as
PathandOsString; convert toStringonly to display them.
Common mistakes#
- Using
from_utf8_lossyon data you will write back. The replacement changes the data permanently. - Assuming the console and the file use the same encoding. The Windows console has its own code page, which is a separate issue from the file's encoding.
- Treating "Latin-1" and "Windows-1252" as the same. They differ in the range 0x80 to 0x9F, where the second has printable characters such as
€.
Related questions#
Does read_to_string strip a BOM?#
No. A UTF-8 file with a BOM keeps U+FEFF at the start of the string. Strip it explicitly if you expect one.
Do I need encoding_rs for UTF-16?#
Not for simple cases: char::decode_utf16 in the standard library decodes UTF-16 units. The crate also detects the byte order mark and handles legacy encodings.
Sources#
encoding_rsdocumentation: https://docs.rs/encoding_rsString::from_utf8_lossy: https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8_lossystd::os::windows::ffi::OsStringExt: https://doc.rust-lang.org/std/os/windows/ffi/trait.OsStringExt.html