Created
March 9, 2018 08:50
-
-
Save goldsborough/a7d0d20807d9428f4e8f66e15f16b077 to your computer and use it in GitHub Desktop.
hex parser in rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
macro_rules! hex { | |
(0) => {48}; | |
(9) => {57}; | |
(A) => {65}; | |
(F) => {70}; | |
(a) => {97}; | |
(z) => {102}; | |
(0..9) => {48...57}; | |
(A..F) => {65...70}; | |
(a..f) => {97...102}; | |
} | |
pub fn parse_hex_address(string: &str) -> Option<usize> { | |
debug_assert!(!string.starts_with("0x")); | |
let mut value: usize = 0; | |
let mut base: usize = 1; | |
for byte in string.bytes().rev() { | |
let digit = match byte { | |
hex!(0..9) => byte - hex!(0), | |
hex!(A..F) => 10 + (byte - hex!(A)), | |
hex!(a..f) => 10 + (byte - hex!(a)), | |
_ => return None, | |
}; | |
value += base * (digit as usize); | |
base *= 16; | |
} | |
Some(value) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment