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.

RustSecurity Boundaries

Code

rustsnippet
25 lines
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

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:`.