String::from_utf16le_lossy¶
Level: reference · for working programmers
One line: from_utf16le that cannot fail — bad sequences become U+FFFD.
Stable since 1.98.0.
Same little-endian reading, no Result. Unpaired surrogates are replaced, and a trailing odd byte is replaced rather than rejected.
That second behaviour is the one to notice: a truncated stream yields text with a � at the end instead of an error, so this is the wrong choice when a partial read needs to be retried rather than displayed.
Example¶
string_from_utf16le_lossy.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let le = [0x68, 0x00, 0x69, 0x00];
println!("{:?}", String::from_utf16le_lossy(&le));
// A trailing odd byte is replaced, not rejected.
let truncated = [0x68, 0x00, 0x69];
println!("{:?}", String::from_utf16le(&truncated).is_err());
println!("{:?}", String::from_utf16le_lossy(&truncated));
// An unpaired surrogate, likewise.
let broken = [0x68, 0x00, 0x3D, 0xD8];
println!("{:?}", String::from_utf16le_lossy(&broken));
}
Verified output of string_from_utf16le_lossy.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
String::from_utf16le— failing instead of replacingString::from_utf16be_lossy— the other byte orderString::from_utf16_lossy— when you already haveu16s
String::from_utf16le_lossy in the standard library ↗
Po polsku¶
Od from_utf16be_lossy różni się tylko kolejnością bajtów, ale jeden szczegół wart jest zapamiętania osobno: obcięty strumień jest tu łatany, a nie odrzucany. Widać to w wyjściu przykładu — [0x68, 0x00, 0x69] (nieparzysta liczba bajtów) i [0x68, 0x00, 0x3D, 0xD8] (niesparowany surogat) dają dokładnie ten sam wynik "h�", więc po samym łańcuchu znaków nie odróżnisz „dane są uszkodzone” od „doczytałem pół jednostki, bo skończył się bufor”. To dyskwalifikuje tę funkcję przy czytaniu strumienia po kawałku: jeśli niepełny odczyt trzeba ponowić, a nie wyświetlić, weź from_utf16le i obsłuż Err.
Szukaj po polsku: obcięty strumień · stratne dekodowanie UTF-16 · czytanie po kawałku · rust from_utf16le_lossy · rust partial read utf16