String::from_utf16 Strict Decode

Decode UTF-16 units with String::from_utf16, which rejects lone surrogates, and fall back to from_utf16_lossy when substitution is fine.

RustData Integrity

Code

rustsnippet
23 lines
fn main() {
    // BMP 内字符各占一个 u16
    let units: Vec<u16> = "hi 世界".encode_utf16().collect();
    println!("units: {}", units.len());

    // from_utf16:逐个校验代理对,返回 Result
    match String::from_utf16(&units) {
        Ok(text) => println!("decoded: {text}"),
        Err(err) => println!("bad input: {err}"),
    }

    // from_utf16_lossy:孤立代理替换成 U+FFFD,不返回错误
    let broken = [0x0041u16, 0xD800, 0x0042];
    println!("lossy: {:?}", String::from_utf16_lossy(&broken));

    // 严格版本对同一输入返回 Err,调用方自己决定怎么处理
    println!("strict ok: {}", String::from_utf16(&broken).is_ok());

    // 合法代理对(emoji)能通过严格校验,字符数少于码元数
    let emoji: Vec<u16> = "a😀b".encode_utf16().collect();
    let text = String::from_utf16(&emoji).unwrap();
    println!("emoji units {} chars {}", emoji.len(), text.chars().count());
}

How it works

String::from_utf16 Strict Decode reduces to the function main.

A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Caveats

  • The file brings in no use statements; strings and slices carry the whole example.

Using it

Signature: fn main()

The run is easy to follow: each result arrives behind a marker (units:, decoded:, bad input:).

Key statements

let units: Vec<u16> = "hi 世界".encode_utf16().collect();
let emoji: Vec<u16> = "a😀b".encode_utf16().collect();
let text = String::from_utf16(&emoji).unwrap();

Interactive Tools for This Topic

FAQ

What does String::from_utf16 Strict Decode print when run?
The script runs standalone; its 6 labeled outputs include `units:`, `decoded:`, `bad input:`.