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    serde::serde_if_integer128! {
133        fn deserialize_i128<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
134        where
135            V: serde::de::Visitor<'de>,
136        {
137            visitor.visit_i128(Decode::decode(&mut self.de)?)
138        }
139    }
140
141    fn deserialize_u8<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
142    where
143        V: serde::de::Visitor<'de>,
144    {
145        visitor.visit_u8(Decode::decode(&mut self.de)?)
146    }
147
148    fn deserialize_u16<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
149    where
150        V: serde::de::Visitor<'de>,
151    {
152        visitor.visit_u16(Decode::decode(&mut self.de)?)
153    }
154
155    fn deserialize_u32<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
156    where
157        V: serde::de::Visitor<'de>,
158    {
159        visitor.visit_u32(Decode::decode(&mut self.de)?)
160    }
161
162    fn deserialize_u64<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
163    where
164        V: serde::de::Visitor<'de>,
165    {
166        visitor.visit_u64(Decode::decode(&mut self.de)?)
167    }
168
169    serde::serde_if_integer128! {
170        fn deserialize_u128<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
171        where
172            V: serde::de::Visitor<'de>,
173        {
174            visitor.visit_u128(Decode::decode(&mut self.de)?)
175        }
176    }
177
178    fn deserialize_f32<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
179    where
180        V: serde::de::Visitor<'de>,
181    {
182        visitor.visit_f32(Decode::decode(&mut self.de)?)
183    }
184
185    fn deserialize_f64<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
186    where
187        V: serde::de::Visitor<'de>,
188    {
189        visitor.visit_f64(Decode::decode(&mut self.de)?)
190    }
191
192    fn deserialize_char<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
193    where
194        V: serde::de::Visitor<'de>,
195    {
196        visitor.visit_char(Decode::decode(&mut self.de)?)
197    }
198
199    fn deserialize_str<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
200    where
201        V: serde::de::Visitor<'de>,
202    {
203        let str = <&'de str>::borrow_decode(&mut self.de)?;
204        visitor.visit_borrowed_str(str)
205    }
206
207    #[cfg(not(feature = "alloc"))]
208    fn deserialize_string<V>(self, _: V) -> Result<V::Value, Self::Error>
209    where
210        V: serde::de::Visitor<'de>,
211    {
212        Err(SerdeDecodeError::CannotBorrowOwnedData.into())
213    }
214
215    #[cfg(feature = "alloc")]
216    fn deserialize_string<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
217    where
218        V: serde::de::Visitor<'de>,
219    {
220        visitor.visit_string(Decode::decode(&mut self.de)?)
221    }
222
223    fn deserialize_bytes<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
224    where
225        V: serde::de::Visitor<'de>,
226    {
227        let bytes = <&'de [u8]>::borrow_decode(&mut self.de)?;
228        visitor.visit_borrowed_bytes(bytes)
229    }
230
231    #[cfg(not(feature = "alloc"))]
232    fn deserialize_byte_buf<V>(self, _: V) -> Result<V::Value, Self::Error>
233    where
234        V: serde::de::Visitor<'de>,
235    {
236        Err(SerdeDecodeError::CannotBorrowOwnedData.into())
237    }
238
239    #[cfg(feature = "alloc")]
240    fn deserialize_byte_buf<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
241    where
242        V: serde::de::Visitor<'de>,
243    {
244        visitor.visit_byte_buf(Decode::decode(&mut self.de)?)
245    }
246
247    fn deserialize_option<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
248    where
249        V: serde::de::Visitor<'de>,
250    {
251        let variant = crate::de::decode_option_variant(&mut self.de, "Option<T>")?;
252        if variant.is_some() {
253            visitor.visit_some(self)
254        } else {
255            visitor.visit_none()
256        }
257    }
258
259    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
260    where
261        V: serde::de::Visitor<'de>,
262    {
263        visitor.visit_unit()
264    }
265
266    fn deserialize_unit_struct<V>(
267        self,
268        _name: &'static str,
269        visitor: V,
270    ) -> Result<V::Value, Self::Error>
271    where
272        V: serde::de::Visitor<'de>,
273    {
274        visitor.visit_unit()
275    }
276
277    fn deserialize_newtype_struct<V>(
278        self,
279        _name: &'static str,
280        visitor: V,
281    ) -> Result<V::Value, Self::Error>
282    where
283        V: serde::de::Visitor<'de>,
284    {
285        visitor.visit_newtype_struct(self)
286    }
287
288    fn deserialize_seq<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
289    where
290        V: serde::de::Visitor<'de>,
291    {
292        let len = usize::decode(&mut self.de)?;
293        self.deserialize_tuple(len, visitor)
294    }
295
296    fn deserialize_tuple<V>(mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
297    where
298        V: serde::de::Visitor<'de>,
299    {
300        struct Access<'a, 'b, 'de, DE: BorrowDecoder<'de>> {
301            deserializer: &'a mut SerdeDecoder<'b, 'de, DE>,
302            len: usize,
303        }
304
305        impl<'de, 'a, 'b: 'a, DE: BorrowDecoder<'de> + 'b> SeqAccess<'de> for Access<'a, 'b, 'de, DE> {
306            type Error = DecodeError;
307
308            fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, DecodeError>
309            where
310                T: DeserializeSeed<'de>,
311            {
312                if self.len > 0 {
313                    self.len -= 1;
314                    let value = DeserializeSeed::deserialize(
315                        seed,
316                        SerdeDecoder {
317                            de: self.deserializer.de,
318                            pd: PhantomData,
319                        },
320                    )?;
321                    Ok(Some(value))
322                } else {
323                    Ok(None)
324                }
325            }
326
327            fn size_hint(&self) -> Option<usize> {
328                Some(self.len)
329            }
330        }
331
332        visitor.visit_seq(Access {
333            deserializer: &mut self,
334            len,
335        })
336    }
337
338    fn deserialize_tuple_struct<V>(
339        self,
340        _name: &'static str,
341        len: usize,
342        visitor: V,
343    ) -> Result<V::Value, Self::Error>
344    where
345        V: serde::de::Visitor<'de>,
346    {
347        self.deserialize_tuple(len, visitor)
348    }
349
350    fn deserialize_map<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
351    where
352        V: serde::de::Visitor<'de>,
353    {
354        struct Access<'a, 'b, 'de, DE: BorrowDecoder<'de>> {
355            deserializer: &'a mut SerdeDecoder<'b, 'de, DE>,
356            len: usize,
357        }
358
359        impl<'de, 'a, 'b: 'a, DE: BorrowDecoder<'de> + 'b> MapAccess<'de> for Access<'a, 'b, 'de, DE> {
360            type Error = DecodeError;
361
362            fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, DecodeError>
363            where
364                K: DeserializeSeed<'de>,
365            {
366                if self.len > 0 {
367                    self.len -= 1;
368                    let key = DeserializeSeed::deserialize(
369                        seed,
370                        SerdeDecoder {
371                            de: self.deserializer.de,
372                            pd: PhantomData,
373                        },
374                    )?;
375                    Ok(Some(key))
376                } else {
377                    Ok(None)
378                }
379            }
380
381            fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, DecodeError>
382            where
383                V: DeserializeSeed<'de>,
384            {
385                let value = DeserializeSeed::deserialize(
386                    seed,
387                    SerdeDecoder {
388                        de: self.deserializer.de,
389                        pd: PhantomData,
390                    },
391                )?;
392                Ok(value)
393            }
394
395            fn size_hint(&self) -> Option<usize> {
396                Some(self.len)
397            }
398        }
399
400        let len = usize::decode(&mut self.de)?;
401
402        visitor.visit_map(Access {
403            deserializer: &mut self,
404            len,
405        })
406    }
407
408    fn deserialize_struct<V>(
409        self,
410        _name: &'static str,
411        fields: &'static [&'static str],
412        visitor: V,
413    ) -> Result<V::Value, Self::Error>
414    where
415        V: serde::de::Visitor<'de>,
416    {
417        self.deserialize_tuple(fields.len(), visitor)
418    }
419
420    fn deserialize_enum<V>(
421        self,
422        _name: &'static str,
423        _variants: &'static [&'static str],
424        visitor: V,
425    ) -> Result<V::Value, Self::Error>
426    where
427        V: serde::de::Visitor<'de>,
428    {
429        visitor.visit_enum(self)
430    }
431
432    fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
433    where
434        V: serde::de::Visitor<'de>,
435    {
436        Err(SerdeDecodeError::IdentifierNotSupported.into())
437    }
438
439    fn deserialize_ignored_any<V>(self, _: V) -> Result<V::Value, Self::Error>
440    where
441        V: serde::de::Visitor<'de>,
442    {
443        Err(SerdeDecodeError::IgnoredAnyNotSupported.into())
444    }
445
446    fn is_human_readable(&self) -> bool {
447        false
448    }
449}
450
451impl<'de, DE: BorrowDecoder<'de>> EnumAccess<'de> for SerdeDecoder<'_, 'de, DE> {
452    type Error = DecodeError;
453    type Variant = Self;
454
455    fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
456    where
457        V: DeserializeSeed<'de>,
458    {
459        let idx = u32::decode(&mut self.de)?;
460        let val = seed.deserialize(idx.into_deserializer())?;
461        Ok((val, self))
462    }
463}
464
465impl<'de, DE: BorrowDecoder<'de>> VariantAccess<'de> for SerdeDecoder<'_, 'de, DE> {
466    type Error = DecodeError;
467
468    fn unit_variant(self) -> Result<(), Self::Error> {
469        Ok(())
470    }
471
472    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
473    where
474        T: DeserializeSeed<'de>,
475    {
476        DeserializeSeed::deserialize(seed, self)
477    }
478
479    fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
480    where
481        V: Visitor<'de>,
482    {
483        Deserializer::deserialize_tuple(self, len, visitor)
484    }
485
486    fn struct_variant<V>(
487        self,
488        fields: &'static [&'static str],
489        visitor: V,
490    ) -> Result<V::Value, Self::Error>
491    where
492        V: Visitor<'de>,
493    {
494        Deserializer::deserialize_tuple(self, fields.len(), visitor)
495    }
496}