Decode UTF-16 With char::decode_utf16

Decode UTF-16 code units with char::decode_utf16, merging surrogate pairs and reporting unpaired surrogates without panicking.

RustData Integrity

Code

rustsnippet
27 lines
fn main() {
    let text = "Rust 🚀 语言";
    // 包含 BMP 外字符的 UTF-16 码元序列
    let units: Vec<u16> = text.encode_utf16().collect();
    println!("code units: {} chars: {}", units.len(), text.chars().count());

    // decode_utf16 逐项返回 Result,代理对自动合并
    let decoded: String = char::decode_utf16(units.iter().copied())
        .map(|item| item.unwrap_or(char::REPLACEMENT_CHARACTER))
        .collect();
    println!("decoded: {decoded}");
    println!("roundtrip: {}", decoded == text);

    // 孤立高代理会返回 Err,而不是 panic
    let broken = vec![0xD800u16, 0x0041, 0x0042];
    for item in char::decode_utf16(broken) {
        match item {
            Ok(ch) => println!("ok: {ch}"),
            Err(e) => println!("lone surrogate at {}", e.unpaired_surrogate()),
        }
    }

    // 合法代理对返回单个字符
    let pair = [0xD83D, 0xDE80];
    let result: Vec<char> = char::decode_utf16(pair).filter_map(Result::ok).collect();
    println!("pair -> {:?}", result);
}

How the snippet works

Decode UTF-16 With char::decode_utf16 is built around the function main.

Repetition is confined to for item in char::decode_utf16(broken) — the rest of the file is straight-line. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Applying it

Each run prints the 6 labeled blocks code units:, decoded:, roundtrip:, ok:, lone surrogate at, pair -> in source order.

Statements that matter

.map(|item| item.unwrap_or(char::REPLACEMENT_CHARACTER))
.collect();
let result: Vec<char> = char::decode_utf16(pair).filter_map(Result::ok).collect();
let units: Vec<u16> = text.encode_utf16().collect();

Interactive Tools for This Topic

FAQ

What does Decode UTF-16 With char::decode_utf16 print when run?
Execute the whole file; each printed line is prefixed with a label like `code units:`, `decoded:`, `roundtrip:`.