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