zwnbsp/
binary.rs

1use crate::error::Error;
2use std::str::FromStr;
3use std::string::ToString;
4
5/// Binary Representation of a `String` value
6pub struct Binary(String);
7
8impl Binary {
9    /// Decodes a `Binary` back to the _ASCII_ representation
10    pub fn decode(&self) -> Result<String, Error> {
11        let as_u8: Vec<u8> = (0..self.0.len())
12            .step_by(9)
13            .map(|i| u8::from_str_radix(&self.0[i..i + 8], 2).expect("Unable to parse to u8"))
14            .collect();
15
16        Ok(String::from_utf8(as_u8)?)
17    }
18}
19
20impl ToString for Binary {
21    fn to_string(&self) -> String {
22        self.0.clone()
23    }
24}
25
26impl FromStr for Binary {
27    type Err = Error;
28
29    fn from_str(s: &str) -> Result<Self, Self::Err> {
30        let mut binary = String::default();
31        let ascii: String = s.into();
32
33        for character in ascii.into_bytes() {
34            binary += &format!("0{:b} ", character);
35        }
36
37        // removes the trailing space at the end
38        binary.pop();
39
40        Ok(Self(binary))
41    }
42}
43
44#[cfg(test)]
45mod test {
46    use super::*;
47
48    #[test]
49    fn converts_to_binary() {
50        let ascii = "Rustaceans";
51        let binary = "01010010 01110101 01110011 01110100 01100001 01100011 01100101 01100001 01101110 01110011";
52
53        assert_eq!(binary, Binary::from_str(ascii).unwrap().0);
54    }
55
56    #[test]
57    fn get_the_string_representation() {
58        let binary_raw = "01010010 01110101 01110011 01110100 01100001 01100011 01100101 01100001 01101110 01110011";
59        let binary_string = Binary::from_str("Rustaceans").unwrap();
60
61        assert_eq!(binary_raw, binary_string.to_string());
62    }
63
64    #[test]
65    fn converts_to_ascii() {
66        let original = "Rustaceans";
67        let decoded = Binary::from_str(original).unwrap();
68        let decoded = decoded.decode().unwrap();
69
70        assert_eq!(original.to_string(), decoded);
71    }
72}