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.
Code
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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text ReverserReverse text by characters, words, or lines, counting Unicode code points so emoji stay intact.
FAQ
- What does String::from_utf16 Strict Decode print when run?
- The script runs standalone; its 6 labeled outputs include `units:`, `decoded:`, `bad input:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.