1use crate::error::DecodeError;
5
6pub struct Reader<'a> {
7 bytes: &'a [u8],
8 pos: usize,
9}
10
11impl<'a> Reader<'a> {
12 pub fn new(bytes: &'a [u8]) -> Self {
13 Self {
14 bytes,
15 pos: 0,
16 }
17 }
18
19 pub fn position(&self) -> usize {
20 self.pos
21 }
22
23 pub fn remaining(&self) -> usize {
24 self.bytes.len() - self.pos
25 }
26
27 pub fn is_empty(&self) -> bool {
28 self.remaining() == 0
29 }
30
31 pub fn take(&mut self, n: usize) -> Result<&'a [u8], DecodeError> {
32 if self.remaining() < n {
33 return Err(DecodeError::UnexpectedEof {
34 expected: n,
35 available: self.remaining(),
36 });
37 }
38 let slice = &self.bytes[self.pos..self.pos + n];
39 self.pos += n;
40 Ok(slice)
41 }
42
43 pub fn u8(&mut self) -> Result<u8, DecodeError> {
44 Ok(self.take(1)?[0])
45 }
46
47 pub fn u16(&mut self) -> Result<u16, DecodeError> {
48 Ok(u16::from_le_bytes(self.take(2)?.try_into().unwrap()))
49 }
50
51 pub fn u32(&mut self) -> Result<u32, DecodeError> {
52 Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
53 }
54
55 pub fn u64(&mut self) -> Result<u64, DecodeError> {
56 Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap()))
57 }
58
59 pub fn u128(&mut self) -> Result<u128, DecodeError> {
60 Ok(u128::from_le_bytes(self.take(16)?.try_into().unwrap()))
61 }
62
63 pub fn i8(&mut self) -> Result<i8, DecodeError> {
64 Ok(self.take(1)?[0] as i8)
65 }
66
67 pub fn i16(&mut self) -> Result<i16, DecodeError> {
68 Ok(i16::from_le_bytes(self.take(2)?.try_into().unwrap()))
69 }
70
71 pub fn i32(&mut self) -> Result<i32, DecodeError> {
72 Ok(i32::from_le_bytes(self.take(4)?.try_into().unwrap()))
73 }
74
75 pub fn i64(&mut self) -> Result<i64, DecodeError> {
76 Ok(i64::from_le_bytes(self.take(8)?.try_into().unwrap()))
77 }
78
79 pub fn i128(&mut self) -> Result<i128, DecodeError> {
80 Ok(i128::from_le_bytes(self.take(16)?.try_into().unwrap()))
81 }
82
83 pub fn f32(&mut self) -> Result<f32, DecodeError> {
84 Ok(f32::from_le_bytes(self.take(4)?.try_into().unwrap()))
85 }
86
87 pub fn f64(&mut self) -> Result<f64, DecodeError> {
88 Ok(f64::from_le_bytes(self.take(8)?.try_into().unwrap()))
89 }
90}