Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_reflect/src/serde/de/registrations.rs
6600 views
1
use crate::{serde::de::error_utils::make_custom_error, TypeRegistration, TypeRegistry};
2
use core::{fmt, fmt::Formatter};
3
use serde::de::{DeserializeSeed, Error, Visitor};
4
5
/// A deserializer for type registrations.
6
///
7
/// This will return a [`&TypeRegistration`] corresponding to the given type.
8
/// This deserializer expects a string containing the _full_ [type path] of the
9
/// type to find the `TypeRegistration` of.
10
///
11
/// [`&TypeRegistration`]: TypeRegistration
12
/// [type path]: crate::TypePath::type_path
13
pub struct TypeRegistrationDeserializer<'a> {
14
registry: &'a TypeRegistry,
15
}
16
17
impl<'a> TypeRegistrationDeserializer<'a> {
18
/// Creates a new [`TypeRegistrationDeserializer`].
19
pub fn new(registry: &'a TypeRegistry) -> Self {
20
Self { registry }
21
}
22
}
23
24
impl<'a, 'de> DeserializeSeed<'de> for TypeRegistrationDeserializer<'a> {
25
type Value = &'a TypeRegistration;
26
27
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
28
where
29
D: serde::Deserializer<'de>,
30
{
31
struct TypeRegistrationVisitor<'a>(&'a TypeRegistry);
32
33
impl<'de, 'a> Visitor<'de> for TypeRegistrationVisitor<'a> {
34
type Value = &'a TypeRegistration;
35
36
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
37
formatter.write_str("string containing `type` entry for the reflected value")
38
}
39
40
fn visit_str<E>(self, type_path: &str) -> Result<Self::Value, E>
41
where
42
E: Error,
43
{
44
self.0.get_with_type_path(type_path).ok_or_else(|| {
45
make_custom_error(format_args!("no registration found for `{type_path}`"))
46
})
47
}
48
}
49
50
deserializer.deserialize_str(TypeRegistrationVisitor(self.registry))
51
}
52
}
53
54