zaun_community_protocol/encoding/reader/
variable.rs1use super::Reader;
4use crate::encoding::DecodeError;
5
6impl<'a> Reader<'a> {
7 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 pub fn bytes(&mut self, max: usize) -> Result<&'a [u8], DecodeError> {
28 let len = self.length(max)?;
29 self.fixed(len)
30 }
31
32 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 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 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}