jyt/
lib.rs

1pub mod error;
2
3mod ext;
4
5pub use ext::Ext;
6
7pub trait Converter {
8    fn to_json(self, from: Ext) -> Result<String, error::Error>;
9    fn to_yaml(self, from: Ext) -> Result<String, error::Error>;
10    fn to_toml(self, from: Ext) -> Result<String, error::Error>;
11}
12
13impl Converter for String {
14    fn to_json(self, from: Ext) -> Result<String, error::Error> {
15        let value = ext::deserialize::<ext::json::Value>(from, &self)?;
16        ext::json::serialize(&value)
17    }
18    fn to_yaml(self, from: Ext) -> Result<String, error::Error> {
19        let value = ext::deserialize::<ext::yaml::Value>(from, &self)?;
20        ext::yaml::serialize(&value)
21    }
22    fn to_toml(self, from: Ext) -> Result<String, error::Error> {
23        let value = ext::deserialize::<ext::toml::Value>(from, &self)?;
24        ext::toml::serialize(&value)
25    }
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31    use paste::paste;
32
33    static JSON: &str = r#"{
34  "title": "TOML Example",
35  "owner": {
36    "name": "Tom Preston-Werner"
37  },
38  "database": {
39    "server": "192.168.1.1",
40    "ports": [
41      8000,
42      8001,
43      8002
44    ],
45    "connection_max": 5000,
46    "enabled": true
47  }
48}"#;
49
50    static YAML: &str = r#"title: TOML Example
51owner:
52  name: Tom Preston-Werner
53database:
54  server: 192.168.1.1
55  ports:
56  - 8000
57  - 8001
58  - 8002
59  connection_max: 5000
60  enabled: true
61"#;
62
63    static TOML: &str = r#"title = "TOML Example"
64
65[owner]
66name = "Tom Preston-Werner"
67
68[database]
69server = "192.168.1.1"
70ports = [8000, 8001, 8002]
71connection_max = 5000
72enabled = true
73"#;
74
75    macro_rules! test_convert {
76        ($from:ident, $to:ident) => {
77            paste! {
78                #[test]
79                fn [< convert_ $from _to_ $to >]() {
80                    let output = [<$from:upper>].to_string().[< to_ $to >](Ext::[<$from:camel>]);
81                    assert!(output.is_ok());
82                    assert_eq!(output.unwrap(), [<$to:upper>].to_string());
83                }
84            }
85        };
86    }
87
88    test_convert!(json, yaml);
89    test_convert!(json, toml);
90    test_convert!(yaml, json);
91    test_convert!(yaml, toml);
92    test_convert!(toml, json);
93    test_convert!(toml, yaml);
94}