Skip to main content

bincode/features/serde/
de_borrowed.rs

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