| 1 |
#[test] |
| 2 |
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 |
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 12 |
where |
| 13 |
D: serde::Deserializer<'de>, |
| 14 |
{ |
| 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 |
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> |
| 26 |
where |
| 27 |
A: serde::de::MapAccess<'de>, |
| 28 |
{ |
| 29 |
let mut inner = HashMap::new(); |
| 30 |
while let Some((k, v)) = map.next_entry::<String, String>()? { |
| 31 |
inner.insert(k, v); |
| 32 |
} |
| 33 |
Ok(CustomMap(inner)) |
| 34 |
} |
| 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 |
deserializer.deserialize_any(CVisitor) |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
let mut map = HashMap::<String, String>::new(); |
| 43 |
map.insert("key1".into(), "value1".into()); |
| 44 |
map.insert("key2".into(), "value2".into()); |
| 45 |
|
| 46 |
let result: Result<CustomMap, _> = ron::from_str( |
| 47 |
r#"( |
| 48 |
key1: "value1", |
| 49 |
key2: "value2", |
| 50 |
)"#, |
| 51 |
); |
| 52 |
|
| 53 |
assert_eq!(result, Ok(CustomMap(map))); |
| 54 |
} |
| 55 |
|
| 56 |
#[test] |
| 57 |
fn test_ron_struct_as_json_map() { |
| 58 |
let json: serde_json::Value = ron::from_str("(f1: 0, f2: 1)").unwrap(); |
| 59 |
assert_eq!( |
| 60 |
json, |
| 61 |
serde_json::Value::Object( |
| 62 |
[ |
| 63 |
( |
| 64 |
String::from("f1"), |
| 65 |
serde_json::Value::Number(serde_json::Number::from(0)) |
| 66 |
), |
| 67 |
( |
| 68 |
String::from("f2"), |
| 69 |
serde_json::Value::Number(serde_json::Number::from(1)) |
| 70 |
), |
| 71 |
] |
| 72 |
.into_iter() |
| 73 |
.collect() |
| 74 |
) |
| 75 |
); |
| 76 |
} |