Skip to main content

zaun_community_protocol/encoding/reader/
variable.rs

1//! Variable-length fields: `bytes`, `string`, `option<T>` and `list<T>`.
2
3use super::Reader;
4use crate::encoding::DecodeError;
5
6impl<'a> Reader<'a> {
7    /// A `u32` length or count, checked against `max` and then against the remaining input
8    /// (every element of every list is at least one byte).
9    fn length(&mut self, max: usize) -> Result<usize, DecodeError> {
10        let len = self.u32()? as usize;
11        if len > max {
12            return Err(DecodeError::OverLimit { len, max });
13        }
14        if len > self.input.len() {
15            return Err(DecodeError::Truncated {
16                needed: len,
17                remaining: self.input.len(),
18            });
19        }
20        Ok(len)
21    }
22
23    /// Variable `bytes` of at most `max` bytes.
24    ///
25    /// # Errors
26    /// [`DecodeError::OverLimit`] or [`DecodeError::Truncated`].
27    pub fn bytes(&mut self, max: usize) -> Result<&'a [u8], DecodeError> {
28        let len = self.length(max)?;
29        self.fixed(len)
30    }
31
32    /// `string` of at most `max` bytes; valid UTF-8, not normalised.
33    ///
34    /// # Errors
35    /// As [`Self::bytes`], or [`DecodeError::InvalidUtf8`].
36    pub fn string(&mut self, max: usize) -> Result<&'a str, DecodeError> {
37        std::str::from_utf8(self.bytes(max)?).map_err(|_| DecodeError::InvalidUtf8)
38    }
39
40    /// `option<T>` with the value read by `f`; tags other than `0x00`/`0x01` are errors.
41    ///
42    /// # Errors
43    /// [`DecodeError::InvalidOptionTag`], or whatever `f` returns.
44    pub fn option<T>(
45        &mut self,
46        f: impl FnOnce(&mut Self) -> Result<T, DecodeError>,
47    ) -> Result<Option<T>, DecodeError> {
48        match self.u8()? {
49            0 => Ok(None),
50            1 => f(self).map(Some),
51            tag => Err(DecodeError::InvalidOptionTag(tag)),
52        }
53    }
54
55    /// `list<T>` of at most `max` elements, each read by `f`.
56    ///
57    /// # Errors
58    /// [`DecodeError::OverLimit`], [`DecodeError::Truncated`], or whatever `f` returns.
59    pub fn list<T>(
60        &mut self,
61        max: usize,
62        mut f: impl FnMut(&mut Self) -> Result<T, DecodeError>,
63    ) -> Result<Vec<T>, DecodeError> {
64        let count = self.length(max)?;
65        let mut out = Vec::with_capacity(count);
66        for _ in 0..count {
67            out.push(f(self)?);
68        }
69        Ok(out)
70    }
71}