Reject Surrogates With char::from_u32

Validate untrusted code points with char::from_u32 before building chars: the surrogate range and values past U+10FFFF come back None instead of panicking.

RustSecurity Boundaries

Code

rustsnippet
21 lines
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}");
}

How it works

Reject Surrogates With char::from_u32 reduces to the function main.

Repetition is confined to for code in candidates — the rest of the file is straight-line. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Using it

The demo output is labeled (U+, 0x110000 is beyond the Unicode range, built from scalar:), so every printed line maps back to its originating operation.

Key statements

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"),
}

Interactive Tools for This Topic

FAQ

What does Reject Surrogates With char::from_u32 print when run?
Invoke the file as-is — the `U+`, `0x110000 is beyond the Unicode range`, `built from scalar:` prefixes identify which step printed each line.