1fn to_reverse_hex_digit(b: u8) -> Option<u8> {
15 let value = match b {
16 b'0'..=b'9' => b - b'0',
17 b'A'..=b'F' => b - b'A' + 10,
18 b'a'..=b'f' => b - b'a' + 10,
19 _ => return None,
20 };
21 Some(b'z' - value)
22}
23
24fn to_forward_hex_digit(b: u8) -> Option<u8> {
25 let value = match b {
26 b'k'..=b'z' => b'z' - b,
27 b'K'..=b'Z' => b'Z' - b,
28 _ => return None,
29 };
30 if value < 10 {
31 Some(b'0' + value)
32 } else {
33 Some(b'a' + value - 10)
34 }
35}
36
37pub fn to_forward_hex(reverse_hex: &str) -> Option<String> {
38 reverse_hex
39 .bytes()
40 .map(|b| to_forward_hex_digit(b).map(char::from))
41 .collect()
42}
43
44pub fn to_reverse_hex(forward_hex: &str) -> Option<String> {
45 forward_hex
46 .bytes()
47 .map(|b| to_reverse_hex_digit(b).map(char::from))
48 .collect()
49}
50
51#[cfg(test)]
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 #[test]
57 fn test_reverse_hex() {
58 assert_eq!(to_reverse_hex(""), Some("".to_string()));
60 assert_eq!(to_forward_hex(""), Some("".to_string()));
61
62 assert_eq!(to_reverse_hex("0"), Some("z".to_string()));
64 assert_eq!(to_forward_hex("z"), Some("0".to_string()));
65
66 assert_eq!(
68 to_reverse_hex("0123456789abcdefABCDEF"),
69 Some("zyxwvutsrqponmlkponmlk".to_string())
70 );
71 assert_eq!(
72 to_forward_hex("zyxwvutsrqponmlkPONMLK"),
73 Some("0123456789abcdefabcdef".to_string())
74 );
75
76 assert_eq!(to_reverse_hex("g"), None);
78 assert_eq!(to_forward_hex("j"), None);
79 }
80}