ilmen_dot_parser/dot_parser/
node.rs

1use crate::Attributs;
2use super::parsing_error::ParsingError;
3
4#[derive(PartialEq, Eq, Debug, Clone, Default)]
5#[cfg_attr(
6    feature = "serde",
7    derive(serde::Serialize, serde::Deserialize)
8)]
9pub struct Node{
10    pub identifier: String,
11    pub attributes: Attributs
12}
13
14impl TryFrom<&String> for Node {
15    type Error = ParsingError;
16
17    fn try_from(value: &String) -> Result<Self, Self::Error> {
18
19        let split = value.split_once("[").unwrap_or((value, ""));
20        let attr = match split.1.is_empty() {
21            true => Attributs::default(),
22            false => Attributs::try_from(&split.1.replace("]",""))?
23        };
24        
25        Ok(Self{identifier: split.0.trim().to_string(), attributes: attr})
26    }
27}
28
29
30
31impl Node {
32    pub fn new(identifier: &str, attributes: Attributs) -> Self {
33        Self{
34            identifier: identifier.to_string(), 
35            attributes
36        }
37    }
38}
39
40impl ToString for Node {
41    fn to_string(&self) -> String {
42        let mut content = self.identifier.clone();
43
44        let attributes_to_string = self.attributes.to_string();
45
46        content = content + &attributes_to_string +  ";";
47        content
48    }
49}
50
51mod test {
52    
53
54    
55
56    
57
58    
59
60    
61
62    #[test]
63    fn try_from_ok() {
64        
65        let mut first_map = HashMap::new();
66        first_map.insert("label".to_string(), "\"toto\"".to_string());
67        let mut second_map = HashMap::new();
68        second_map.insert("label".to_string(), "\"toto\"".to_string());
69        second_map.insert("encore".to_string(), "2".to_string());
70        let combinations :Vec<(&str,Node)> = vec![
71            ("A", Node::new("A", Attributs::default())),
72            ("A_long_name", Node::new("A_long_name", Attributs::default())),
73            ("Bepourquoi[label=\"toto\"]", Node::new("Bepourquoi",Attributs::from(first_map))),
74            ("Bepourquoi[label=\"toto\",encore=2]", Node::new("Bepourquoi", Attributs::from(second_map)))
75            ];
76            
77    
78        combinations.iter().for_each(|combinaisons| assert_eq!(Node::try_from(&combinaisons.0.to_string()).unwrap(), combinaisons.1));
79    } 
80}