| 1 |
use std::any::Any; |
| 2 |
|
| 3 |
use serde::{ |
| 4 |
de::{MapAccess, Visitor}, |
| 5 |
Deserializer, |
| 6 |
}; |
| 7 |
|
| 8 |
#[test] |
| 9 |
fn manually_deserialize_dyn() { |
| 10 |
let ron = r#"SerializeDyn( |
| 11 |
type: "engine_utils::types::registry::tests::Player", |
| 12 |
)"#; |
| 13 |
|
| 14 |
let mut de = ron::Deserializer::from_bytes(ron.as_bytes()).unwrap(); |
| 15 |
|
| 16 |
let result = de |
| 17 |
.deserialize_struct("SerializeDyn", &["type"], SerializeDynVisitor) |
| 18 |
.unwrap(); |
| 19 |
|
| 20 |
assert_eq!( |
| 21 |
*result.downcast::<Option<(String, String)>>().unwrap(), |
| 22 |
Some(( |
| 23 |
String::from("type"), |
| 24 |
String::from("engine_utils::types::registry::tests::Player") |
| 25 |
)) |
| 26 |
); |
| 27 |
} |
| 28 |
|
| 29 |
struct SerializeDynVisitor; |
| 30 |
|
| 31 |
impl<'de> Visitor<'de> for SerializeDynVisitor { |
| 32 |
type Value = Box<dyn Any>; |
| 33 |
|
| 34 |
|
| 35 |
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { |
| 36 |
write!(formatter, "a serialize dyn struct") |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { |
| 41 |
let entry = map.next_entry::<&str, String>()?; |
| 42 |
|
| 43 |
Ok(Box::new(entry.map(|(k, v)| (String::from(k), v)))) |
| 44 |
} |
| 45 |
} |