Skip to content

Instantly share code, notes, and snippets.

@meetmangukiya
Created March 3, 2022 11:01
Show Gist options
  • Save meetmangukiya/4d7c4470c3e9e02a95459a1c63b41baf to your computer and use it in GitHub Desktop.
Save meetmangukiya/4d7c4470c3e9e02a95459a1c63b41baf to your computer and use it in GitHub Desktop.
`const` function for parsing a 20 byte string into an `Address`. Can be used to declare global variables to hold addresses.
pub const fn parse_hex_20b(input: &str) -> [u8; 20] {
let mut addr = [0; 20];
let mut i = 0usize;
let mut idx = 0usize;
let bytes = input.as_bytes();
loop {
let char1 = bytes[i];
let char2 = bytes[i + 1];
let mut buf = 0u8;
match char1 {
b'A'..=b'F' => buf |= char1 - b'A' + 10,
b'a'..=b'f' => buf |= char1 - b'a' + 10,
b'0'..=b'9' => buf |= char1 - b'0',
_ => panic!("invalid hex character"),
}
buf <<= 4;
match char2 {
b'A'..=b'F' => buf |= char2 - b'A' + 10,
b'a'..=b'f' => buf |= char2 - b'a' + 10,
b'0'..=b'9' => buf |= char2 - b'0',
_ => panic!("invalid hex character"),
}
i += 2;
addr[idx] = buf;
idx += 1;
if i == input.len() {
break;
}
}
addr
}
pub const fn parse_address(hex: &str) -> H160 {
let bytes = parse_hex_20b(hex);
H160(bytes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment