Skip to content

Instantly share code, notes, and snippets.

@nerodono
Created April 22, 2023 12:43
Show Gist options
  • Save nerodono/3a1ec0ea90efcc7a7a225afaa9d39b11 to your computer and use it in GitHub Desktop.
Save nerodono/3a1ec0ea90efcc7a7a225afaa9d39b11 to your computer and use it in GitHub Desktop.
pub(crate) fn parse_hex(buffer: &[u8]) -> FeedingResult<usize> {
let mut output = 0;
const fn naive_upper(v: u8) -> u8 {
v & !(0x20 * (v >= b'A') as u8)
}
// !{char} = incorrect
const TABLE: &[usize] = &[
0xF, 0xE, 0xD, 0xC, 0xB, 0xA, 0, // !@
0, // !?
0, // !>
0, // !=
0, // !<
0, // !;
0, // !:
9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
];
let buf_len = buffer.len();
for (idx, chr) in buffer.iter().copied().enumerate() {
let shl = 4 * (buf_len - idx - 1);
// branch can be elided if known that input is correct
if !matches!(chr, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z') {
return Err(FeedingError::Malformed);
}
output += TABLE[(b'F' - naive_upper(chr)) as usize] << shl;
}
Ok(output)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment