File: 511_deserialize_any_map_string_key.rs

package info (click to toggle)
rust-ron 0.12.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,096 kB
  • sloc: makefile: 2
file content (76 lines) | stat: -rw-r--r-- 2,442 bytes parent folder | download | duplicates (3)
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
#[test]
fn test_map_custom_deserialize() {
    use std::collections::HashMap;

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

    // Use a custom deserializer for CustomMap in order to extract String
    // keys in the visit_map method.
    impl<'de> serde::de::Deserialize<'de> for CustomMap {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            struct CVisitor;
            impl<'de> serde::de::Visitor<'de> for CVisitor {
                type Value = CustomMap;

                // GRCOV_EXCL_START
                fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
                    write!(formatter, "a map with string keys and values")
                }
                // GRCOV_EXCL_STOP

                fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
                where
                    A: serde::de::MapAccess<'de>,
                {
                    let mut inner = HashMap::new();
                    while let Some((k, v)) = map.next_entry::<String, String>()? {
                        inner.insert(k, v);
                    }
                    Ok(CustomMap(inner))
                }
            }
            // Note: This method will try to deserialize any value. In this test, it will
            // invoke the visit_map method in the visitor.
            deserializer.deserialize_any(CVisitor)
        }
    }

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

    let result: Result<CustomMap, _> = ron::from_str(
        r#"(
            key1: "value1",
            key2: "value2",
        )"#,
    );

    assert_eq!(result, Ok(CustomMap(map)));
}

#[test]
fn test_ron_struct_as_json_map() {
    let json: serde_json::Value = ron::from_str("(f1: 0, f2: 1)").unwrap();
    assert_eq!(
        json,
        serde_json::Value::Object(
            [
                (
                    String::from("f1"),
                    serde_json::Value::Number(serde_json::Number::from(0))
                ),
                (
                    String::from("f2"),
                    serde_json::Value::Number(serde_json::Number::from(1))
                ),
            ]
            .into_iter()
            .collect()
        )
    );
}