erased_serde/
error.rs

1use alloc::borrow::ToOwned;
2use alloc::boxed::Box;
3use alloc::string::{String, ToString};
4use alloc::vec::Vec;
5use core::fmt::{self, Debug, Display};
6use serde::de::Expected;
7
8/// Error when a `Serializer` or `Deserializer` trait object fails.
9pub struct Error {
10    imp: Box<ErrorImpl>,
11}
12
13/// Result type alias where the error is `erased_serde::Error`.
14pub type Result<T> = core::result::Result<T, Error>;
15
16pub(crate) fn erase_de<E: serde::de::Error>(e: E) -> Error {
17    serde::de::Error::custom(e)
18}
19
20pub(crate) fn unerase_de<E: serde::de::Error>(e: Error) -> E {
21    e.as_serde_de_error()
22}
23
24impl Display for Error {
25    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
26        let error = self.as_serde_de_error::<serde::de::value::Error>();
27        Display::fmt(&error, formatter)
28    }
29}
30
31impl Debug for Error {
32    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
33        let error = self.as_serde_de_error::<serde::de::value::Error>();
34        Debug::fmt(&error, formatter)
35    }
36}
37
38impl serde::ser::StdError for Error {}
39
40enum ErrorImpl {
41    Custom(String),
42    InvalidType {
43        unexpected: Unexpected,
44        expected: String,
45    },
46    InvalidValue {
47        unexpected: Unexpected,
48        expected: String,
49    },
50    InvalidLength {
51        len: usize,
52        expected: String,
53    },
54    UnknownVariant {
55        variant: String,
56        expected: &'static [&'static str],
57    },
58    UnknownField {
59        field: String,
60        expected: &'static [&'static str],
61    },
62    MissingField {
63        field: &'static str,
64    },
65    DuplicateField {
66        field: &'static str,
67    },
68}
69
70enum Unexpected {
71    Bool(bool),
72    Unsigned(u64),
73    Signed(i64),
74    Float(f64),
75    Char(char),
76    Str(String),
77    Bytes(Vec<u8>),
78    Unit,
79    Option,
80    NewtypeStruct,
81    Seq,
82    Map,
83    Enum,
84    UnitVariant,
85    NewtypeVariant,
86    TupleVariant,
87    StructVariant,
88    Other(String),
89}
90
91impl serde::ser::Error for Error {
92    fn custom<T: Display>(msg: T) -> Self {
93        let imp = Box::new(ErrorImpl::Custom(msg.to_string()));
94        Error { imp }
95    }
96}
97
98impl serde::de::Error for Error {
99    fn custom<T: Display>(msg: T) -> Self {
100        let imp = Box::new(ErrorImpl::Custom(msg.to_string()));
101        Error { imp }
102    }
103
104    fn invalid_type(unexpected: serde::de::Unexpected, expected: &dyn Expected) -> Self {
105        let imp = Box::new(ErrorImpl::InvalidType {
106            unexpected: Unexpected::from_serde(unexpected),
107            expected: expected.to_string(),
108        });
109        Error { imp }
110    }
111
112    fn invalid_value(unexpected: serde::de::Unexpected, expected: &dyn Expected) -> Self {
113        let imp = Box::new(ErrorImpl::InvalidValue {
114            unexpected: Unexpected::from_serde(unexpected),
115            expected: expected.to_string(),
116        });
117        Error { imp }
118    }
119
120    fn invalid_length(len: usize, expected: &dyn Expected) -> Self {
121        let imp = Box::new(ErrorImpl::InvalidLength {
122            len,
123            expected: expected.to_string(),
124        });
125        Error { imp }
126    }
127
128    fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self {
129        let imp = Box::new(ErrorImpl::UnknownVariant {
130            variant: variant.to_owned(),
131            expected,
132        });
133        Error { imp }
134    }
135
136    fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
137        let imp = Box::new(ErrorImpl::UnknownField {
138            field: field.to_owned(),
139            expected,
140        });
141        Error { imp }
142    }
143
144    fn missing_field(field: &'static str) -> Self {
145        let imp = Box::new(ErrorImpl::MissingField { field });
146        Error { imp }
147    }
148
149    fn duplicate_field(field: &'static str) -> Self {
150        let imp = Box::new(ErrorImpl::DuplicateField { field });
151        Error { imp }
152    }
153}
154
155impl Error {
156    fn as_serde_de_error<E: serde::de::Error>(&self) -> E {
157        match self.imp.as_ref() {
158            ErrorImpl::Custom(msg) => E::custom(msg),
159            ErrorImpl::InvalidType {
160                unexpected,
161                expected,
162            } => E::invalid_type(unexpected.as_serde(), &expected.as_str()),
163            ErrorImpl::InvalidValue {
164                unexpected,
165                expected,
166            } => E::invalid_value(unexpected.as_serde(), &expected.as_str()),
167            ErrorImpl::InvalidLength { len, expected } => {
168                E::invalid_length(*len, &expected.as_str())
169            }
170            ErrorImpl::UnknownVariant { variant, expected } => {
171                E::unknown_variant(variant, expected)
172            }
173            ErrorImpl::UnknownField { field, expected } => E::unknown_field(field, expected),
174            ErrorImpl::MissingField { field } => E::missing_field(field),
175            ErrorImpl::DuplicateField { field } => E::duplicate_field(field),
176        }
177    }
178}
179
180impl Unexpected {
181    fn from_serde(unexpected: serde::de::Unexpected) -> Self {
182        match unexpected {
183            serde::de::Unexpected::Bool(value) => Unexpected::Bool(value),
184            serde::de::Unexpected::Unsigned(value) => Unexpected::Unsigned(value),
185            serde::de::Unexpected::Signed(value) => Unexpected::Signed(value),
186            serde::de::Unexpected::Float(value) => Unexpected::Float(value),
187            serde::de::Unexpected::Char(value) => Unexpected::Char(value),
188            serde::de::Unexpected::Str(value) => Unexpected::Str(value.to_owned()),
189            serde::de::Unexpected::Bytes(value) => Unexpected::Bytes(value.to_owned()),
190            serde::de::Unexpected::Unit => Unexpected::Unit,
191            serde::de::Unexpected::Option => Unexpected::Option,
192            serde::de::Unexpected::NewtypeStruct => Unexpected::NewtypeStruct,
193            serde::de::Unexpected::Seq => Unexpected::Seq,
194            serde::de::Unexpected::Map => Unexpected::Map,
195            serde::de::Unexpected::Enum => Unexpected::Enum,
196            serde::de::Unexpected::UnitVariant => Unexpected::UnitVariant,
197            serde::de::Unexpected::NewtypeVariant => Unexpected::NewtypeVariant,
198            serde::de::Unexpected::TupleVariant => Unexpected::TupleVariant,
199            serde::de::Unexpected::StructVariant => Unexpected::StructVariant,
200            serde::de::Unexpected::Other(msg) => Unexpected::Other(msg.to_owned()),
201        }
202    }
203
204    fn as_serde(&self) -> serde::de::Unexpected {
205        match self {
206            Unexpected::Bool(value) => serde::de::Unexpected::Bool(*value),
207            Unexpected::Unsigned(value) => serde::de::Unexpected::Unsigned(*value),
208            Unexpected::Signed(value) => serde::de::Unexpected::Signed(*value),
209            Unexpected::Float(value) => serde::de::Unexpected::Float(*value),
210            Unexpected::Char(value) => serde::de::Unexpected::Char(*value),
211            Unexpected::Str(value) => serde::de::Unexpected::Str(value),
212            Unexpected::Bytes(value) => serde::de::Unexpected::Bytes(value),
213            Unexpected::Unit => serde::de::Unexpected::Unit,
214            Unexpected::Option => serde::de::Unexpected::Option,
215            Unexpected::NewtypeStruct => serde::de::Unexpected::NewtypeStruct,
216            Unexpected::Seq => serde::de::Unexpected::Seq,
217            Unexpected::Map => serde::de::Unexpected::Map,
218            Unexpected::Enum => serde::de::Unexpected::Enum,
219            Unexpected::UnitVariant => serde::de::Unexpected::UnitVariant,
220            Unexpected::NewtypeVariant => serde::de::Unexpected::NewtypeVariant,
221            Unexpected::TupleVariant => serde::de::Unexpected::TupleVariant,
222            Unexpected::StructVariant => serde::de::Unexpected::StructVariant,
223            Unexpected::Other(msg) => serde::de::Unexpected::Other(msg),
224        }
225    }
226}