Skip to main content

bincode_next/de/
mod.rs

1//! Decoder-based structs and traits.
2#![allow(clippy::used_underscore_binding)]
3
4mod decoder;
5#[doc(hidden)]
6pub(crate) mod deterministic;
7mod impl_core;
8mod impl_tuples;
9mod impls;
10
11use self::decoder::WithContext;
12use self::read::BorrowReader;
13use self::read::Reader;
14use crate::config::Config;
15use crate::config::Format;
16use crate::config::IntEncoding;
17use crate::config::InternalLimitConfig;
18use crate::error::DecodeError;
19use crate::utils::Sealed;
20
21/// Fiber-backed abstraction for zero-cost async decoding.
22#[cfg(feature = "async-fiber")]
23pub mod async_fiber;
24/// Bit-level reader for space-optimized packing.
25pub mod bit_reader;
26pub(crate) mod cbor;
27pub(crate) mod fixed;
28pub mod read;
29
30pub use self::decoder::DecoderImpl;
31
32/// Trait that makes a type able to be decoded, akin to serde's `DeserializeOwned` trait.
33///
34/// Some types may require specific contexts. For example, to decode arena-based collections, an arena allocator must be provided as a context. In these cases, the context type `Context` should be specified or bounded.
35///
36/// This trait should be implemented for types which do not have references to data in the reader. For types that contain e.g. `&str` and `&[u8]`, implement [`BorrowDecode`\] instead.
37///
38/// Whenever you derive `Decode` for your type, the base trait `BorrowDecode` is automatically implemented.
39///
40/// This trait will be automatically implemented with unbounded `Context` if you enable the `derive` feature and add `#[derive(bincode::Decode)]` to your type. Note that if the type contains any lifetimes, `BorrowDecode` will be implemented instead.
41///
42/// # Implementing this trait manually
43///
44/// If you want to implement this trait for your type, the easiest way is to add a `#[derive(bincode::Decode)]`, build and check your `target/generated/bincode/` folder. This should generate a `<Struct name>_Decode.rs` file.
45///
46/// For this struct:
47///
48/// ```
49/// struct Entity {
50///     pub x: f32,
51///     pub y: f32,
52/// }
53/// ```
54///
55/// It will look something like:
56///
57/// ```
58/// # struct Entity {
59/// #     pub x: f32,
60/// #     pub y: f32,
61/// # }
62/// impl<Context> bincode_next::Decode<Context> for Entity {
63///     fn decode<D: bincode_next::de::Decoder<Context = Context>>(
64///         decoder: &mut D
65///     ) -> core::result::Result<Self, bincode_next::error::DecodeError> {
66///         Ok(Self {
67///             x: bincode_next::Decode::decode(decoder)?,
68///             y: bincode_next::Decode::decode(decoder)?,
69///         })
70///     }
71/// }
72/// impl<'de, Context> bincode_next::BorrowDecode<'de, Context> for Entity {
73///     fn borrow_decode<D: bincode_next::de::BorrowDecoder<'de, Context = Context>>(
74///         decoder: &mut D
75///     ) -> core::result::Result<Self, bincode_next::error::DecodeError> {
76///         Ok(Self {
77///             x: bincode_next::BorrowDecode::borrow_decode(decoder)?,
78///             y: bincode_next::BorrowDecode::borrow_decode(decoder)?,
79///         })
80///     }
81/// }
82/// ```
83///
84/// From here you can add/remove fields, or add custom logic.
85///
86/// To get specific integer types, you can use:
87/// ```
88/// # struct Foo;
89/// # impl<Context> bincode_next::Decode<Context> for Foo {
90/// #     fn decode<D: bincode_next::de::Decoder<Context = Context>>(
91/// #         decoder: &mut D,
92/// #     ) -> core::result::Result<Self, bincode_next::error::DecodeError> {
93/// let x: u8 = bincode_next::Decode::<Context>::decode(decoder)?;
94/// let x = <u8 as bincode_next::Decode<Context>>::decode(decoder)?;
95/// #         Ok(Foo)
96/// #     }
97/// # }
98/// # bincode_next::impl_borrow_decode!(Foo);
99/// ```
100///
101/// You can use `Context` to require contexts for decoding a type:
102/// ```
103/// # /// # use bumpalo::Bump;
104/// use bincode_next::de::{Decode, Decoder};
105/// use bincode_next::error::DecodeError;
106/// struct BytesInArena<'a>(bumpalo::collections::Vec<'a, u8>);
107/// impl<'a> bincode_next::Decode<&'a bumpalo::Bump> for BytesInArena<'a> {
108///
109///     fn decode<D: Decoder<Context = &'a bumpalo::Bump>>(decoder: &mut D) -> Result<Self, DecodeError> {
110///         let len = u64::decode(decoder)?;
111///         let len: usize = len.try_into().map_err(|_| DecodeError::OutsideUsizeRange(len))?;
112///         decoder.claim_bytes_read(len)?;
113///         let mut vec = bumpalo::collections::Vec::with_capacity_in(len, decoder.context());
114///         for _ in 0..len {
115///             decoder.unclaim_bytes_read(1);
116///             vec.push(u8::decode(decoder)?);
117///         }
118///         Ok(Self(vec))
119///     }
120/// # }
121/// ```
122pub trait Decode<Context>: Sized {
123    /// Attempt to decode this type with the given [`Decode`\].
124    ///
125    /// # Errors
126    ///
127    /// Returns any error encountered during decoding.
128    fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError>;
129}
130
131/// Trait that makes a type able to be decoded, akin to serde's `Deserialize` trait.
132///
133/// This trait should be implemented for types that contain borrowed data, like `&str` and `&[u8]`. If your type does not have borrowed data, consider implementing [`Decode`\] instead.
134///
135/// This trait will be automatically implemented if you enable the `derive` feature and add `#[derive(bincode::Decode)]` to a type with a lifetime.
136pub trait BorrowDecode<'de, Context>: Sized {
137    /// Attempt to decode this type with the given [`BorrowDecode`\].
138    ///
139    /// # Errors
140    ///
141    /// Returns any error encountered during decoding.
142    fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(
143        decoder: &mut D
144    ) -> Result<Self, DecodeError>;
145}
146
147/// Helper macro to implement `BorrowDecode` for any type that implements `Decode`.
148#[macro_export]
149#[doc(hidden)]
150macro_rules! impl_borrow_decode {
151    ($ty:ty $(, $param:tt)*) => {
152        impl<'de $(, $param)*, __Context> $crate::BorrowDecode<'de, __Context> for $ty {
153            #[inline(always)]
154            fn borrow_decode<D: $crate::de::BorrowDecoder<'de, Context = __Context>>(
155                decoder: &mut D,
156            ) -> core::result::Result<Self, $crate::error::DecodeError> {
157                $crate::Decode::decode(decoder)
158            }
159        }
160    };
161}
162
163/// Helper macro to implement `BorrowDecode` for any type that implements `Decode`.
164#[macro_export]
165#[doc(hidden)]
166macro_rules! impl_borrow_decode_with_context {
167    ($ty:ty, $context:ty $(, $param:tt)*) => {
168        impl<'de $(, $param)*> $crate::BorrowDecode<'de, $context> for $ty {
169            #[inline(always)]
170            fn borrow_decode<D: $crate::de::BorrowDecoder<'de, Context = $context>>(
171                decoder: &mut D,
172            ) -> core::result::Result<Self, $crate::error::DecodeError> {
173                $crate::Decode::decode(decoder)
174            }
175        }
176    };
177}
178
179/// Any source that can decode basic types. This type is most notably implemented for [Decoder].
180pub trait Decoder: Sealed + crate::error_path::BincodeErrorPathCovered<0> {
181    /// The concrete [Reader] type
182    type R: Reader;
183
184    /// The concrete [Config] type
185    type C: Config;
186
187    /// The decoding context type
188    type Context;
189
190    /// Returns the decoding context
191    fn context(&mut self) -> &mut Self::Context;
192
193    /// Wraps decoder with a context
194    #[inline(always)]
195    fn with_context<C>(
196        &mut self,
197        context: C,
198    ) -> WithContext<'_, Self, C> {
199        WithContext {
200            decoder: self,
201            context,
202        }
203    }
204
205    /// Returns a mutable reference to the reader
206    fn reader(&mut self) -> &mut Self::R;
207
208    /// Returns a reference to the config
209    fn config(&self) -> &Self::C;
210
211    /// Claim that `n` bytes are going to be read from the decoder.
212    /// This can be used to validate `Configuration::Limit<N>()`.
213    ///
214    /// # Errors
215    ///
216    /// Returns `DecodeError::LimitExceeded` if the limit is exceeded.
217    fn claim_bytes_read(
218        &mut self,
219        n: usize,
220    ) -> Result<(), DecodeError>;
221
222    /// Claim that we're going to read a container which contains `len` entries of `T`.
223    /// This will correctly handle overflowing if `len * size_of::<T>() > usize::max_value`
224    ///
225    /// # Errors
226    ///
227    /// Returns `DecodeError::LimitExceeded` if the limit is exceeded or if `len * size_of::<T>()` overflows.
228    #[inline(always)]
229    fn claim_container_read<T>(
230        &mut self,
231        len: usize,
232    ) -> Result<(), DecodeError> {
233        Self::assert_covered();
234        if <Self::C as InternalLimitConfig>::LIMIT.is_some() {
235            len.checked_mul(core::mem::size_of::<T>()).map_or_else(
236                || crate::error::cold_decode_error_limit_exceeded(),
237                |val| self.claim_bytes_read(val),
238            )
239        } else {
240            Ok(())
241        }
242    }
243
244    /// Notify the decoder that `n` bytes are being reclaimed.
245    ///
246    /// When decoding container types, a typical implementation would claim to read `len * size_of::<T>()` bytes.
247    /// This is to ensure that bincode won't allocate several GB of memory while constructing the container.
248    ///
249    /// Because the implementation claims `len * size_of::<T>()`, but then has to decode each `T`, this would be marked
250    /// as double. This function allows us to un-claim each `T` that gets decoded.
251    ///
252    /// We cannot check if `len * size_of::<T>()` is valid without claiming it, because this would mean that if you have
253    /// a nested container (e.g. `Vec<Vec<T>>`), it does not know how much memory is already claimed, and could easily
254    /// allocate much more than the user intends.
255    /// ```
256    /// # use bincode_next::de::{Decode, Decoder};
257    /// # use bincode_next::error::DecodeError;
258    /// # struct Container<T>(Vec<T>);
259    /// # impl<T> Container<T> {
260    /// #     fn with_capacity(cap: usize) -> Self {
261    /// #         Self(Vec::with_capacity(cap))
262    /// #     }
263    /// #
264    ///
265    /// #     fn push(&mut self, t: T) {
266    /// #         self.0.push(t);
267    /// #     }
268    /// # }
269    /// impl<Context, T: Decode<Context>> Decode<Context> for Container<T> {
270    ///     fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
271    ///         let len = u64::decode(decoder)?;
272    ///         let len: usize = len
273    ///             .try_into()
274    ///             .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
275    ///         // Make sure we don't allocate too much memory
276    ///         decoder.claim_bytes_read(len * core::mem::size_of::<T>());
277    ///
278    ///         let mut result = Container::with_capacity(len);
279    ///         for _ in 0..len {
280    ///             // un-claim the memory
281    ///             decoder.unclaim_bytes_read(core::mem::size_of::<T>());
282    ///             result.push(T::decode(decoder)?)
283    ///         }
284    ///         Ok(result)
285    ///     }
286    /// }
287    /// impl<'de, Context, T: bincode_next::BorrowDecode<'de, Context>>
288    ///     bincode_next::BorrowDecode<'de, Context> for Container<T>
289    /// {
290    ///     fn borrow_decode<D: bincode_next::de::BorrowDecoder<'de, Context = Context>>(
291    ///         decoder: &mut D
292    ///     ) -> core::result::Result<Self, bincode_next::error::DecodeError> {
293    ///         let len = u64::borrow_decode(decoder)?;
294    ///         let len: usize = len
295    ///             .try_into()
296    ///             .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
297    ///         // Make sure we don't allocate too much memory
298    ///         decoder.claim_bytes_read(len * core::mem::size_of::<T>());
299    ///
300    ///         let mut result = Container::with_capacity(len);
301    ///         for _ in 0..len {
302    ///             // un-claim the memory
303    ///             decoder.unclaim_bytes_read(core::mem::size_of::<T>());
304    ///             result.push(T::borrow_decode(decoder)?)
305    ///         }
306    ///         Ok(result)
307    ///     }
308    /// }
309    /// ```
310    fn unclaim_bytes_read(
311        &mut self,
312        n: usize,
313    );
314
315    /// Decode a `u8` value.
316    ///
317    /// # Errors
318    ///
319    /// Returns an error if the operation fails.
320    #[inline(always)]
321    fn decode_u8(&mut self) -> Result<u8, DecodeError> {
322        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
323            | Format::Bincode | Format::BincodeDeterministic => self.reader().read_u8(),
324            | Format::Cbor | Format::CborDeterministic => cbor::decode_u8(self.reader()),
325        }
326    }
327
328    /// Decode a `u16` value.
329    ///
330    /// # Errors
331    ///
332    /// Returns an error if the operation fails.
333    #[inline(always)]
334    fn decode_u16(&mut self) -> Result<u16, DecodeError> {
335        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
336            | Format::Bincode | Format::BincodeDeterministic => {
337                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
338                    | IntEncoding::Variable => {
339                        crate::varint::varint_decode_u16(
340                            self.reader(),
341                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
342                        )
343                    },
344                    | IntEncoding::Fixed => {
345                        fixed::decode_u16(
346                            self.reader(),
347                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
348                        )
349                    },
350                }
351            },
352            | Format::Cbor | Format::CborDeterministic => cbor::decode_u16(self.reader()),
353        }
354    }
355
356    /// Decode a `u32` value.
357    ///
358    /// # Errors
359    ///
360    /// Returns an error if the operation fails.
361    #[inline(always)]
362    fn decode_u32(&mut self) -> Result<u32, DecodeError> {
363        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
364            | Format::Bincode | Format::BincodeDeterministic => {
365                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
366                    | IntEncoding::Variable => {
367                        crate::varint::varint_decode_u32(
368                            self.reader(),
369                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
370                        )
371                    },
372                    | IntEncoding::Fixed => {
373                        fixed::decode_u32(
374                            self.reader(),
375                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
376                        )
377                    },
378                }
379            },
380            | Format::Cbor | Format::CborDeterministic => cbor::decode_u32(self.reader()),
381        }
382    }
383
384    /// Decode a `u64` value.
385    ///
386    /// # Errors
387    ///
388    /// Returns an error if the operation fails.
389    #[inline(always)]
390    fn decode_u64(&mut self) -> Result<u64, DecodeError> {
391        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
392            | Format::Bincode | Format::BincodeDeterministic => {
393                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
394                    | IntEncoding::Variable => {
395                        crate::varint::varint_decode_u64(
396                            self.reader(),
397                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
398                        )
399                    },
400                    | IntEncoding::Fixed => {
401                        fixed::decode_u64(
402                            self.reader(),
403                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
404                        )
405                    },
406                }
407            },
408            | Format::Cbor | Format::CborDeterministic => cbor::decode_u64(self.reader()),
409        }
410    }
411
412    /// Decode a `u128` value.
413    ///
414    /// # Errors
415    ///
416    /// Returns an error if the operation fails.
417    #[inline(always)]
418    fn decode_u128(&mut self) -> Result<u128, DecodeError> {
419        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
420            | Format::Bincode | Format::BincodeDeterministic => {
421                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
422                    | IntEncoding::Variable => {
423                        crate::varint::varint_decode_u128(
424                            self.reader(),
425                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
426                        )
427                    },
428                    | IntEncoding::Fixed => {
429                        fixed::decode_u128(
430                            self.reader(),
431                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
432                        )
433                    },
434                }
435            },
436            | Format::Cbor | Format::CborDeterministic => cbor::decode_u128(self.reader()),
437        }
438    }
439
440    /// Decode a `usize` value.
441    ///
442    /// # Errors
443    ///
444    /// Returns an error if the operation fails.
445    #[inline(always)]
446    fn decode_usize(&mut self) -> Result<usize, DecodeError> {
447        self.claim_bytes_read(8)?;
448        let v = self.decode_u64()?;
449        v.try_into()
450            .map_err(|_| crate::error::cold_decode_error_outside_usize_range::<()>(v).unwrap_err())
451    }
452
453    /// Decode an `i8` value.
454    ///
455    /// # Errors
456    ///
457    /// Returns an error if the operation fails.
458    #[inline(always)]
459    fn decode_i8(&mut self) -> Result<i8, DecodeError> {
460        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
461            | Format::Bincode | Format::BincodeDeterministic => {
462                self.reader().read_u8().map(|v| v as i8)
463            },
464            | Format::Cbor | Format::CborDeterministic => cbor::decode_i8(self.reader()),
465        }
466    }
467
468    /// Decode an `i16` value.
469    ///
470    /// # Errors
471    ///
472    /// Returns an error if the operation fails.
473    #[inline(always)]
474    fn decode_i16(&mut self) -> Result<i16, DecodeError> {
475        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
476            | Format::Bincode | Format::BincodeDeterministic => {
477                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
478                    | IntEncoding::Variable => {
479                        crate::varint::varint_decode_i16(
480                            self.reader(),
481                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
482                        )
483                    },
484                    | IntEncoding::Fixed => {
485                        fixed::decode_i16(
486                            self.reader(),
487                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
488                        )
489                    },
490                }
491            },
492            | Format::Cbor | Format::CborDeterministic => cbor::decode_i16(self.reader()),
493        }
494    }
495
496    /// Decode an `i32` value.
497    ///
498    /// # Errors
499    ///
500    /// Returns an error if the operation fails.
501    #[inline(always)]
502    fn decode_i32(&mut self) -> Result<i32, DecodeError> {
503        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
504            | Format::Bincode | Format::BincodeDeterministic => {
505                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
506                    | IntEncoding::Variable => {
507                        crate::varint::varint_decode_i32(
508                            self.reader(),
509                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
510                        )
511                    },
512                    | IntEncoding::Fixed => {
513                        fixed::decode_i32(
514                            self.reader(),
515                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
516                        )
517                    },
518                }
519            },
520            | Format::Cbor | Format::CborDeterministic => cbor::decode_i32(self.reader()),
521        }
522    }
523
524    /// Decode an `i64` value.
525    ///
526    /// # Errors
527    ///
528    /// Returns an error if the operation fails.
529    #[inline(always)]
530    fn decode_i64(&mut self) -> Result<i64, DecodeError> {
531        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
532            | Format::Bincode | Format::BincodeDeterministic => {
533                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
534                    | IntEncoding::Variable => {
535                        crate::varint::varint_decode_i64(
536                            self.reader(),
537                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
538                        )
539                    },
540                    | IntEncoding::Fixed => {
541                        fixed::decode_i64(
542                            self.reader(),
543                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
544                        )
545                    },
546                }
547            },
548            | Format::Cbor | Format::CborDeterministic => cbor::decode_i64(self.reader()),
549        }
550    }
551
552    /// Decode an `i128` value.
553    ///
554    /// # Errors
555    ///
556    /// Returns an error if the operation fails.
557    #[inline(always)]
558    fn decode_i128(&mut self) -> Result<i128, DecodeError> {
559        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
560            | Format::Bincode | Format::BincodeDeterministic => {
561                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
562                    | IntEncoding::Variable => {
563                        crate::varint::varint_decode_i128(
564                            self.reader(),
565                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
566                        )
567                    },
568                    | IntEncoding::Fixed => {
569                        fixed::decode_i128(
570                            self.reader(),
571                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
572                        )
573                    },
574                }
575            },
576            | Format::Cbor | Format::CborDeterministic => cbor::decode_i128(self.reader()),
577        }
578    }
579
580    /// Decode an `isize` value.
581    ///
582    /// # Errors
583    ///
584    /// Returns an error if the operation fails.
585    #[inline(always)]
586    fn decode_isize(&mut self) -> Result<isize, DecodeError> {
587        self.claim_bytes_read(8)?;
588        let v = self.decode_i64()?;
589        v.try_into()
590            .map_err(|_| crate::error::cold_decode_error_outside_isize_range::<()>(v).unwrap_err())
591    }
592
593    /// Decode an `f32` value.
594    ///
595    /// # Errors
596    ///
597    /// Returns an error if the operation fails.
598    #[inline(always)]
599    fn decode_f32(&mut self) -> Result<f32, DecodeError> {
600        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
601            | Format::Bincode | Format::BincodeDeterministic => {
602                fixed::decode_f32(
603                    self.reader(),
604                    <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
605                )
606            },
607            | Format::Cbor | Format::CborDeterministic => cbor::decode_f32(self.reader()),
608        }
609    }
610
611    /// Decode an `f64` value.
612    ///
613    /// # Errors
614    ///
615    /// Returns an error if the operation fails.
616    #[inline(always)]
617    fn decode_f64(&mut self) -> Result<f64, DecodeError> {
618        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
619            | Format::Bincode | Format::BincodeDeterministic => {
620                fixed::decode_f64(
621                    self.reader(),
622                    <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
623                )
624            },
625            | Format::Cbor | Format::CborDeterministic => cbor::decode_f64(self.reader()),
626        }
627    }
628
629    /// Decode a `bool` value.
630    ///
631    /// # Errors
632    ///
633    /// Returns an error if the operation fails.
634    #[inline(always)]
635    fn decode_bool(&mut self) -> Result<bool, DecodeError> {
636        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
637            | Format::Bincode | Format::BincodeDeterministic => {
638                match self.reader().read_u8()? {
639                    | 0 => Ok(false),
640                    | 1 => Ok(true),
641                    | x => crate::error::cold_decode_error_invalid_boolean_value(x),
642                }
643            },
644            | Format::Cbor | Format::CborDeterministic => cbor::decode_bool(self.reader()),
645        }
646    }
647
648    /// Decode the length of a slice.
649    ///
650    /// # Errors
651    ///
652    /// Returns an error if the operation fails.
653    #[inline(always)]
654    fn decode_slice_len(&mut self) -> Result<usize, DecodeError> {
655        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
656            | Format::Bincode | Format::BincodeDeterministic => {
657                self.claim_bytes_read(8)?;
658                let v = self.decode_u64()?;
659                v.try_into().map_err(|_| {
660                    crate::error::cold_decode_error_outside_usize_range::<()>(v).unwrap_err()
661                })
662            },
663            | Format::Cbor | Format::CborDeterministic => {
664                self.claim_bytes_read(9)?;
665                cbor::decode_slice_len(self.reader())
666            },
667        }
668    }
669
670    /// Decode the length of an array.
671    ///
672    /// # Errors
673    ///
674    /// Returns an error if the operation fails.
675    #[inline(always)]
676    fn decode_array_len(&mut self) -> Result<usize, DecodeError> {
677        self.decode_slice_len()
678    }
679
680    /// Decode the length of a map.
681    ///
682    /// # Errors
683    ///
684    /// Returns an error if the operation fails.
685    #[inline(always)]
686    fn decode_map_len(&mut self) -> Result<usize, DecodeError> {
687        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
688            | Format::Bincode | Format::BincodeDeterministic => self.decode_slice_len(),
689            | Format::Cbor | Format::CborDeterministic => {
690                self.claim_bytes_read(9)?;
691                cbor::decode_map_len(self.reader())
692            },
693        }
694    }
695
696    /// Decode an enum variant index.
697    ///
698    /// # Errors
699    ///
700    /// Returns `DecodeError` if the encoding fails.
701    #[inline(always)]
702    fn decode_variant_index(&mut self) -> Result<u32, DecodeError> {
703        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
704            | Format::Bincode | Format::BincodeDeterministic => {
705                self.claim_bytes_read(1)?;
706                self.decode_u8().map(u32::from)
707            },
708            | Format::Cbor | Format::CborDeterministic => {
709                self.claim_bytes_read(5)?;
710                cbor::decode_u32(self.reader())
711            },
712        }
713    }
714
715    /// Decode the length of a byte slice (Major Type 2 in CBOR).
716    ///
717    /// # Errors
718    ///
719    /// Returns `DecodeError` if the encoding fails.
720    #[inline(always)]
721    fn decode_byte_slice_len(&mut self) -> Result<usize, DecodeError> {
722        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
723            | Format::Bincode | Format::BincodeDeterministic => self.decode_slice_len(),
724            | Format::Cbor | Format::CborDeterministic => {
725                self.claim_bytes_read(9)?;
726                cbor::decode_byte_slice_len(self.reader())
727            },
728        }
729    }
730
731    /// Decode the length of a byte slice or an array (Major Type 2 or 4 in CBOR).
732    ///
733    /// # Errors
734    ///
735    /// Returns `DecodeError` if the encoding fails.
736    #[inline(always)]
737    fn decode_byte_slice_or_array_len(&mut self) -> Result<(u8, usize), DecodeError> {
738        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
739            | Format::Bincode | Format::BincodeDeterministic => {
740                self.decode_slice_len().map(|len| (0, len))
741            },
742            | Format::Cbor | Format::CborDeterministic => {
743                self.claim_bytes_read(9)?;
744                cbor::decode_byte_slice_or_array_len(self.reader())
745            },
746        }
747    }
748
749    /// Decode the length of a string (Major Type 3 in CBOR).
750    ///
751    /// # Errors
752    ///
753    /// Returns `DecodeError` if the encoding fails.
754    #[inline(always)]
755    fn decode_str_len(&mut self) -> Result<usize, DecodeError> {
756        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
757            | Format::Bincode | Format::BincodeDeterministic => self.decode_slice_len(),
758            | Format::Cbor | Format::CborDeterministic => {
759                self.claim_bytes_read(9)?;
760                cbor::decode_str_len(self.reader())
761            },
762        }
763    }
764
765    /// Decode the header for a struct.
766    ///
767    /// # Errors
768    ///
769    /// Returns `DecodeError` if the encoding fails.
770    #[inline(always)]
771    fn decode_struct_header(
772        &mut self,
773        _len: usize,
774    ) -> Result<(), DecodeError> {
775        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
776            | Format::Bincode | Format::BincodeDeterministic => Ok(()),
777            | Format::Cbor | Format::CborDeterministic => {
778                let actual_len = cbor::decode_slice_len(self.reader())?;
779                if actual_len != _len && actual_len != usize::MAX {
780                    return crate::error::cold_decode_error_other("struct length mismatch");
781                }
782                Ok(())
783            },
784        }
785    }
786}
787
788/// Any source that can decode basic types. This type is most notably implemented for [Decoder].
789///
790/// This is an extension of [Decode] that can also return borrowed data.
791pub trait BorrowDecoder<'de>: Decoder {
792    /// The concrete [`BorrowReader`\] type
793    type BR: BorrowReader<'de>;
794
795    /// Returns a mutable reference to the borrow reader
796    fn borrow_reader(&mut self) -> &mut Self::BR;
797}
798
799impl<T> crate::error_path::BincodeErrorPathCovered<0> for &mut T where
800    T: crate::error_path::BincodeErrorPathCovered<0>
801{
802}
803
804impl<T> Decoder for &mut T
805where
806    T: Decoder,
807{
808    type C = T::C;
809    type Context = T::Context;
810    type R = T::R;
811
812    #[inline(always)]
813    fn reader(&mut self) -> &mut Self::R {
814        T::reader(self)
815    }
816
817    #[inline(always)]
818    fn config(&self) -> &Self::C {
819        T::config(self)
820    }
821
822    #[inline(always)]
823    fn claim_bytes_read(
824        &mut self,
825        n: usize,
826    ) -> Result<(), DecodeError> {
827        T::claim_bytes_read(self, n)
828    }
829
830    #[inline(always)]
831    fn unclaim_bytes_read(
832        &mut self,
833        n: usize,
834    ) {
835        T::unclaim_bytes_read(self, n);
836    }
837
838    #[inline(always)]
839    fn context(&mut self) -> &mut Self::Context {
840        T::context(self)
841    }
842
843    #[inline(always)]
844    fn decode_u8(&mut self) -> Result<u8, DecodeError> {
845        T::decode_u8(self)
846    }
847
848    #[inline(always)]
849    fn decode_u16(&mut self) -> Result<u16, DecodeError> {
850        T::decode_u16(self)
851    }
852
853    #[inline(always)]
854    fn decode_u32(&mut self) -> Result<u32, DecodeError> {
855        T::decode_u32(self)
856    }
857
858    #[inline(always)]
859    fn decode_u64(&mut self) -> Result<u64, DecodeError> {
860        T::decode_u64(self)
861    }
862
863    #[inline(always)]
864    fn decode_u128(&mut self) -> Result<u128, DecodeError> {
865        T::decode_u128(self)
866    }
867
868    #[inline(always)]
869    fn decode_usize(&mut self) -> Result<usize, DecodeError> {
870        T::decode_usize(self)
871    }
872
873    #[inline(always)]
874    fn decode_i8(&mut self) -> Result<i8, DecodeError> {
875        T::decode_i8(self)
876    }
877
878    #[inline(always)]
879    fn decode_i16(&mut self) -> Result<i16, DecodeError> {
880        T::decode_i16(self)
881    }
882
883    #[inline(always)]
884    fn decode_i32(&mut self) -> Result<i32, DecodeError> {
885        T::decode_i32(self)
886    }
887
888    #[inline(always)]
889    fn decode_i64(&mut self) -> Result<i64, DecodeError> {
890        T::decode_i64(self)
891    }
892
893    #[inline(always)]
894    fn decode_i128(&mut self) -> Result<i128, DecodeError> {
895        T::decode_i128(self)
896    }
897
898    #[inline(always)]
899    fn decode_isize(&mut self) -> Result<isize, DecodeError> {
900        T::decode_isize(self)
901    }
902
903    #[inline(always)]
904    fn decode_f32(&mut self) -> Result<f32, DecodeError> {
905        T::decode_f32(self)
906    }
907
908    #[inline(always)]
909    fn decode_f64(&mut self) -> Result<f64, DecodeError> {
910        T::decode_f64(self)
911    }
912
913    #[inline(always)]
914    fn decode_bool(&mut self) -> Result<bool, DecodeError> {
915        T::decode_bool(self)
916    }
917
918    #[inline(always)]
919    fn decode_slice_len(&mut self) -> Result<usize, DecodeError> {
920        T::decode_slice_len(self)
921    }
922
923    #[inline(always)]
924    fn decode_array_len(&mut self) -> Result<usize, DecodeError> {
925        T::decode_array_len(self)
926    }
927
928    #[inline(always)]
929    fn decode_map_len(&mut self) -> Result<usize, DecodeError> {
930        T::decode_map_len(self)
931    }
932
933    #[inline(always)]
934    fn decode_variant_index(&mut self) -> Result<u32, DecodeError> {
935        T::decode_variant_index(self)
936    }
937
938    #[inline(always)]
939    fn decode_byte_slice_len(&mut self) -> Result<usize, DecodeError> {
940        T::decode_byte_slice_len(self)
941    }
942
943    #[inline(always)]
944    fn decode_str_len(&mut self) -> Result<usize, DecodeError> {
945        T::decode_str_len(self)
946    }
947
948    #[inline(always)]
949    fn decode_struct_header(
950        &mut self,
951        len: usize,
952    ) -> Result<(), DecodeError> {
953        T::decode_struct_header(self, len)
954    }
955}
956
957impl<'de, T> BorrowDecoder<'de> for &mut T
958where
959    T: BorrowDecoder<'de>,
960{
961    type BR = T::BR;
962
963    #[inline(always)]
964    fn borrow_reader(&mut self) -> &mut Self::BR {
965        T::borrow_reader(self)
966    }
967}
968
969/// Decodes only the option variant from the decoder. Will not read any more data than that.
970///
971/// # Errors
972///
973/// Returns `DecodeError` if the encoding fails.
974#[inline(always)]
975pub(crate) fn decode_option_variant<D: Decoder>(
976    decoder: &mut D,
977    type_name: &'static str,
978) -> Result<Option<()>, DecodeError> {
979    D::assert_covered();
980    let is_some = u8::decode(decoder)?;
981    match is_some {
982        | 0 => Ok(None),
983        | 1 => Ok(Some(())),
984        | x => {
985            crate::error::cold_decode_error_unexpected_variant(
986                type_name,
987                &crate::error::AllowedEnumVariants::Range { max: 1, min: 0 },
988                u32::from(x),
989            )
990        },
991    }
992}
993
994/// Decodes the length of any slice, container, etc from the decoder
995///
996/// # Errors
997///
998/// Returns an error if the operation fails.
999#[inline(always)]
1000#[allow(dead_code)]
1001pub(crate) fn decode_slice_len<D: Decoder>(decoder: &mut D) -> Result<usize, DecodeError> {
1002    D::assert_covered();
1003    decoder.decode_slice_len()
1004}