1 | use crate::limb::Limb; |
2 | |
3 | const fn parse_digit(d: u8) -> u8 { |
4 | match d.to_ascii_lowercase() { |
5 | b'0' ..=b'9' => d - b'0' , |
6 | b'a' ..=b'f' => d - b'a' + 10, |
7 | _ => panic!(), |
8 | } |
9 | } |
10 | |
11 | // TODO: this would be nicer as a trait, but currently traits don't support const functions |
12 | pub const fn limbs_from_hex<const LIMBS: usize>(hex: &str) -> [Limb; LIMBS] { |
13 | let hex: &[u8] = hex.as_bytes(); |
14 | let mut limbs: [u64; LIMBS] = [0; LIMBS]; |
15 | let limb_nibbles: usize = core::mem::size_of::<Limb>() * 2; |
16 | let mut i: usize = 0; |
17 | |
18 | while i < hex.len() { |
19 | let char: u8 = hex[hex.len() - 1 - i]; |
20 | let val: u8 = parse_digit(char); |
21 | limbs[i / limb_nibbles] |= (val as Limb) << ((i % limb_nibbles) * 4); |
22 | i += 1; |
23 | } |
24 | |
25 | limbs |
26 | } |
27 | |