1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use super::*;

pub use self::de::from_tree;
pub use self::error::Error;
pub use self::ser::to_tree;

mod de;
mod error;
mod fmt;
mod ser;

pub mod json {
    use super::*;
    pub use fmt::json::ParseErr as JsonParseErrDetail;
    pub use fmt::json::Parser as JsonParser;
    pub use fmt::json::Terminal;
}

pub mod toml {
    use super::*;
    use kg_diag::ParseDiag;
    use serde::de;

    pub use fmt::toml::ParseErrDetail as TomlParseErrDetail;
    pub use fmt::toml::Parser as TomlParser;

    pub fn from_str<'de, T>(toml: &'de str) -> Result<T, ParseDiag>
    where
        T: de::Deserialize<'de>,
    {
        let n = NodeRef::from_toml(toml)?;

        // FIXME ws error handling
        super::de::from_tree(&n).map_err(|err| {
            eprintln!("Cannot deserialize type = {:?}", err);
            panic!("Deserialization error")
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, Serialize, Deserialize)]
    struct Data {
        str_prop: String,
        usize_prop: usize,
        float_prop: f64,
    }

    #[test]
    fn serialization() {
        let d = Data {
            str_prop: "String property value".to_string(),
            usize_prop: 130,
            float_prop: 12.5,
        };

        let json = r#"{"str_prop":"String property value","usize_prop":130,"float_prop":12.5}"#;

        let n = self::ser::to_tree(&d).unwrap();

        assert_eq!(n.to_json(), json);
    }

    #[test]
    fn deserialization() {
        let json = r#"{
            "str_prop": "String property value",
            "usize_prop": 130,
            "float_prop": 12.5
        }"#;

        let n = NodeRef::from_json(json).unwrap();

        let d: Data = self::de::from_tree(&n).unwrap();

        assert_eq!(d.str_prop, "String property value");
        assert_eq!(d.usize_prop, 130);
        assert_eq!(d.float_prop, 12.5);
    }
}