bitsy_parser/
variable.rs

1#[derive(Clone, Debug, Eq, PartialEq)]
2pub struct Variable {
3    pub id: String,
4    pub initial_value: String,
5}
6
7impl From<String> for Variable {
8    fn from(string: String) -> Variable {
9        let id_value: Vec<&str> = string.lines().collect();
10        let id = id_value[0].replace("VAR ", "");
11
12        let initial_value = if id_value.len() == 1 {
13            "".to_string()
14        } else {
15            id_value[1..].join("")
16        };
17
18        Variable { id, initial_value }
19    }
20}
21
22impl ToString for Variable {
23    fn to_string(&self) -> String {
24        format!("VAR {}\n{}", self.id, self.initial_value)
25    }
26}
27
28#[cfg(test)]
29mod test {
30    use crate::Variable;
31
32    #[test]
33    fn variable_from_string() {
34        assert_eq!(
35            Variable::from("VAR a\n42".to_string()),
36            Variable {
37                id: "a".to_string(),
38                initial_value: "42".to_string()
39            }
40        );
41    }
42
43    #[test]
44    fn variable_to_string() {
45        let output = Variable {
46            id: "c".to_string(),
47            initial_value: "57".to_string(),
48        }
49            .to_string();
50        let expected = "VAR c\n57".to_string();
51        assert_eq!(output, expected);
52    }
53}