← 中文资源

简体中文版本

用 char::from_u32 拒绝代理区码点

char::from_u32 在构造 char 前校验码点:代理区与超出 U+10FFFF 的值返回 None,不可信输入无法混进合法字符串。

阅读英文原文

实现说明

用 char::from_u32 拒绝代理区码点可以归结为函数 main。 for code in candidates 反复执行,循环体之外没有别的重复。通过 match 做模式匹配,值的每种形态都必须被处理。

使用要点

  • 直接运行文件,输出会带上标签,比如 U+、0x110000 is beyond the Unicode range、built from scalar:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「用 char::from_u32 拒绝代理区码点」会打印什么?

运行文件本身,U+、0x110000 is beyond the Unicode range、built from scalar: 这些前缀各对应一段演示逻辑。

核心语句

match char::from_u32(code) {
    Some(c) => println!("U+{code:04X} accepted: {c}"),
    // 0xD800..=0xDFFF is the surrogate range, not valid scalar values
    None => println!("U+{code:04X} rejected"),
}

代码示例

fn main() {
    // a code point from untrusted input: validate first, then decide whether to build a char
    let candidates: [u32; 4] = [0x1F600, 0x00E9, 0xD800, 0xDFFF];

    for code in candidates {
        match char::from_u32(code) {
            Some(c) => println!("U+{code:04X} accepted: {c}"),
            // 0xD800..=0xDFFF is the surrogate range, not valid scalar values
            None => println!("U+{code:04X} rejected"),
        }
    }

    // out of range: nothing exists above U+10FFFF
    if char::from_u32(0x110000).is_none() {
        println!("0x110000 is beyond the Unicode range");
    }

    // str never contains surrogates: from_u32 is the safe entry point for building a char from a number
    let check = char::from_u32(0x2713).expect("check mark is a valid scalar");
    println!("built from scalar: {check}");
}