Skip to main content

zaun_community_protocol/encoding/
reader.rs

1//! The canonical decoder.
2
3mod variable;
4
5use super::{Decode, DecodeError};
6
7/// Reads canonical encodings from a byte slice. Lengths and counts are checked against the
8/// field's limit and the remaining input before anything is allocated.
9#[derive(Debug, Clone)]
10pub struct Reader<'a> {
11    input: &'a [u8],
12}
13
14impl<'a> Reader<'a> {
15    /// A reader over `input`.
16    #[must_use]
17    pub const fn new(input: &'a [u8]) -> Self {
18        Self { input }
19    }
20
21    /// Bytes not yet read.
22    #[must_use]
23    pub const fn remaining(&self) -> usize {
24        self.input.len()
25    }
26
27    /// Ends a top-level decode.
28    ///
29    /// # Errors
30    /// [`DecodeError::TrailingBytes`] when input remains.
31    pub const fn finish(self) -> Result<(), DecodeError> {
32        match self.input.len() {
33            0 => Ok(()),
34            n => Err(DecodeError::TrailingBytes(n)),
35        }
36    }
37
38    /// `bytes[n]`: the next `n` bytes.
39    ///
40    /// # Errors
41    /// [`DecodeError::Truncated`].
42    pub fn fixed(&mut self, n: usize) -> Result<&'a [u8], DecodeError> {
43        if n > self.input.len() {
44            return Err(DecodeError::Truncated {
45                needed: n,
46                remaining: self.input.len(),
47            });
48        }
49        let (head, rest) = self.input.split_at(n);
50        self.input = rest;
51        Ok(head)
52    }
53
54    /// `bytes[N]` as an array.
55    ///
56    /// # Errors
57    /// [`DecodeError::Truncated`].
58    pub fn array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
59        let mut out = [0u8; N];
60        out.copy_from_slice(self.fixed(N)?);
61        Ok(out)
62    }
63
64    /// The next byte without consuming it.
65    ///
66    /// # Errors
67    /// [`DecodeError::Truncated`].
68    pub fn peek_u8(&self) -> Result<u8, DecodeError> {
69        self.input.first().copied().ok_or(DecodeError::Truncated {
70            needed: 1,
71            remaining: 0,
72        })
73    }
74
75    /// `u8`.
76    ///
77    /// # Errors
78    /// [`DecodeError::Truncated`].
79    pub fn u8(&mut self) -> Result<u8, DecodeError> {
80        Ok(self.array::<1>()?[0])
81    }
82
83    /// `u16`, big-endian.
84    ///
85    /// # Errors
86    /// [`DecodeError::Truncated`].
87    pub fn u16(&mut self) -> Result<u16, DecodeError> {
88        self.array().map(u16::from_be_bytes)
89    }
90
91    /// `u32`, big-endian.
92    ///
93    /// # Errors
94    /// [`DecodeError::Truncated`].
95    pub fn u32(&mut self) -> Result<u32, DecodeError> {
96        self.array().map(u32::from_be_bytes)
97    }
98
99    /// `u64`, big-endian.
100    ///
101    /// # Errors
102    /// [`DecodeError::Truncated`].
103    pub fn u64(&mut self) -> Result<u64, DecodeError> {
104        self.array().map(u64::from_be_bytes)
105    }
106
107    /// `bool`: only `0x00` and `0x01`.
108    ///
109    /// # Errors
110    /// [`DecodeError::InvalidBool`] or [`DecodeError::Truncated`].
111    pub fn bool(&mut self) -> Result<bool, DecodeError> {
112        match self.u8()? {
113            0 => Ok(false),
114            1 => Ok(true),
115            other => Err(DecodeError::InvalidBool(other)),
116        }
117    }
118
119    /// Reads a value with a canonical decoding.
120    ///
121    /// # Errors
122    /// Whatever the value's decoder returns.
123    pub fn get<T: Decode>(&mut self) -> Result<T, DecodeError> {
124        T::decode(self)
125    }
126}