1
#[test]
2
4
fn test_map_custom_deserialize() {
3
    use std::collections::HashMap;
4

            
5
    #[derive(PartialEq, Debug)]
6
    struct CustomMap(HashMap<String, String>);
7

            
8
    // Use a custom deserializer for CustomMap in order to extract String
9
    // keys in the visit_map method.
10
    impl<'de> serde::de::Deserialize<'de> for CustomMap {
11
4
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
12
4
        where
13
4
            D: serde::Deserializer<'de>,
14
4
        {
15
            struct CVisitor;
16
            impl<'de> serde::de::Visitor<'de> for CVisitor {
17
                type Value = CustomMap;
18

            
19
                // GRCOV_EXCL_START
20
                fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
21
                    write!(formatter, "a map with string keys and values")
22
                }
23
                // GRCOV_EXCL_STOP
24

            
25
4
                fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
26
4
                where
27
4
                    A: serde::de::MapAccess<'de>,
28
4
                {
29
4
                    let mut inner = HashMap::new();
30
12
                    while let Some((k, v)) = map.next_entry::<String, String>()? {
31
8
                        inner.insert(k, v);
32
8
                    }
33
4
                    Ok(CustomMap(inner))
34
4
                }
35
            }
36
            // Note: This method will try to deserialize any value. In this test, it will
37
            // invoke the visit_map method in the visitor.
38
4
            deserializer.deserialize_any(CVisitor)
39
4
        }
40
    }
41

            
42
4
    let mut map = HashMap::<String, String>::new();
43
4
    map.insert("key1".into(), "value1".into());
44
4
    map.insert("key2".into(), "value2".into());
45
4

            
46
4
    let result: Result<CustomMap, _> = ron::from_str(
47
4
        r#"(
48
4
            key1: "value1",
49
4
            key2: "value2",
50
4
        )"#,
51
4
    );
52
4

            
53
4
    assert_eq!(result, Ok(CustomMap(map)));
54
4
}
55

            
56
#[test]
57
4
fn test_ron_struct_as_json_map() {
58
4
    let json: serde_json::Value = ron::from_str("(f1: 0, f2: 1)").unwrap();
59
4
    assert_eq!(
60
4
        json,
61
4
        serde_json::Value::Object(
62
4
            [
63
4
                (
64
4
                    String::from("f1"),
65
4
                    serde_json::Value::Number(serde_json::Number::from(0))
66
4
                ),
67
4
                (
68
4
                    String::from("f2"),
69
4
                    serde_json::Value::Number(serde_json::Number::from(1))
70
4
                ),
71
4
            ]
72
4
            .into_iter()
73
4
            .collect()
74
4
        )
75
4
    );
76
4
}