cu_bincode/features/serde/
de_borrowed.rs

1use super::DecodeError as SerdeDecodeError;
2use crate::{
3    config::Config,
4    de::{read::SliceReader, BorrowDecode, BorrowDecoder, Decode, DecoderImpl},
5    error::DecodeError,
6};
7use core::marker::PhantomData;
8use serde::de::*;
9
10/// Serde decoder encapsulating a borrowed reader.
11pub struct BorrowedSerdeDecoder<'de, DE: BorrowDecoder<'de>> {
12    pub(super) de: DE,
13    pub(super) pd: PhantomData<&'de ()>,
14}
15
16impl<'de, DE: BorrowDecoder<'de>> BorrowedSerdeDecoder<'de, DE> {
17    /// Return a type implementing `serde::Deserializer`.
18    pub fn as_deserializer<'a>(
19        &'a mut self,
20    ) -> impl serde::Deserializer<'de, Error = DecodeError> + 'a {
21        SerdeDecoder {
22            de: &mut self.de,
23            pd: PhantomData,
24        }
25    }
26}
27
28impl<'de, C: Config, Context> BorrowedSerdeDecoder<'de, DecoderImpl<SliceReader<'de>, C, Context>> {
29    /// Creates the decoder from a borrowed slice.
30    pub fn from_slice(
31        slice: &'de [u8],
32        config: C,
33        context: Context,
34    ) -> BorrowedSerdeDecoder<'de, DecoderImpl<SliceReader<'de>, C, Context>>
35    where
36        C: Config,
37    {
38        let reader = SliceReader::new(slice);
39        let decoder = DecoderImpl::new(reader, config, context);
40        Self {
41            de: decoder,
42            pd: PhantomData,
43        }
44    }
45}
46
47/// Attempt to decode a given type `D` from the given slice. Returns the decoded output and the amount of bytes read.
48///
49/// See the [config](../config/index.html) module for more information on configurations.
50pub fn borrow_decode_from_slice<'de, D, C>(
51    slice: &'de [u8],
52    config: C,
53) -> Result<(D, usize), DecodeError>
54where
55    D: Deserialize<'de>,
56    C: Config,
57{
58    let mut serde_decoder =
59        BorrowedSerdeDecoder::<DecoderImpl<SliceReader<'de>, C, ()>>::from_slice(slice, config, ());
60    let result = D::deserialize(serde_decoder.as_deserializer())?;
61    let bytes_read = slice.len() - serde_decoder.de.borrow_reader().slice.len();
62    Ok((result, bytes_read))
63}
64
65/// Decode a borrowed type from the given slice using a seed. Some parts of the decoded type are expected to be referring to the given slice
66pub fn seed_decode_from_slice<'de, D, C>(
67    seed: D,
68    slice: &'de [u8],
69    config: C,
70) -> Result<(D::Value, usize), DecodeError>
71where
72    D: DeserializeSeed<'de>,
73    C: Config,
74{
75    let mut serde_decoder =
76        BorrowedSerdeDecoder::<DecoderImpl<SliceReader<'de>, C, ()>>::from_slice(slice, config, ());
77    let result = seed.deserialize(serde_decoder.as_deserializer())?;
78    let bytes_read = slice.len() - serde_decoder.de.borrow_reader().slice.len();
79    Ok((result, bytes_read))
80}
81
82pub(super) struct SerdeDecoder<'a, 'de, DE: BorrowDecoder<'de>> {
83    pub(super) de: &'a mut DE,
84    pub(super) pd: PhantomData<&'de ()>,
85}
86
87impl<'de, DE: BorrowDecoder<'de>> Deserializer<'de> for SerdeDecoder<'_, 'de, DE> {
88    type Error = DecodeError;
89
90    fn deserialize_any<V>(self, _: V) -> Result<V::Value, Self::Error>
91    where
92        V: serde::de::Visitor<'de>,
93    {
94        Err(SerdeDecodeError::AnyNotSupported.into())
95    }
96
97    fn deserialize_bool<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
98    where
99        V: serde::de::Visitor<'de>,
100    {
101        visitor.visit_bool(Decode::decode(&mut self.de)?)
102    }
103
104    fn deserialize_i8<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
105    where
106        V: serde::de::Visitor<'de>,
107    {
108        visitor.visit_i8(Decode::decode(&mut self.de)?)
109    }
110
111    fn deserialize_i16<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
112    where
113        V: serde::de::Visitor<'de>,
114    {
115        visitor.visit_i16(Decode::decode(&mut self.de)?)
116    }
117
118    fn deserialize_i32<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
119    where
120        V: serde::de::Visitor<'de>,
121    {
122        visitor.visit_i32(Decode::decode(&mut self.de)?)
123    }
124
125    fn deserialize_i64<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
126    where
127        V: serde::de::Visitor<'de>,
128    {
129        visitor.visit_i64(Decode::decode(&mut self.de)?)
130    }
131
132    fn deserialize_i128<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
133    where
134        V: serde::de::Visitor<'de>,
135    {
136        visitor.visit_i128(Decode::decode(&mut self.de)?)
137    }
138
139    fn deserialize_u8<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
140    where
141        V: serde::de::Visitor<'de>,
142    {
143        visitor.visit_u8(Decode::decode(&mut self.de)?)
144    }
145
146    fn deserialize_u16<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
147    where
148        V: serde::de::Visitor<'de>,
149    {
150        visitor.visit_u16(Decode::decode(&mut self.de)?)
151    }
152
153    fn deserialize_u32<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
154    where
155        V: serde::de::Visitor<'de>,
156    {
157        visitor.visit_u32(Decode::decode(&mut self.de)?)
158    }
159
160    fn deserialize_u64<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
161    where
162        V: serde::de::Visitor<'de>,
163    {
164        visitor.visit_u64(Decode::decode(&mut self.de)?)
165    }
166
167    fn deserialize_u128<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
168    where
169        V: serde::de::Visitor<'de>,
170    {
171        visitor.visit_u128(Decode::decode(&mut self.de)?)
172    }
173
174    fn deserialize_f32<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
175    where
176        V: serde::de::Visitor<'de>,
177    {
178        visitor.visit_f32(Decode::decode(&mut self.de)?)
179    }
180
181    fn deserialize_f64<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
182    where
183        V: serde::de::Visitor<'de>,
184    {
185        visitor.visit_f64(Decode::decode(&mut self.de)?)
186    }
187
188    fn deserialize_char<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
189    where
190        V: serde::de::Visitor<'de>,
191    {
192        visitor.visit_char(Decode::decode(&mut self.de)?)
193    }
194
195    fn deserialize_str<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
196    where
197        V: serde::de::Visitor<'de>,
198    {
199        let str = <&'de str>::borrow_decode(&mut self.de)?;
200        visitor.visit_borrowed_str(str)
201    }
202
203    #[cfg(not(feature = "alloc"))]
204    fn deserialize_string<V>(self, _: V) -> Result<V::Value, Self::Error>
205    where
206        V: serde::de::Visitor<'de>,
207    {
208        Err(SerdeDecodeError::CannotBorrowOwnedData.into())
209    }
210
211    #[cfg(feature = "alloc")]
212    fn deserialize_string<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
213    where
214        V: serde::de::Visitor<'de>,
215    {
216        visitor.visit_string(Decode::decode(&mut self.de)?)
217    }
218
219    fn deserialize_bytes<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
220    where
221        V: serde::de::Visitor<'de>,
222    {
223        let bytes = <&'de [u8]>::borrow_decode(&mut self.de)?;
224        visitor.visit_borrowed_bytes(bytes)
225    }
226
227    #[cfg(not(feature = "alloc"))]
228    fn deserialize_byte_buf<V>(self, _: V) -> Result<V::Value, Self::Error>
229    where
230        V: serde::de::Visitor<'de>,
231    {
232        Err(SerdeDecodeError::CannotBorrowOwnedData.into())
233    }
234
235    #[cfg(feature = "alloc")]
236    fn deserialize_byte_buf<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
237    where
238        V: serde::de::Visitor<'de>,
239    {
240        visitor.visit_byte_buf(Decode::decode(&mut self.de)?)
241    }
242
243    fn deserialize_option<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
244    where
245        V: serde::de::Visitor<'de>,
246    {
247        let variant = crate::de::decode_option_variant(&mut self.de, "Option<T>")?;
248        if variant.is_some() {
249            visitor.visit_some(self)
250        } else {
251            visitor.visit_none()
252        }
253    }
254
255    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
256    where
257        V: serde::de::Visitor<'de>,
258    {
259        visitor.visit_unit()
260    }
261
262    fn deserialize_unit_struct<V>(
263        self,
264        _name: &'static str,
265        visitor: V,
266    ) -> Result<V::Value, Self::Error>
267    where
268        V: serde::de::Visitor<'de>,
269    {
270        visitor.visit_unit()
271    }
272
273    fn deserialize_newtype_struct<V>(
274        self,
275        _name: &'static str,
276        visitor: V,
277    ) -> Result<V::Value, Self::Error>
278    where
279        V: serde::de::Visitor<'de>,
280    {
281        visitor.visit_newtype_struct(self)
282    }
283
284    fn deserialize_seq<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
285    where
286        V: serde::de::Visitor<'de>,
287    {
288        let len = usize::decode(&mut self.de)?;
289        self.deserialize_tuple(len, visitor)
290    }
291
292    fn deserialize_tuple<V>(mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
293    where
294        V: serde::de::Visitor<'de>,
295    {
296        struct Access<'a, 'b, 'de, DE: BorrowDecoder<'de>> {
297            deserializer: &'a mut SerdeDecoder<'b, 'de, DE>,
298            len: usize,
299        }
300
301        impl<'de, 'a, 'b: 'a, DE: BorrowDecoder<'de> + 'b> SeqAccess<'de> for Access<'a, 'b, 'de, DE> {
302            type Error = DecodeError;
303
304            fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, DecodeError>
305            where
306                T: DeserializeSeed<'de>,
307            {
308                if self.len > 0 {
309                    self.len -= 1;
310                    let value = DeserializeSeed::deserialize(
311                        seed,
312                        SerdeDecoder {
313                            de: self.deserializer.de,
314                            pd: PhantomData,
315                        },
316                    )?;
317                    Ok(Some(value))
318                } else {
319                    Ok(None)
320                }
321            }
322
323            fn size_hint(&self) -> Option<usize> {
324                Some(self.len)
325            }
326        }
327
328        visitor.visit_seq(Access {
329            deserializer: &mut self,
330            len,
331        })
332    }
333
334    fn deserialize_tuple_struct<V>(
335        self,
336        _name: &'static str,
337        len: usize,
338        visitor: V,
339    ) -> Result<V::Value, Self::Error>
340    where
341        V: serde::de::Visitor<'de>,
342    {
343        self.deserialize_tuple(len, visitor)
344    }
345
346    fn deserialize_map<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
347    where
348        V: serde::de::Visitor<'de>,
349    {
350        struct Access<'a, 'b, 'de, DE: BorrowDecoder<'de>> {
351            deserializer: &'a mut SerdeDecoder<'b, 'de, DE>,
352            len: usize,
353        }
354
355        impl<'de, 'a, 'b: 'a, DE: BorrowDecoder<'de> + 'b> MapAccess<'de> for Access<'a, 'b, 'de, DE> {
356            type Error = DecodeError;
357
358            fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, DecodeError>
359            where
360                K: DeserializeSeed<'de>,
361            {
362                if self.len > 0 {
363                    self.len -= 1;
364                    let key = DeserializeSeed::deserialize(
365                        seed,
366                        SerdeDecoder {
367                            de: self.deserializer.de,
368                            pd: PhantomData,
369                        },
370                    )?;
371                    Ok(Some(key))
372                } else {
373                    Ok(None)
374                }
375            }
376
377            fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, DecodeError>
378            where
379                V: DeserializeSeed<'de>,
380            {
381                let value = DeserializeSeed::deserialize(
382                    seed,
383                    SerdeDecoder {
384                        de: self.deserializer.de,
385                        pd: PhantomData,
386                    },
387                )?;
388                Ok(value)
389            }
390
391            fn size_hint(&self) -> Option<usize> {
392                Some(self.len)
393            }
394        }
395
396        let len = usize::decode(&mut self.de)?;
397
398        visitor.visit_map(Access {
399            deserializer: &mut self,
400            len,
401        })
402    }
403
404    fn deserialize_struct<V>(
405        self,
406        _name: &'static str,
407        fields: &'static [&'static str],
408        visitor: V,
409    ) -> Result<V::Value, Self::Error>
410    where
411        V: serde::de::Visitor<'de>,
412    {
413        self.deserialize_tuple(fields.len(), visitor)
414    }
415
416    fn deserialize_enum<V>(
417        self,
418        _name: &'static str,
419        _variants: &'static [&'static str],
420        visitor: V,
421    ) -> Result<V::Value, Self::Error>
422    where
423        V: serde::de::Visitor<'de>,
424    {
425        visitor.visit_enum(self)
426    }
427
428    fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
429    where
430        V: serde::de::Visitor<'de>,
431    {
432        Err(SerdeDecodeError::IdentifierNotSupported.into())
433    }
434
435    fn deserialize_ignored_any<V>(self, _: V) -> Result<V::Value, Self::Error>
436    where
437        V: serde::de::Visitor<'de>,
438    {
439        Err(SerdeDecodeError::IgnoredAnyNotSupported.into())
440    }
441
442    fn is_human_readable(&self) -> bool {
443        false
444    }
445}
446
447impl<'de, DE: BorrowDecoder<'de>> EnumAccess<'de> for SerdeDecoder<'_, 'de, DE> {
448    type Error = DecodeError;
449    type Variant = Self;
450
451    fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
452    where
453        V: DeserializeSeed<'de>,
454    {
455        let idx = u32::decode(&mut self.de)?;
456        let val = seed.deserialize(idx.into_deserializer())?;
457        Ok((val, self))
458    }
459}
460
461impl<'de, DE: BorrowDecoder<'de>> VariantAccess<'de> for SerdeDecoder<'_, 'de, DE> {
462    type Error = DecodeError;
463
464    fn unit_variant(self) -> Result<(), Self::Error> {
465        Ok(())
466    }
467
468    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
469    where
470        T: DeserializeSeed<'de>,
471    {
472        DeserializeSeed::deserialize(seed, self)
473    }
474
475    fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
476    where
477        V: Visitor<'de>,
478    {
479        Deserializer::deserialize_tuple(self, len, visitor)
480    }
481
482    fn struct_variant<V>(
483        self,
484        fields: &'static [&'static str],
485        visitor: V,
486    ) -> Result<V::Value, Self::Error>
487    where
488        V: Visitor<'de>,
489    {
490        Deserializer::deserialize_tuple(self, fields.len(), visitor)
491    }
492}