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/// Accounts for one element of an indefinite-length (CBOR) container.
180///
181/// Definite-length containers claim `len * size_of::<T>()` up front. Indefinite ones
182/// have no length, so each element's in-memory size is claimed as it is decoded;
183/// otherwise a compact indefinite encoding (1 wire byte per element) could be
184/// accepted under a limit that the equivalent definite encoding would exceed.
185/// One-byte elements are already charged exactly by their own decode.
186#[inline(always)]
187pub(crate) fn claim_indefinite_item<T, D: Decoder + ?Sized>(
188    decoder: &mut D
189) -> Result<(), DecodeError> {
190    if core::mem::size_of::<T>() > 1 {
191        decoder.claim_container_read::<T>(1)
192    } else {
193        Ok(())
194    }
195}
196
197/// Any source that can decode basic types. This type is most notably implemented for [Decoder].
198pub trait Decoder: Sealed + crate::error_path::BincodeErrorPathCovered<0> {
199    /// The concrete [Reader] type
200    type R: Reader;
201
202    /// The concrete [Config] type
203    type C: Config;
204
205    /// The decoding context type
206    type Context;
207
208    /// Returns the decoding context
209    fn context(&mut self) -> &mut Self::Context;
210
211    /// Wraps decoder with a context
212    #[inline(always)]
213    fn with_context<C>(
214        &mut self,
215        context: C,
216    ) -> WithContext<'_, Self, C> {
217        WithContext {
218            decoder: self,
219            context,
220        }
221    }
222
223    /// Returns a mutable reference to the reader
224    fn reader(&mut self) -> &mut Self::R;
225
226    /// Returns a reference to the config
227    fn config(&self) -> &Self::C;
228
229    /// Claim that `n` bytes are going to be read from the decoder.
230    /// This can be used to validate `Configuration::Limit<N>()`.
231    ///
232    /// # Errors
233    ///
234    /// Returns `DecodeError::LimitExceeded` if the limit is exceeded.
235    fn claim_bytes_read(
236        &mut self,
237        n: usize,
238    ) -> Result<(), DecodeError>;
239
240    /// Claim that we're going to read a container which contains `len` entries of `T`.
241    /// This will correctly handle overflowing if `len * size_of::<T>() > usize::max_value`
242    ///
243    /// # Errors
244    ///
245    /// Returns `DecodeError::LimitExceeded` if the limit is exceeded or if `len * size_of::<T>()` overflows.
246    #[inline(always)]
247    fn claim_container_read<T>(
248        &mut self,
249        len: usize,
250    ) -> Result<(), DecodeError> {
251        Self::assert_covered();
252        if <Self::C as InternalLimitConfig>::LIMIT.is_some() {
253            len.checked_mul(core::mem::size_of::<T>()).map_or_else(
254                || crate::error::cold_decode_error_limit_exceeded(),
255                |val| self.claim_bytes_read(val),
256            )
257        } else {
258            Ok(())
259        }
260    }
261
262    /// Notify the decoder that `n` bytes are being reclaimed.
263    ///
264    /// When decoding container types, a typical implementation would claim to read `len * size_of::<T>()` bytes.
265    /// This is to ensure that bincode won't allocate several GB of memory while constructing the container.
266    ///
267    /// Because the implementation claims `len * size_of::<T>()`, but then has to decode each `T`, this would be marked
268    /// as double. This function allows us to un-claim each `T` that gets decoded.
269    ///
270    /// We cannot check if `len * size_of::<T>()` is valid without claiming it, because this would mean that if you have
271    /// a nested container (e.g. `Vec<Vec<T>>`), it does not know how much memory is already claimed, and could easily
272    /// allocate much more than the user intends.
273    /// ```
274    /// # use bincode_next::de::{Decode, Decoder};
275    /// # use bincode_next::error::DecodeError;
276    /// # struct Container<T>(Vec<T>);
277    /// # impl<T> Container<T> {
278    /// #     fn with_capacity(cap: usize) -> Self {
279    /// #         Self(Vec::with_capacity(cap))
280    /// #     }
281    /// #
282    ///
283    /// #     fn push(&mut self, t: T) {
284    /// #         self.0.push(t);
285    /// #     }
286    /// # }
287    /// impl<Context, T: Decode<Context>> Decode<Context> for Container<T> {
288    ///     fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
289    ///         let len = u64::decode(decoder)?;
290    ///         let len: usize = len
291    ///             .try_into()
292    ///             .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
293    ///         // Make sure we don't allocate too much memory
294    ///         decoder.claim_bytes_read(len * core::mem::size_of::<T>());
295    ///
296    ///         let mut result = Container::with_capacity(len);
297    ///         for _ in 0..len {
298    ///             // un-claim the memory
299    ///             decoder.unclaim_bytes_read(core::mem::size_of::<T>());
300    ///             result.push(T::decode(decoder)?)
301    ///         }
302    ///         Ok(result)
303    ///     }
304    /// }
305    /// impl<'de, Context, T: bincode_next::BorrowDecode<'de, Context>>
306    ///     bincode_next::BorrowDecode<'de, Context> for Container<T>
307    /// {
308    ///     fn borrow_decode<D: bincode_next::de::BorrowDecoder<'de, Context = Context>>(
309    ///         decoder: &mut D
310    ///     ) -> core::result::Result<Self, bincode_next::error::DecodeError> {
311    ///         let len = u64::borrow_decode(decoder)?;
312    ///         let len: usize = len
313    ///             .try_into()
314    ///             .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
315    ///         // Make sure we don't allocate too much memory
316    ///         decoder.claim_bytes_read(len * core::mem::size_of::<T>());
317    ///
318    ///         let mut result = Container::with_capacity(len);
319    ///         for _ in 0..len {
320    ///             // un-claim the memory
321    ///             decoder.unclaim_bytes_read(core::mem::size_of::<T>());
322    ///             result.push(T::borrow_decode(decoder)?)
323    ///         }
324    ///         Ok(result)
325    ///     }
326    /// }
327    /// ```
328    fn unclaim_bytes_read(
329        &mut self,
330        n: usize,
331    );
332
333    /// Decode a `u8` value.
334    ///
335    /// # Errors
336    ///
337    /// Returns an error if the operation fails.
338    #[inline(always)]
339    fn decode_u8(&mut self) -> Result<u8, DecodeError> {
340        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
341            | Format::Bincode | Format::BincodeDeterministic => self.reader().read_u8(),
342            | Format::Cbor | Format::CborDeterministic => cbor::decode_u8(self.reader()),
343        }
344    }
345
346    /// Decode a `u16` value.
347    ///
348    /// # Errors
349    ///
350    /// Returns an error if the operation fails.
351    #[inline(always)]
352    fn decode_u16(&mut self) -> Result<u16, DecodeError> {
353        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
354            | Format::Bincode | Format::BincodeDeterministic => {
355                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
356                    | IntEncoding::Variable => {
357                        crate::varint::varint_decode_u16(
358                            self.reader(),
359                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
360                        )
361                    },
362                    | IntEncoding::Fixed => {
363                        fixed::decode_u16(
364                            self.reader(),
365                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
366                        )
367                    },
368                }
369            },
370            | Format::Cbor | Format::CborDeterministic => cbor::decode_u16(self.reader()),
371        }
372    }
373
374    /// Decode a `u32` value.
375    ///
376    /// # Errors
377    ///
378    /// Returns an error if the operation fails.
379    #[inline(always)]
380    fn decode_u32(&mut self) -> Result<u32, DecodeError> {
381        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
382            | Format::Bincode | Format::BincodeDeterministic => {
383                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
384                    | IntEncoding::Variable => {
385                        crate::varint::varint_decode_u32(
386                            self.reader(),
387                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
388                        )
389                    },
390                    | IntEncoding::Fixed => {
391                        fixed::decode_u32(
392                            self.reader(),
393                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
394                        )
395                    },
396                }
397            },
398            | Format::Cbor | Format::CborDeterministic => cbor::decode_u32(self.reader()),
399        }
400    }
401
402    /// Decode a `u64` value.
403    ///
404    /// # Errors
405    ///
406    /// Returns an error if the operation fails.
407    #[inline(always)]
408    fn decode_u64(&mut self) -> Result<u64, DecodeError> {
409        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
410            | Format::Bincode | Format::BincodeDeterministic => {
411                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
412                    | IntEncoding::Variable => {
413                        crate::varint::varint_decode_u64(
414                            self.reader(),
415                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
416                        )
417                    },
418                    | IntEncoding::Fixed => {
419                        fixed::decode_u64(
420                            self.reader(),
421                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
422                        )
423                    },
424                }
425            },
426            | Format::Cbor | Format::CborDeterministic => cbor::decode_u64(self.reader()),
427        }
428    }
429
430    /// Decode a `u128` value.
431    ///
432    /// # Errors
433    ///
434    /// Returns an error if the operation fails.
435    #[inline(always)]
436    fn decode_u128(&mut self) -> Result<u128, DecodeError> {
437        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
438            | Format::Bincode | Format::BincodeDeterministic => {
439                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
440                    | IntEncoding::Variable => {
441                        crate::varint::varint_decode_u128(
442                            self.reader(),
443                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
444                        )
445                    },
446                    | IntEncoding::Fixed => {
447                        fixed::decode_u128(
448                            self.reader(),
449                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
450                        )
451                    },
452                }
453            },
454            | Format::Cbor | Format::CborDeterministic => cbor::decode_u128(self.reader()),
455        }
456    }
457
458    /// Decode a `usize` value.
459    ///
460    /// # Errors
461    ///
462    /// Returns an error if the operation fails.
463    #[inline(always)]
464    fn decode_usize(&mut self) -> Result<usize, DecodeError> {
465        self.claim_bytes_read(8)?;
466        let v = self.decode_u64()?;
467        v.try_into()
468            .map_err(|_| crate::error::cold_decode_error_outside_usize_range::<()>(v).unwrap_err())
469    }
470
471    /// Decode an `i8` value.
472    ///
473    /// # Errors
474    ///
475    /// Returns an error if the operation fails.
476    #[inline(always)]
477    fn decode_i8(&mut self) -> Result<i8, DecodeError> {
478        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
479            | Format::Bincode | Format::BincodeDeterministic => {
480                self.reader().read_u8().map(|v| v as i8)
481            },
482            | Format::Cbor | Format::CborDeterministic => cbor::decode_i8(self.reader()),
483        }
484    }
485
486    /// Decode an `i16` value.
487    ///
488    /// # Errors
489    ///
490    /// Returns an error if the operation fails.
491    #[inline(always)]
492    fn decode_i16(&mut self) -> Result<i16, DecodeError> {
493        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
494            | Format::Bincode | Format::BincodeDeterministic => {
495                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
496                    | IntEncoding::Variable => {
497                        crate::varint::varint_decode_i16(
498                            self.reader(),
499                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
500                        )
501                    },
502                    | IntEncoding::Fixed => {
503                        fixed::decode_i16(
504                            self.reader(),
505                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
506                        )
507                    },
508                }
509            },
510            | Format::Cbor | Format::CborDeterministic => cbor::decode_i16(self.reader()),
511        }
512    }
513
514    /// Decode an `i32` value.
515    ///
516    /// # Errors
517    ///
518    /// Returns an error if the operation fails.
519    #[inline(always)]
520    fn decode_i32(&mut self) -> Result<i32, DecodeError> {
521        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
522            | Format::Bincode | Format::BincodeDeterministic => {
523                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
524                    | IntEncoding::Variable => {
525                        crate::varint::varint_decode_i32(
526                            self.reader(),
527                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
528                        )
529                    },
530                    | IntEncoding::Fixed => {
531                        fixed::decode_i32(
532                            self.reader(),
533                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
534                        )
535                    },
536                }
537            },
538            | Format::Cbor | Format::CborDeterministic => cbor::decode_i32(self.reader()),
539        }
540    }
541
542    /// Decode an `i64` value.
543    ///
544    /// # Errors
545    ///
546    /// Returns an error if the operation fails.
547    #[inline(always)]
548    fn decode_i64(&mut self) -> Result<i64, DecodeError> {
549        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
550            | Format::Bincode | Format::BincodeDeterministic => {
551                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
552                    | IntEncoding::Variable => {
553                        crate::varint::varint_decode_i64(
554                            self.reader(),
555                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
556                        )
557                    },
558                    | IntEncoding::Fixed => {
559                        fixed::decode_i64(
560                            self.reader(),
561                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
562                        )
563                    },
564                }
565            },
566            | Format::Cbor | Format::CborDeterministic => cbor::decode_i64(self.reader()),
567        }
568    }
569
570    /// Decode an `i128` value.
571    ///
572    /// # Errors
573    ///
574    /// Returns an error if the operation fails.
575    #[inline(always)]
576    fn decode_i128(&mut self) -> Result<i128, DecodeError> {
577        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
578            | Format::Bincode | Format::BincodeDeterministic => {
579                match <Self::C as crate::config::InternalIntEncodingConfig>::INT_ENCODING {
580                    | IntEncoding::Variable => {
581                        crate::varint::varint_decode_i128(
582                            self.reader(),
583                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
584                        )
585                    },
586                    | IntEncoding::Fixed => {
587                        fixed::decode_i128(
588                            self.reader(),
589                            <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
590                        )
591                    },
592                }
593            },
594            | Format::Cbor | Format::CborDeterministic => cbor::decode_i128(self.reader()),
595        }
596    }
597
598    /// Decode an `isize` value.
599    ///
600    /// # Errors
601    ///
602    /// Returns an error if the operation fails.
603    #[inline(always)]
604    fn decode_isize(&mut self) -> Result<isize, DecodeError> {
605        self.claim_bytes_read(8)?;
606        let v = self.decode_i64()?;
607        v.try_into()
608            .map_err(|_| crate::error::cold_decode_error_outside_isize_range::<()>(v).unwrap_err())
609    }
610
611    /// Decode an `f32` value.
612    ///
613    /// # Errors
614    ///
615    /// Returns an error if the operation fails.
616    #[inline(always)]
617    fn decode_f32(&mut self) -> Result<f32, DecodeError> {
618        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
619            | Format::Bincode | Format::BincodeDeterministic => {
620                fixed::decode_f32(
621                    self.reader(),
622                    <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
623                )
624            },
625            | Format::Cbor | Format::CborDeterministic => cbor::decode_f32(self.reader()),
626        }
627    }
628
629    /// Decode an `f64` value.
630    ///
631    /// # Errors
632    ///
633    /// Returns an error if the operation fails.
634    #[inline(always)]
635    fn decode_f64(&mut self) -> Result<f64, DecodeError> {
636        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
637            | Format::Bincode | Format::BincodeDeterministic => {
638                fixed::decode_f64(
639                    self.reader(),
640                    <Self::C as crate::config::InternalEndianConfig>::ENDIAN,
641                )
642            },
643            | Format::Cbor | Format::CborDeterministic => cbor::decode_f64(self.reader()),
644        }
645    }
646
647    /// Decode a `bool` value.
648    ///
649    /// # Errors
650    ///
651    /// Returns an error if the operation fails.
652    #[inline(always)]
653    fn decode_bool(&mut self) -> Result<bool, DecodeError> {
654        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
655            | Format::Bincode | Format::BincodeDeterministic => {
656                match self.reader().read_u8()? {
657                    | 0 => Ok(false),
658                    | 1 => Ok(true),
659                    | x => crate::error::cold_decode_error_invalid_boolean_value(x),
660                }
661            },
662            | Format::Cbor | Format::CborDeterministic => cbor::decode_bool(self.reader()),
663        }
664    }
665
666    /// Decode the length of a slice.
667    ///
668    /// # Errors
669    ///
670    /// Returns an error if the operation fails.
671    #[inline(always)]
672    fn decode_slice_len(&mut self) -> Result<usize, DecodeError> {
673        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
674            | Format::Bincode | Format::BincodeDeterministic => {
675                self.claim_bytes_read(8)?;
676                let v = self.decode_u64()?;
677                v.try_into().map_err(|_| {
678                    crate::error::cold_decode_error_outside_usize_range::<()>(v).unwrap_err()
679                })
680            },
681            | Format::Cbor | Format::CborDeterministic => {
682                self.claim_bytes_read(9)?;
683                cbor::decode_slice_len(self.reader())
684            },
685        }
686    }
687
688    /// Decode the length of an array.
689    ///
690    /// # Errors
691    ///
692    /// Returns an error if the operation fails.
693    #[inline(always)]
694    fn decode_array_len(&mut self) -> Result<usize, DecodeError> {
695        self.decode_slice_len()
696    }
697
698    /// Decode the length of a map.
699    ///
700    /// # Errors
701    ///
702    /// Returns an error if the operation fails.
703    #[inline(always)]
704    fn decode_map_len(&mut self) -> Result<usize, DecodeError> {
705        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
706            | Format::Bincode | Format::BincodeDeterministic => self.decode_slice_len(),
707            | Format::Cbor | Format::CborDeterministic => {
708                self.claim_bytes_read(9)?;
709                cbor::decode_map_len(self.reader())
710            },
711        }
712    }
713
714    /// Decode an enum variant index.
715    ///
716    /// # Errors
717    ///
718    /// Returns `DecodeError` if the encoding fails.
719    #[inline(always)]
720    fn decode_variant_index(&mut self) -> Result<u32, DecodeError> {
721        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
722            // Enum discriminants are `u32` (see docs/spec.md).
723            | Format::Bincode | Format::BincodeDeterministic => self.decode_u32(),
724            | Format::Cbor | Format::CborDeterministic => {
725                self.claim_bytes_read(5)?;
726                cbor::decode_u32(self.reader())
727            },
728        }
729    }
730
731    /// Decode the length of a byte slice (Major Type 2 in CBOR).
732    ///
733    /// # Errors
734    ///
735    /// Returns `DecodeError` if the encoding fails.
736    #[inline(always)]
737    fn decode_byte_slice_len(&mut self) -> Result<usize, DecodeError> {
738        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
739            | Format::Bincode | Format::BincodeDeterministic => self.decode_slice_len(),
740            | Format::Cbor | Format::CborDeterministic => {
741                self.claim_bytes_read(9)?;
742                cbor::decode_byte_slice_len(self.reader())
743            },
744        }
745    }
746
747    /// Decode the length of a byte slice or an array (Major Type 2 or 4 in CBOR).
748    ///
749    /// # Errors
750    ///
751    /// Returns `DecodeError` if the encoding fails.
752    #[inline(always)]
753    fn decode_byte_slice_or_array_len(&mut self) -> Result<(u8, usize), DecodeError> {
754        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
755            | Format::Bincode | Format::BincodeDeterministic => {
756                self.decode_slice_len().map(|len| (0, len))
757            },
758            | Format::Cbor | Format::CborDeterministic => {
759                self.claim_bytes_read(9)?;
760                cbor::decode_byte_slice_or_array_len(self.reader())
761            },
762        }
763    }
764
765    /// Decode the length of a string (Major Type 3 in CBOR).
766    ///
767    /// # Errors
768    ///
769    /// Returns `DecodeError` if the encoding fails.
770    #[inline(always)]
771    fn decode_str_len(&mut self) -> Result<usize, DecodeError> {
772        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
773            | Format::Bincode | Format::BincodeDeterministic => self.decode_slice_len(),
774            | Format::Cbor | Format::CborDeterministic => {
775                self.claim_bytes_read(9)?;
776                cbor::decode_str_len(self.reader())
777            },
778        }
779    }
780
781    /// Decode the header for a struct.
782    ///
783    /// # Errors
784    ///
785    /// Returns `DecodeError` if the encoding fails.
786    #[inline(always)]
787    fn decode_struct_header(
788        &mut self,
789        _len: usize,
790    ) -> Result<(), DecodeError> {
791        match <Self::C as crate::config::InternalFormatConfig>::FORMAT {
792            | Format::Bincode | Format::BincodeDeterministic => Ok(()),
793            | Format::Cbor | Format::CborDeterministic => {
794                let actual_len = cbor::decode_slice_len(self.reader())?;
795                if actual_len != _len && actual_len != usize::MAX {
796                    return crate::error::cold_decode_error_other("struct length mismatch");
797                }
798                Ok(())
799            },
800        }
801    }
802}
803
804/// Any source that can decode basic types. This type is most notably implemented for [Decoder].
805///
806/// This is an extension of [Decode] that can also return borrowed data.
807pub trait BorrowDecoder<'de>: Decoder {
808    /// The concrete [`BorrowReader`\] type
809    type BR: BorrowReader<'de>;
810
811    /// Returns a mutable reference to the borrow reader
812    fn borrow_reader(&mut self) -> &mut Self::BR;
813}
814
815impl<T> crate::error_path::BincodeErrorPathCovered<0> for &mut T where
816    T: crate::error_path::BincodeErrorPathCovered<0>
817{
818}
819
820impl<T> Decoder for &mut T
821where
822    T: Decoder,
823{
824    type C = T::C;
825    type Context = T::Context;
826    type R = T::R;
827
828    #[inline(always)]
829    fn reader(&mut self) -> &mut Self::R {
830        T::reader(self)
831    }
832
833    #[inline(always)]
834    fn config(&self) -> &Self::C {
835        T::config(self)
836    }
837
838    #[inline(always)]
839    fn claim_bytes_read(
840        &mut self,
841        n: usize,
842    ) -> Result<(), DecodeError> {
843        T::claim_bytes_read(self, n)
844    }
845
846    #[inline(always)]
847    fn unclaim_bytes_read(
848        &mut self,
849        n: usize,
850    ) {
851        T::unclaim_bytes_read(self, n);
852    }
853
854    #[inline(always)]
855    fn context(&mut self) -> &mut Self::Context {
856        T::context(self)
857    }
858
859    #[inline(always)]
860    fn decode_u8(&mut self) -> Result<u8, DecodeError> {
861        T::decode_u8(self)
862    }
863
864    #[inline(always)]
865    fn decode_u16(&mut self) -> Result<u16, DecodeError> {
866        T::decode_u16(self)
867    }
868
869    #[inline(always)]
870    fn decode_u32(&mut self) -> Result<u32, DecodeError> {
871        T::decode_u32(self)
872    }
873
874    #[inline(always)]
875    fn decode_u64(&mut self) -> Result<u64, DecodeError> {
876        T::decode_u64(self)
877    }
878
879    #[inline(always)]
880    fn decode_u128(&mut self) -> Result<u128, DecodeError> {
881        T::decode_u128(self)
882    }
883
884    #[inline(always)]
885    fn decode_usize(&mut self) -> Result<usize, DecodeError> {
886        T::decode_usize(self)
887    }
888
889    #[inline(always)]
890    fn decode_i8(&mut self) -> Result<i8, DecodeError> {
891        T::decode_i8(self)
892    }
893
894    #[inline(always)]
895    fn decode_i16(&mut self) -> Result<i16, DecodeError> {
896        T::decode_i16(self)
897    }
898
899    #[inline(always)]
900    fn decode_i32(&mut self) -> Result<i32, DecodeError> {
901        T::decode_i32(self)
902    }
903
904    #[inline(always)]
905    fn decode_i64(&mut self) -> Result<i64, DecodeError> {
906        T::decode_i64(self)
907    }
908
909    #[inline(always)]
910    fn decode_i128(&mut self) -> Result<i128, DecodeError> {
911        T::decode_i128(self)
912    }
913
914    #[inline(always)]
915    fn decode_isize(&mut self) -> Result<isize, DecodeError> {
916        T::decode_isize(self)
917    }
918
919    #[inline(always)]
920    fn decode_f32(&mut self) -> Result<f32, DecodeError> {
921        T::decode_f32(self)
922    }
923
924    #[inline(always)]
925    fn decode_f64(&mut self) -> Result<f64, DecodeError> {
926        T::decode_f64(self)
927    }
928
929    #[inline(always)]
930    fn decode_bool(&mut self) -> Result<bool, DecodeError> {
931        T::decode_bool(self)
932    }
933
934    #[inline(always)]
935    fn decode_slice_len(&mut self) -> Result<usize, DecodeError> {
936        T::decode_slice_len(self)
937    }
938
939    #[inline(always)]
940    fn decode_array_len(&mut self) -> Result<usize, DecodeError> {
941        T::decode_array_len(self)
942    }
943
944    #[inline(always)]
945    fn decode_map_len(&mut self) -> Result<usize, DecodeError> {
946        T::decode_map_len(self)
947    }
948
949    #[inline(always)]
950    fn decode_variant_index(&mut self) -> Result<u32, DecodeError> {
951        T::decode_variant_index(self)
952    }
953
954    #[inline(always)]
955    fn decode_byte_slice_len(&mut self) -> Result<usize, DecodeError> {
956        T::decode_byte_slice_len(self)
957    }
958
959    #[inline(always)]
960    fn decode_str_len(&mut self) -> Result<usize, DecodeError> {
961        T::decode_str_len(self)
962    }
963
964    #[inline(always)]
965    fn decode_struct_header(
966        &mut self,
967        len: usize,
968    ) -> Result<(), DecodeError> {
969        T::decode_struct_header(self, len)
970    }
971}
972
973impl<'de, T> BorrowDecoder<'de> for &mut T
974where
975    T: BorrowDecoder<'de>,
976{
977    type BR = T::BR;
978
979    #[inline(always)]
980    fn borrow_reader(&mut self) -> &mut Self::BR {
981        T::borrow_reader(self)
982    }
983}
984
985/// Decodes only the option variant from the decoder. Will not read any more data than that.
986///
987/// # Errors
988///
989/// Returns `DecodeError` if the encoding fails.
990#[inline(always)]
991pub(crate) fn decode_option_variant<D: Decoder>(
992    decoder: &mut D,
993    type_name: &'static str,
994) -> Result<Option<()>, DecodeError> {
995    D::assert_covered();
996    let is_some = u8::decode(decoder)?;
997    match is_some {
998        | 0 => Ok(None),
999        | 1 => Ok(Some(())),
1000        | x => {
1001            crate::error::cold_decode_error_unexpected_variant(
1002                type_name,
1003                &crate::error::AllowedEnumVariants::Range { max: 1, min: 0 },
1004                u32::from(x),
1005            )
1006        },
1007    }
1008}
1009
1010/// Decodes the length of any slice, container, etc from the decoder
1011///
1012/// # Errors
1013///
1014/// Returns an error if the operation fails.
1015#[inline(always)]
1016#[allow(dead_code)]
1017pub(crate) fn decode_slice_len<D: Decoder>(decoder: &mut D) -> Result<usize, DecodeError> {
1018    D::assert_covered();
1019    decoder.decode_slice_len()
1020}