1pub mod alphabet_translator {
2 use std::num::ParseIntError;
3
4 const VALID_CHARS: [char; 61] = [
5 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
6 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'y', 'z', 'A',
7 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
8 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
9 ];
10
11 pub fn hex_to_char(hex: &str) -> Result<char, ParseIntError> {
13 let numeric_code = u8::from_str_radix(&hex, 16);
14 match numeric_code {
15 Err(e) => Err(e),
16 Ok(code) => Ok(code as char),
17 }
18 }
19
20 pub fn char_to_hex(c: char) -> String {
23 let mut temp = String::new();
24 let n = c as u8;
25 let mut hex_code = format!("{:X}", n);
26 if hex_code.len() == 1 {
27 hex_code.insert(0, '0');
28 }
29 temp.push('x');
30 temp.push_str(&hex_code);
31 temp
32 }
33
34 pub fn char_to_hex_a_string(input: &str) -> String {
36 input.chars().map(|c| char_to_hex(c)).collect()
37 }
38
39 pub fn char_to_hex_if_required(c: char) -> String {
42 if !VALID_CHARS.contains(&c) {
43 return char_to_hex(c);
44 }
45 c.to_string()
46 }
47
48 pub fn char_to_hex_str_if_required(input: &str) -> String {
51 input.chars().map(|c| char_to_hex_if_required(c)).collect()
52 }
53}
54
55#[cfg(test)]
56mod test {
57 use crate::alphabet_translator::*;
58
59 #[test]
60 fn char_to_hex_if_required_tests() {
61 assert_eq!("a", char_to_hex_if_required('a'));
62 assert_eq!("x20", char_to_hex_if_required(' '));
63 assert_eq!("x0A", char_to_hex_if_required('\n'));
64 assert_eq!("x5C", char_to_hex_if_required('\\'));
65 assert_eq!("k", char_to_hex_if_required('k'));
66 }
67
68 #[test]
69 #[should_panic]
70 fn bad_hex_to_char() {
71 hex_to_char("AY").unwrap();
72 }
73
74 #[test]
75 fn trans_with_wacks() {
76 assert_eq!("x61x62x5Cx61x62", char_to_hex_a_string("ab\\ab"));
77 }
78 #[test]
79 fn simple_str_trans() {
80 assert_eq!("x61x62", char_to_hex_a_string("ab"));
81 }
82
83 #[test]
84 fn char_to_hex_tests() {
85 assert_eq!("x61", char_to_hex('a'));
86 assert_eq!("x20", char_to_hex(' '));
87 assert_eq!("x0A", char_to_hex('\n'));
88 assert_eq!("x5C", char_to_hex('\\'));
89 }
90 #[test]
91 fn basic_hex_to_char_hex() {
92 assert_eq!('a', hex_to_char("61").unwrap());
93 assert_eq!(' ', hex_to_char("20").unwrap());
94 assert_eq!('\n', hex_to_char("0A").unwrap());
95 assert_eq!('\\', hex_to_char("5C").unwrap());
96 }
97}