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.
Code
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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.