1pub struct Hex<T>(pub T);
2
3struct Iter<'a> {
4 s: &'a [u8],
5 i: usize,
6}
7
8impl<'a> Iter<'a> {
9 const fn new(s: &'a str) -> Self {
10 Self {
11 s: s.as_bytes(),
12 i: 0,
13 }
14 }
15
16 const fn next(mut self) -> (Self, Option<u8>) {
17 let mut i = self.i;
18 let s = self.s;
19
20 macro_rules! next {
21 () => {{
22 if i < s.len() {
23 let b = s[i];
24 i += 1;
25 Some(b)
26 } else {
27 None
28 }
29 }};
30 }
31
32 while let Some(b) = next!() {
33 let high = match b {
34 b'0'..=b'9' => b - b'0',
35 b'a'..=b'f' => b - b'a' + 10,
36 b'A'..=b'F' => b - b'A' + 10,
37 b' ' | b'\r' | b'\n' | b'\t' => continue,
38 _ => panic!("invalid character"),
39 };
40
41 let low = match next!() {
42 None => panic!("expected even number of hex characters"),
43 Some(b) => match b {
44 b'0'..=b'9' => b - b'0',
45 b'a'..=b'f' => b - b'a' + 10,
46 b'A'..=b'F' => b - b'A' + 10,
47 _ => panic!("expected hex character"),
48 },
49 };
50
51 self.i = i;
52 let val = (high << 4) | low;
53 return (self, Some(val));
54 }
55 (self, None)
56 }
57}
58
59impl Hex<&[&str]> {
60 pub const fn output_len(&self) -> usize {
61 let mut i = 0;
62 let mut ans = 0;
63
64 while i < self.0.len() {
65 let mut iter = Iter::new(self.0[i]);
66 while let (next, Some(_)) = iter.next() {
67 iter = next;
68 ans += 1;
69 }
70 i += 1;
71 }
72 ans
73 }
74
75 pub const fn const_eval<const N: usize>(&self) -> [u8; N] {
76 let mut buf = [0; N];
77 let mut pos = 0;
78
79 let mut i = 0;
80 while i < self.0.len() {
81 let mut iter = Iter::new(self.0[i]);
82 while let (next, Some(val)) = iter.next() {
83 iter = next;
84 buf[pos] = val;
85 pos += 1;
86 }
87 i += 1;
88 }
89 assert!(pos == N);
90 buf
91 }
92}
93
94impl Hex<&str> {
95 pub const fn output_len(&self) -> usize {
96 let ss: &[&str] = &[self.0];
97 Hex(ss).output_len()
98 }
99 pub const fn const_eval<const N: usize>(&self) -> [u8; N] {
100 let ss: &[&str] = &[self.0];
101 Hex(ss).const_eval()
102 }
103}
104
105impl<const L: usize> Hex<[&str; L]> {
106 pub const fn output_len(&self) -> usize {
107 let ss: &[&str] = &self.0;
108 Hex(ss).output_len()
109 }
110 pub const fn const_eval<const N: usize>(&self) -> [u8; N] {
111 let ss: &[&str] = &self.0;
112 Hex(ss).const_eval()
113 }
114}
115
116#[macro_export]
150macro_rules! hex {
151 ($s: expr) => {{
152 const OUTPUT_LEN: usize = $crate::__ctfe::Hex($s).output_len();
153 const OUTPUT_BUF: [u8; OUTPUT_LEN] = $crate::__ctfe::Hex($s).const_eval();
154 OUTPUT_BUF
155 }};
156}