Lossy Utf8 Conversion For Byte Vectors

Decode byte vectors with from_utf8_lossy so invalid bytes become U+FFFD instead of panicking, against the strict from_utf8 that keeps the bytes in Err.

RustData Integrity

Code

rustsnippet
15 lines
fn main() {
    // 合法 UTF-8:原样转回 String
    let good = vec![104, 101, 108, 108, 111];
    println!("good: {}", String::from_utf8_lossy(&good));

    // 含非法字节:U+FFFD 替换符标记损坏位置,不 panic
    let broken = vec![b'o', b'k', 0xFF, b'!'];
    println!("broken: {}", String::from_utf8_lossy(&broken));

    // 对照 from_utf8:严格版本返回 Err,原始字节留在错误里
    match String::from_utf8(broken.clone()) {
        Ok(text) => println!("unexpected ok: {text}"),
        Err(err) => println!("strict err byte: {:?}", err.into_bytes()[2]),
    }
}

How it works

Lossy Utf8 Conversion For Byte Vectors comes down to the function main.

Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Putting it to use

Running the file prints labeled results such as good:, broken:, unexpected ok: — each operation’s effect is visible in the output.

Core lines

match String::from_utf8(broken.clone()) {
Ok(text) => println!("unexpected ok: {text}"),
Err(err) => println!("strict err byte: {:?}", err.into_bytes()[2]),
}

Interactive Tools for This Topic

FAQ

What does Lossy Utf8 Conversion For Byte Vectors print when run?
Invoke the file as-is — the `good:`, `broken:`, `unexpected ok:` prefixes identify which step printed each line.