ASCII Hex Digit Validation
Validate characters with is_ascii_hexdigit to accept only 0-9 a-f A-F, then decode each accepted char through to_digit with radix 16.
Code
fn parse_hex_token(token: &str) -> Option<Vec<u8>> {
// 逐字符校验:只放行 0-9 a-f A-F,其余一律拒绝
if !token.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
// 校验通过后再解码:to_digit(16) 在已验证字符上不会失败
let mut bytes = Vec::with_capacity(token.len() / 2);
let digits: Vec<u8> = token
.chars()
.map(|c| c.to_digit(16).expect("validated hex digit") as u8)
.collect();
for pair in digits.chunks(2) {
let high = pair[0] * 16;
let low = pair.get(1).copied().unwrap_or(0);
bytes.push(high + low);
}
Some(bytes)
}
fn main() {
println!("ok: {:?}", parse_hex_token("DEADBEEF"));
println!("odd: {:?}", parse_hex_token("ABC"));
println!("bad: {:?}", parse_hex_token("0x12"));
println!("uni: {:?}", parse_hex_token("01")); // 全角零一
}Inside the snippet
ASCII Hex Digit Validation is built around the functions parse_hex_token and main.
Repetition is confined to for pair in digits.chunks(2) — the rest of the file is straight-line.
Using it
Signature: fn parse_hex_token(token: &str) -> Option<Vec<u8>>
The demo output is labeled (ok:, odd:, bad:), so every printed line maps back to its originating operation.
The sequence parse_hex_token lives in main; running the file triggers it.
Key statements
let low = pair.get(1).copied().unwrap_or(0);
.map(|c| c.to_digit(16).expect("validated hex digit") as u8)
.collect();
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- What does ASCII Hex Digit Validation print when run?
- Run it as a complete program — the output lines carry labels such as `ok:`, `odd:`, `bad:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.