1use alloc::format;
5use alloc::string::String;
6use core::fmt;
7
8pub fn encode(bytes: &[u8]) -> String {
9 bytes.iter().map(|byte| format!("{byte:02X}")).collect()
10}
11
12pub const fn decode_const<const N: usize>(text: &[u8]) -> [u8; N] {
14 assert!(text.len() == N * 2, "wrong length");
15 let mut bytes = [0; N];
16 let mut index = 0;
17 while index < N {
18 bytes[index] = upper_nibble(text[2 * index]) << 4 | upper_nibble(text[2 * index + 1]);
19 index += 1;
20 }
21 bytes
22}
23
24const fn upper_nibble(digit: u8) -> u8 {
25 match digit {
26 b'0'..=b'9' => digit - b'0',
27 b'A'..=b'F' => digit - b'A' + 10,
28 _ => panic!("not an upper-case hex digit"),
29 }
30}
31
32pub fn decode<const N: usize>(text: &str) -> Result<[u8; N], ParseHexError> {
33 if let Some((index, character)) = text
34 .chars()
35 .enumerate()
36 .find(|(_, character)| !character.is_ascii_hexdigit())
37 {
38 return Err(ParseHexError::InvalidCharacter { index, character });
39 }
40 let digits = text.as_bytes();
42 if digits.len() != N * 2 {
43 return Err(ParseHexError::InvalidLength {
44 expected: N * 2,
45 actual: digits.len(),
46 });
47 }
48 let mut bytes = [0; N];
49 for (byte, [high, low]) in bytes.iter_mut().zip(digits.as_chunks::<2>().0) {
50 *byte = nibble(*high) << 4 | nibble(*low);
51 }
52 Ok(bytes)
53}
54
55fn nibble(digit: u8) -> u8 {
56 match digit {
57 b'0'..=b'9' => digit - b'0',
58 b'A'..=b'F' => digit - b'A' + 10,
59 b'a'..=b'f' => digit - b'a' + 10,
60 _ => unreachable!("checked by is_ascii_hexdigit"),
61 }
62}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub enum ParseHexError {
66 InvalidLength { expected: usize, actual: usize },
68 InvalidCharacter { index: usize, character: char },
70}
71
72impl fmt::Display for ParseHexError {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 match self {
75 Self::InvalidLength { expected, actual } => {
76 write!(f, "16進で {expected} 文字のはずが {actual} 文字でした")
77 }
78 Self::InvalidCharacter { index, character } => {
79 write!(
80 f,
81 "{index} 文字目の {character:?} は16進の数字ではありません"
82 )
83 }
84 }
85 }
86}
87
88impl core::error::Error for ParseHexError {}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93
94 #[test]
95 fn encodes_in_upper_case() {
96 assert_eq!(encode(&[0x00, 0xAB, 0x0F]), "00AB0F");
97 }
98
99 #[test]
100 fn decodes_both_cases() {
101 assert_eq!(decode::<2>("aBcD"), Ok([0xAB, 0xCD]));
102 }
103
104 #[test]
105 fn rejects_wrong_length() {
106 assert_eq!(
107 decode::<2>("ABC"),
108 Err(ParseHexError::InvalidLength {
109 expected: 4,
110 actual: 3
111 })
112 );
113 }
114
115 #[test]
116 fn rejects_non_hex_characters() {
117 assert_eq!(
118 decode::<2>("ABCG"),
119 Err(ParseHexError::InvalidCharacter {
120 index: 3,
121 character: 'G'
122 })
123 );
124 }
125
126 #[test]
127 fn reports_multibyte_characters_without_panicking() {
128 assert_eq!(
130 decode::<2>("Aあ"),
131 Err(ParseHexError::InvalidCharacter {
132 index: 1,
133 character: 'あ'
134 })
135 );
136 }
137}