Skip to content

String::from_utf16be_lossy

String methods · Strings

Level: reference · for working programmers

One line: from_utf16be that cannot fail — bad sequences become U+FFFD.

pub fn from_utf16be_lossy(v: &[u8]) -> String

Stable since 1.98.0.

Same big-endian reading, no Result. Unpaired surrogates and a trailing odd byte are both replaced.

The endianness caveat is unchanged and is the more dangerous one: reading with the wrong order produces neither an error nor a replacement character, just different text.

Example

string_from_utf16be_lossy.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let be = [0x00, 0x68, 0x00, 0x69];
    println!("{:?}", String::from_utf16be_lossy(&be));

    // Truncation is replaced rather than refused.
    println!("{:?}", String::from_utf16be_lossy(&[0x00, 0x68, 0x00]));

    // The wrong endianness is silent -- no error, no replacement char.
    let wrong = String::from_utf16le_lossy(&be);
    println!("{:?} contains no replacement char: {}",
             wrong, !wrong.contains('\u{FFFD}'));
}

Verified output of string_from_utf16be_lossy.rs — regenerated by tools/run_examples.py, never hand-typed.

"hi"
"h�"
"栀椀" contains no replacement char: true

See also

String::from_utf16be_lossy in the standard library ↗

Po polsku

Wersja bez Result: i niesparowany surogat, i zwisający nieparzysty bajt zamieniają się w , więc [0x00, 0x68, 0x00] daje "h�" zamiast błędu. Kusi wtedy, żeby uznać obecność za sygnał „coś poszło nie tak” — i przed tym właśnie ta strona ostrzega mocniej niż przed samą stratnością: przy złej kolejności bajtów nie pojawi się ani błąd, ani żaden znak zastępczy, tylko inny, pozornie zupełnie czysty tekst ("栀椀" zamiast "hi"). Brak niczego więc nie dowodzi; kolejność bajtów trzeba znać z formatu, a nie wnioskować z wyniku.

Szukaj po polsku: stratne dekodowanie · znak zastępczy · kolejność bajtów big-endian · rust from_utf16be_lossy · rust utf16 wrong endianness silent