ilmen_dot_parser/dot_parser/
attributs.rs1use std::collections::HashMap;
2
3use super::parsing_error::ParsingError;
4
5
6#[derive(Default, PartialEq, Eq, Debug, Clone)]
7#[cfg_attr(
8 feature = "serde",
9 derive(serde::Serialize, serde::Deserialize)
10)]
11pub struct Attributs(Option<HashMap<String,String>>);
12
13impl Attributs {
14 pub fn label(&self) -> Option<&String> {
15 self.get("label")
16 }
17
18 pub fn get(&self, key: &str) -> Option<&String> {
19 self.0.as_ref()
20 .map(|attributs| attributs.get(key))
21 .unwrap_or_default()
22 }
23
24 pub fn attributs(&self) -> Option<HashMap<String, String>> {
25 self.0.clone()
26 }
27
28}
29
30impl From<HashMap<String,String>> for Attributs {
31 fn from(value: HashMap<String,String>) -> Self {
32 Attributs(Some(value))
33 }
34}
35
36impl ToString for Attributs {
37 fn to_string(&self) -> String {
38 self.0.clone().map(
39 |attributs| "[".to_string() + &attributs.iter().map(|(id, value)| id.clone()+"="+value).collect::<Vec<_>>().join(",") + "]")
40 .unwrap_or_default()
41 }
42}
43
44impl TryFrom<&String> for Attributs {
45 type Error = ParsingError;
46
47 fn try_from(value: &String) -> Result<Self, Self::Error> {
48 value.split(",")
49 .map(as_key_value)
50 .collect::<Result<HashMap<String, String>,ParsingError>>()
51 .map(Attributs::from)
52 }
53}
54
55fn as_key_value(value: &str) -> Result<(String, String), ParsingError> {
56 let splitted = value.trim().split_once("=")
57 .ok_or(ParsingError::DefaultError("Could not parse Attribute: ".to_string() + value))?;
58 Ok((splitted.0.to_string(),splitted.1.to_string()))
59}