FAQ - Help and questions

How do I read text that is not valid UTF-8, such as Windows-1252 or UTF-16 files?

#strings#encodings#portingpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Rust strings are always valid UTF-8, so reading other data needs a decision. Use from_utf8 to detect bad bytes, from_utf8_lossy to replace them, or the encoding_rs crate to decode a known legacy encoding or UTF-16 with a byte order mark. Windows file names can also be invalid Unicode and need OsString.

Checked with rustc 1.93.0, encoding_rs 0.8.44, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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:

SituationTool
Should be UTF-8; bad data is an errorString::from_utf8(bytes); the error says where the first bad byte is
Should be UTF-8; bad data is tolerableString::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 markencoding_rs::Encoding::for_bom then decode
File names and environment values on WindowsOsString, 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:

src/main.rsrust
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());
}
text
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}b

Reading 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#

  1. 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.
  2. Read files as bytes (fs::read), then decode in one place, so the rest of the program only sees String.
  3. Decide per input what a decoding error means: reject the file, or replace and continue. Log the decision.
  4. For output, encode on the way out if the receiver needs a legacy encoding (encoding_rs can encode too); UTF-8 is the default everywhere else.
  5. Keep file names and paths as Path and OsString; convert to String only to display them.

Common mistakes#

  • Using from_utf8_lossy on 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 €.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet