Function std::char::decode_utf161.9.0[][src]

pub fn decode_utf16<I>(iter: I) -> DecodeUtf16<<I as IntoIterator>::IntoIter>
Notable traits for DecodeUtf16<I>
impl<I> Iterator for DecodeUtf16<I> where
    I: Iterator<Item = u16>, 
type Item = Result<char, DecodeUtf16Error>;
where
    I: IntoIterator<Item = u16>, 
Expand description

iter 中的 UTF-16 编码的代码点上创建一个迭代器,将不成对的代理返回为 Errs。

Examples

基本用法:

use std::char::decode_utf16;

// 𝄞mus<invalid>ic<invalid>
let v = [
    0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
];

assert_eq!(
    decode_utf16(v.iter().cloned())
        .map(|r| r.map_err(|e| e.unpaired_surrogate()))
        .collect::<Vec<_>>(),
    vec![
        Ok('𝄞'),
        Ok('m'), Ok('u'), Ok('s'),
        Err(0xDD1E),
        Ok('i'), Ok('c'),
        Err(0xD834)
    ]
);
Run

通过用替换字符替换 Err 结果,可以获得有损解码器:

use std::char::{decode_utf16, REPLACEMENT_CHARACTER};

// 𝄞mus<invalid>ic<invalid>
let v = [
    0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
];

assert_eq!(
    decode_utf16(v.iter().cloned())
       .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
       .collect::<String>(),
    "𝄞mus�ic�"
);
Run