bincode_next/features/serde/
de_borrowed.rs

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