Skip to main content

bevy_reflect/serde/de/
registrations.rs

1use crate::{serde::de::error_utils::make_custom_error, TypeRegistration, TypeRegistry};
2use core::{fmt, fmt::Formatter};
3use 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
13pub struct TypeRegistrationDeserializer<'a> {
14    registry: &'a TypeRegistry,
15}
16
17impl<'a> TypeRegistrationDeserializer<'a> {
18    /// Creates a new [`TypeRegistrationDeserializer`].
19    pub fn new(registry: &'a TypeRegistry) -> Self {
20        Self { registry }
21    }
22}
23
24impl<'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                if let Some(registration) = self.0.get_with_type_path(type_path) {
45                    return Ok(registration);
46                }
47
48                match self.0.get_with_short_type_path(type_path) {
49                    Some(registration) => Ok(registration),
50                    None => Err({
51                        if self.0.is_ambiguous(type_path) {
52                            make_custom_error(format_args!(
53                                "found short type path `{type_path}`, but this short type path is ambiguous between multiple different types"
54                            ))
55                        } else {
56                            make_custom_error(format_args!(
57                                "no registration found for `{type_path}`"
58                            ))
59                        }
60                    }),
61                }
62            }
63        }
64
65        deserializer.deserialize_str(TypeRegistrationVisitor(self.registry))
66    }
67}