zaun_community_protocol/encoding/
reader.rs1mod variable;
4
5use super::{Decode, DecodeError};
6
7#[derive(Debug, Clone)]
10pub struct Reader<'a> {
11 input: &'a [u8],
12}
13
14impl<'a> Reader<'a> {
15 #[must_use]
17 pub const fn new(input: &'a [u8]) -> Self {
18 Self { input }
19 }
20
21 #[must_use]
23 pub const fn remaining(&self) -> usize {
24 self.input.len()
25 }
26
27 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 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 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 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 pub fn u8(&mut self) -> Result<u8, DecodeError> {
80 Ok(self.array::<1>()?[0])
81 }
82
83 pub fn u16(&mut self) -> Result<u16, DecodeError> {
88 self.array().map(u16::from_be_bytes)
89 }
90
91 pub fn u32(&mut self) -> Result<u32, DecodeError> {
96 self.array().map(u32::from_be_bytes)
97 }
98
99 pub fn u64(&mut self) -> Result<u64, DecodeError> {
104 self.array().map(u64::from_be_bytes)
105 }
106
107 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 pub fn get<T: Decode>(&mut self) -> Result<T, DecodeError> {
124 T::decode(self)
125 }
126}