Skip to main content

serde_wincode/
de.rs

1//! Deserializer
2
3use core::marker::PhantomData;
4
5use serde::de::{
6    DeserializeSeed, EnumAccess, MapAccess, SeqAccess, VariantAccess, Visitor,
7};
8use thiserror::Error;
9use wincode::{SchemaRead, error::ReadError, io::Reader};
10
11const ANY_NOT_SUPPORTED: &str =
12    "serde-wincode does not support serde's `any` decoding feature";
13const IDENTIFIER_NOT_SUPPORTED: &str =
14    "serde-wincode does not support serde identifiers";
15const IGNORED_ANY_NOT_SUPPORTED: &str =
16    "serde-wincode does not support serde's `ignored_any`";
17const SERDE_ERROR: &str = "serde error";
18
19#[cfg(not(feature = "alloc"))]
20const CANNOT_ALLOCATE: &str =
21    "Cannot allocate data like `String` and `Vec<u8>` without `alloc` feature";
22
23#[derive(Debug, Error)]
24pub enum Error {
25    /// Bincode does not support serde's `any` decoding feature.
26    #[error("{ANY_NOT_SUPPORTED}")]
27    AnyNotSupported,
28    /// Could not allocate data like `String` and `Vec<u8>`
29    #[cfg(not(feature = "alloc"))]
30    #[error("{CANNOT_ALLOCATE}")]
31    CannotAllocate,
32    #[cfg(feature = "alloc")]
33    #[error("{msg}")]
34    CustomSerde { msg: alloc::string::String },
35    #[cfg(not(feature = "alloc"))]
36    #[error("{SERDE_ERROR}")]
37    CustomSerde,
38    /// serde-wincode does not support serde identifiers.
39    #[error("{IDENTIFIER_NOT_SUPPORTED}")]
40    IdentifierNotSupported,
41    /// serde-wincode does not support serde's `ignored_any`.
42    #[error("{IGNORED_ANY_NOT_SUPPORTED}")]
43    IgnoredAnyNotSupported,
44    #[error(transparent)]
45    Read(#[from] ReadError),
46}
47
48impl serde::de::Error for Error {
49    #[cfg(feature = "alloc")]
50    fn custom<T>(msg: T) -> Self
51    where
52        T: core::fmt::Display,
53    {
54        Self::CustomSerde {
55            msg: alloc::string::ToString::to_string(&msg),
56        }
57    }
58
59    #[cfg(not(feature = "alloc"))]
60    fn custom<T>(_msg: T) -> Self
61    where
62        T: core::fmt::Display,
63    {
64        Self::CustomSerde
65    }
66}
67
68impl From<Error> for ReadError {
69    fn from(err: Error) -> Self {
70        match err {
71            Error::AnyNotSupported => Self::Custom(ANY_NOT_SUPPORTED),
72            #[cfg(not(feature = "alloc"))]
73            Error::CannotAllocate => Self::Custom(CANNOT_ALLOCATE),
74            #[cfg(feature = "alloc")]
75            Error::CustomSerde { msg: _ } => Self::Custom(SERDE_ERROR),
76            #[cfg(not(feature = "alloc"))]
77            Error::CustomSerde => Self::Custom(SERDE_ERROR),
78            Error::IdentifierNotSupported => {
79                Self::Custom(IDENTIFIER_NOT_SUPPORTED)
80            }
81            Error::IgnoredAnyNotSupported => {
82                Self::Custom(IGNORED_ANY_NOT_SUPPORTED)
83            }
84            Error::Read(err) => err,
85        }
86    }
87}
88
89pub struct Deserializer<R, C = wincode::config::Configuration> {
90    inner: R,
91    marker: PhantomData<C>,
92}
93
94impl<R, C> Deserializer<R, C> {
95    pub fn new(reader: R) -> Self {
96        Self {
97            inner: reader,
98            marker: PhantomData,
99        }
100    }
101}
102
103macro_rules! impl_fn {
104    ($deserialize_method:ident, $visit_method:ident, $visit_ty:ty) => {
105        fn $deserialize_method<V>(
106            mut self,
107            visitor: V,
108        ) -> Result<V::Value, Self::Error>
109        where
110            V: Visitor<'de>,
111        {
112            visitor.$visit_method(<$visit_ty as SchemaRead<C>>::get(
113                &mut self.inner,
114            )?)
115        }
116    };
117}
118
119impl<'de, C, R> serde::Deserializer<'de> for Deserializer<R, C>
120where
121    C: wincode::config::Config,
122    R: Reader<'de>,
123{
124    type Error = Error;
125
126    fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
127    where
128        V: Visitor<'de>,
129    {
130        Err(Self::Error::AnyNotSupported)
131    }
132
133    impl_fn!(deserialize_bool, visit_bool, bool);
134    impl_fn!(deserialize_i8, visit_i8, i8);
135    impl_fn!(deserialize_i16, visit_i16, i16);
136    impl_fn!(deserialize_i32, visit_i32, i32);
137    impl_fn!(deserialize_i64, visit_i64, i64);
138    impl_fn!(deserialize_i128, visit_i128, i128);
139    impl_fn!(deserialize_u8, visit_u8, u8);
140    impl_fn!(deserialize_u16, visit_u16, u16);
141    impl_fn!(deserialize_u32, visit_u32, u32);
142    impl_fn!(deserialize_u64, visit_u64, u64);
143    impl_fn!(deserialize_u128, visit_u128, u128);
144    impl_fn!(deserialize_f32, visit_f32, f32);
145    impl_fn!(deserialize_f64, visit_f64, f64);
146    impl_fn!(deserialize_char, visit_char, char);
147    impl_fn!(deserialize_str, visit_borrowed_str, &str);
148
149    #[cfg(feature = "alloc")]
150    impl_fn!(deserialize_string, visit_string, alloc::string::String);
151
152    #[cfg(not(feature = "alloc"))]
153    fn deserialize_string<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
154    where
155        V: Visitor<'de>,
156    {
157        Err(Self::Error::CannotAllocate)
158    }
159
160    impl_fn!(deserialize_bytes, visit_borrowed_bytes, &[u8]);
161
162    #[cfg(feature = "alloc")]
163    impl_fn!(deserialize_byte_buf, visit_byte_buf, alloc::vec::Vec<u8>);
164
165    #[cfg(not(feature = "alloc"))]
166    fn deserialize_byte_buf<V>(
167        self,
168        _visitor: V,
169    ) -> Result<V::Value, Self::Error>
170    where
171        V: Visitor<'de>,
172    {
173        Err(Self::Error::CannotAllocate)
174    }
175
176    fn deserialize_option<V>(
177        mut self,
178        visitor: V,
179    ) -> Result<V::Value, Self::Error>
180    where
181        V: Visitor<'de>,
182    {
183        let discriminant = <u8 as SchemaRead<C>>::get(&mut self.inner)?;
184        match discriminant {
185            0 => visitor.visit_none(),
186            1 => visitor.visit_some(self),
187            d => Err(ReadError::InvalidTagEncoding(d.into()).into()),
188        }
189    }
190
191    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
192    where
193        V: serde::de::Visitor<'de>,
194    {
195        visitor.visit_unit()
196    }
197
198    fn deserialize_unit_struct<V>(
199        self,
200        _name: &'static str,
201        visitor: V,
202    ) -> Result<V::Value, Self::Error>
203    where
204        V: serde::de::Visitor<'de>,
205    {
206        visitor.visit_unit()
207    }
208
209    fn deserialize_newtype_struct<V>(
210        self,
211        _name: &'static str,
212        visitor: V,
213    ) -> Result<V::Value, Self::Error>
214    where
215        V: serde::de::Visitor<'de>,
216    {
217        visitor.visit_newtype_struct(self)
218    }
219
220    fn deserialize_seq<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
221    where
222        V: serde::de::Visitor<'de>,
223    {
224        let len = <usize as SchemaRead<C>>::get(&mut self.inner)?;
225        self.deserialize_tuple(len, visitor)
226    }
227
228    fn deserialize_tuple<V>(
229        self,
230        len: usize,
231        visitor: V,
232    ) -> Result<V::Value, Self::Error>
233    where
234        V: serde::de::Visitor<'de>,
235    {
236        struct Access<R, C> {
237            deserializer: Deserializer<R, C>,
238            len: usize,
239        }
240
241        impl<'de, C, R> SeqAccess<'de> for Access<R, C>
242        where
243            C: wincode::config::Config,
244            R: Reader<'de>,
245        {
246            type Error = Error;
247
248            fn next_element_seed<T>(
249                &mut self,
250                seed: T,
251            ) -> Result<Option<T::Value>, Self::Error>
252            where
253                T: DeserializeSeed<'de>,
254            {
255                if self.len > 0 {
256                    self.len -= 1;
257                    let value = DeserializeSeed::deserialize(
258                        seed,
259                        Deserializer {
260                            inner: &mut self.deserializer.inner,
261                            marker: self.deserializer.marker,
262                        },
263                    )?;
264                    Ok(Some(value))
265                } else {
266                    Ok(None)
267                }
268            }
269
270            fn size_hint(&self) -> Option<usize> {
271                Some(self.len)
272            }
273        }
274
275        visitor.visit_seq(Access {
276            deserializer: self,
277            len,
278        })
279    }
280
281    fn deserialize_tuple_struct<V>(
282        self,
283        _name: &'static str,
284        len: usize,
285        visitor: V,
286    ) -> Result<V::Value, Self::Error>
287    where
288        V: serde::de::Visitor<'de>,
289    {
290        self.deserialize_tuple(len, visitor)
291    }
292
293    fn deserialize_map<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
294    where
295        V: serde::de::Visitor<'de>,
296    {
297        struct Access<R, C> {
298            deserializer: Deserializer<R, C>,
299            len: usize,
300        }
301
302        impl<'de, C, R> MapAccess<'de> for Access<R, C>
303        where
304            C: wincode::config::Config,
305            R: Reader<'de>,
306        {
307            type Error = Error;
308
309            fn next_key_seed<K>(
310                &mut self,
311                seed: K,
312            ) -> Result<Option<K::Value>, Self::Error>
313            where
314                K: DeserializeSeed<'de>,
315            {
316                if self.len > 0 {
317                    self.len -= 1;
318                    let key = DeserializeSeed::deserialize(
319                        seed,
320                        Deserializer {
321                            inner: &mut self.deserializer.inner,
322                            marker: self.deserializer.marker,
323                        },
324                    )?;
325                    Ok(Some(key))
326                } else {
327                    Ok(None)
328                }
329            }
330
331            fn next_value_seed<V>(
332                &mut self,
333                seed: V,
334            ) -> Result<V::Value, Self::Error>
335            where
336                V: DeserializeSeed<'de>,
337            {
338                let value = DeserializeSeed::deserialize(
339                    seed,
340                    Deserializer {
341                        inner: &mut self.deserializer.inner,
342                        marker: self.deserializer.marker,
343                    },
344                )?;
345                Ok(value)
346            }
347
348            fn size_hint(&self) -> Option<usize> {
349                Some(self.len)
350            }
351        }
352
353        let len = <usize as SchemaRead<C>>::get(&mut self.inner)?;
354
355        visitor.visit_map(Access {
356            deserializer: self,
357            len,
358        })
359    }
360
361    fn deserialize_struct<V>(
362        self,
363        _name: &'static str,
364        fields: &'static [&'static str],
365        visitor: V,
366    ) -> Result<V::Value, Self::Error>
367    where
368        V: serde::de::Visitor<'de>,
369    {
370        self.deserialize_tuple(fields.len(), visitor)
371    }
372
373    fn deserialize_enum<V>(
374        self,
375        _name: &'static str,
376        _variants: &'static [&'static str],
377        visitor: V,
378    ) -> Result<V::Value, Self::Error>
379    where
380        V: serde::de::Visitor<'de>,
381    {
382        visitor.visit_enum(self)
383    }
384
385    fn deserialize_identifier<V>(
386        self,
387        _visitor: V,
388    ) -> Result<V::Value, Self::Error>
389    where
390        V: serde::de::Visitor<'de>,
391    {
392        Err(Self::Error::IdentifierNotSupported)
393    }
394
395    fn deserialize_ignored_any<V>(self, _: V) -> Result<V::Value, Self::Error>
396    where
397        V: serde::de::Visitor<'de>,
398    {
399        Err(Self::Error::IgnoredAnyNotSupported)
400    }
401
402    fn is_human_readable(&self) -> bool {
403        false
404    }
405}
406
407impl<'de, C, R> EnumAccess<'de> for Deserializer<R, C>
408where
409    C: wincode::config::Config,
410    R: Reader<'de>,
411{
412    type Error = Error;
413    type Variant = Self;
414
415    fn variant_seed<V>(
416        mut self,
417        seed: V,
418    ) -> Result<(V::Value, Self::Variant), Self::Error>
419    where
420        V: DeserializeSeed<'de>,
421    {
422        use serde::de::value::U32Deserializer;
423        let idx = <u32 as SchemaRead<C>>::get(&mut self.inner)?;
424        let val = seed.deserialize(U32Deserializer::<Self::Error>::new(idx))?;
425        Ok((val, self))
426    }
427}
428
429impl<'de, C, R> VariantAccess<'de> for Deserializer<R, C>
430where
431    C: wincode::config::Config,
432    R: Reader<'de>,
433{
434    type Error = Error;
435
436    fn unit_variant(self) -> Result<(), Self::Error> {
437        Ok(())
438    }
439
440    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
441    where
442        T: DeserializeSeed<'de>,
443    {
444        DeserializeSeed::deserialize(seed, self)
445    }
446
447    fn tuple_variant<V>(
448        self,
449        len: usize,
450        visitor: V,
451    ) -> Result<V::Value, Self::Error>
452    where
453        V: Visitor<'de>,
454    {
455        serde::Deserializer::deserialize_tuple(self, len, visitor)
456    }
457
458    fn struct_variant<V>(
459        self,
460        fields: &'static [&'static str],
461        visitor: V,
462    ) -> Result<V::Value, Self::Error>
463    where
464        V: Visitor<'de>,
465    {
466        serde::Deserializer::deserialize_tuple(self, fields.len(), visitor)
467    }
468}