ring/arithmetic/
constant.rs

1use crate::limb::Limb;
2
3const 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
12pub const fn limbs_from_hex<const LIMBS: usize>(hex: &str) -> [Limb; LIMBS] {
13    let hex = hex.as_bytes();
14    let mut limbs = [0; LIMBS];
15    let limb_nibbles = core::mem::size_of::<Limb>() * 2;
16    let mut i = 0;
17
18    while i < hex.len() {
19        let char = hex[hex.len() - 1 - i];
20        let val = parse_digit(char);
21        limbs[i / limb_nibbles] |= (val as Limb) << ((i % limb_nibbles) * 4);
22        i += 1;
23    }
24
25    limbs
26}