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.
Code
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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.