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