Skip to content

String::from_utf16_lossy

String methods · Strings

Level: reference · for working programmers

One line: from_utf16 that cannot fail — unpaired surrogates become U+FFFD.

pub fn from_utf16_lossy(v: &[u16]) -> String

Stable since 1.0.0.

Same decoding, no Result. Every unpaired surrogate is replaced by and decoding continues.

Unlike from_utf8_lossy, this returns a plain String rather than a Cow — a UTF-16 input always has to be re-encoded into UTF-8, so there is nothing to borrow and an allocation happens either way.

Use it for display of text from a system that permits ill-formed UTF-16, where showing something beats showing an error.

Example

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

fn main() {
    let units: Vec<u16> = "hi 👋".encode_utf16().collect();
    println!("{:?}", String::from_utf16_lossy(&units));

    // Unpaired surrogates are replaced rather than rejected.
    let broken = [0x0068, 0xD83D, 0x0069];
    println!("{:?}", String::from_utf16(&broken).is_err());
    println!("{:?}", String::from_utf16_lossy(&broken));

    // Always a String, never a Cow -- re-encoding is unavoidable.
    let clean: String = String::from_utf16_lossy(&units);
    println!("{} bytes of UTF-8 from {} UTF-16 units", clean.len(), units.len());
}

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

"hi 👋"
true
"h�i"
7 bytes of UTF-8 from 5 UTF-16 units

See also

String::from_utf16_lossy in the standard library ↗

Po polsku

To samo dekodowanie, tylko bez Result: każdy niesparowany surogat zamienia się w znak zastępczy (U+FFFD) i dekodowanie idzie dalej, więc [0x0068, 0xD83D, 0x0069] daje "h�i" zamiast błędu. Różnica wobec from_utf8_lossy jest drobna, ale warto ją zauważyć — tam wynikiem jest Cow, który przy poprawnym wejściu niczego nie kopiuje, a tutaj zawsze dostajesz zwykły String, bo przejście z UTF-16 na UTF-8 i tak wymaga przekodowania całości i nie ma czego pożyczyć. Wybieraj tę wersję do wyświetlania tekstu z systemów tolerujących zepsuty UTF-16, gdzie pokazanie czegokolwiek bije komunikat o błędzie; jeśli dane mają jechać dalej, bierz from_utf16, bo tam uszkodzenie widać, zamiast być zamiecionym pod .

Szukaj po polsku: znak zastępczy U+FFFD · zepsuty UTF-16 · rust from_utf16_lossy · rust replacement character