testnumbat_codec/
nested_de_input.rs

1pub use crate::codec_err::DecodeError;
2use crate::TryStaticCast;
3
4/// Trait that allows deserializing objects from a buffer.
5pub trait NestedDecodeInput {
6    /// The remaining length of the input data.
7    fn remaining_len(&self) -> usize;
8
9    /// True if all data from the buffer has already been used.
10    fn is_depleted(&self) -> bool {
11        self.remaining_len() == 0
12    }
13
14    /// Read the exact number of bytes required to fill the given buffer.
15    fn read_into(&mut self, into: &mut [u8]) -> Result<(), DecodeError>;
16
17    /// Read the exact number of bytes required to fill the given buffer.
18    /// Exit early if there are not enough bytes to fill the result.
19    fn read_into_or_exit<ExitCtx: Clone>(
20        &mut self,
21        into: &mut [u8],
22        c: ExitCtx,
23        exit: fn(ExitCtx, DecodeError) -> !,
24    );
25
26    #[inline]
27    fn read_specialized<T, C, F>(&mut self, _context: C, else_deser: F) -> Result<T, DecodeError>
28    where
29        T: TryStaticCast,
30        C: TryStaticCast,
31        F: FnOnce(&mut Self) -> Result<T, DecodeError>,
32    {
33        else_deser(self)
34    }
35
36    #[inline]
37    fn read_specialized_or_exit<T, C, ExitCtx, F>(
38        &mut self,
39        _context: C,
40        c: ExitCtx,
41        _exit: fn(ExitCtx, DecodeError) -> !,
42        else_deser: F,
43    ) -> T
44    where
45        T: TryStaticCast,
46        C: TryStaticCast,
47        F: FnOnce(&mut Self, ExitCtx) -> T,
48        ExitCtx: Clone,
49    {
50        else_deser(self, c)
51    }
52
53    /// Read a single byte from the input.
54    fn read_byte(&mut self) -> Result<u8, DecodeError> {
55        let mut buf = [0u8];
56        self.read_into(&mut buf[..])?;
57        Ok(buf[0])
58    }
59
60    /// Read a single byte from the input.
61    fn read_byte_or_exit<ExitCtx: Clone>(
62        &mut self,
63        c: ExitCtx,
64        exit: fn(ExitCtx, DecodeError) -> !,
65    ) -> u8 {
66        let mut buf = [0u8];
67        self.read_into_or_exit(&mut buf[..], c, exit);
68        buf[0]
69    }
70}