ascii_to_hex/
lib.rs

1#![allow(dead_code)]
2//! Library to convert an ASCII string into Hex
3//! The general flow goes like this:
4//! 1. Convert the ASCII into bytes.
5//! 2. Convert the bytes into Hex Strings
6//! 3. Concatenate the Hex Strings
7//! 4. Return the single Hex String
8
9pub mod ascii_to_hex {
10
11    /// What gets called from outside
12    pub fn get_hex_string<'a>(ascii_string: &'a str) -> String {
13        let ascii_bytes = get_bytes(ascii_string);
14        let hex_vec = convert_to_hex(ascii_bytes);
15        concatenate_slices(hex_vec)
16    }
17
18    /// This function takes in the ASCII string and
19    /// turns it into its byte representation.
20    /// This returns a u8 slice.
21    fn get_bytes<'a>(ascii_string: &'a str) -> &'a [u8] {
22        ascii_string.as_bytes()
23    }
24    /// This function will convert each u8 slice element
25    /// into a String element containing the hex representation
26    /// of the u8 element
27    fn convert_to_hex<'a>(ascii_bytes: &'a [u8]) -> Vec<String> {
28        ascii_bytes
29            .into_iter()
30            .map(|byte| format!("{:X}", byte).as_str().to_owned())
31            .collect()
32    }
33    /// This function simply concatenates all the hex strings
34    fn concatenate_slices<'a>(hex_vec: Vec<String>) -> String {
35        hex_vec.concat()
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::ascii_to_hex;
42
43    #[test]
44    fn it_works() {
45        let test_string = "test";
46        assert_eq!(ascii_to_hex::get_hex_string(test_string), "74657374");
47    }
48
49    #[test]
50    fn empty_string() {
51        let test_string = "";
52        assert_eq!(ascii_to_hex::get_hex_string(test_string), "");
53    }
54
55    #[test]
56    fn long_string() {
57        let test_string = "DSJAKLFHASJKGLF879Q472631987HJKFSDAHFLKSJADHsdahlkfjhdskalfh";
58        assert_eq!(ascii_to_hex::get_hex_string(test_string), "44534A414B4C464841534A4B474C4638373951343732363331393837484A4B4653444148464C4B534A414448736461686C6B666A6864736B616C6668");
59    }
60
61    #[test]
62    fn special_characters() {
63        let test_string = "!@#%";
64        assert_eq!(ascii_to_hex::get_hex_string(test_string), "21402325");
65    }
66}