1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
pub struct Reader<'a> {
    pub buffer: &'a [u8],
    pub bytes_consumed: usize,
}

impl<'a> Reader<'a> {
    pub fn read(&mut self, length: usize) -> Result<&'a [u8], &'static str> {
        let subslice = self.buffer.get(..length).ok_or("unexpected end of section")?;
        self.buffer = &self.buffer[length..];
        self.bytes_consumed += length;
        Ok(subslice)
    }

    pub fn read_byte(&mut self) -> Result<u8, &'static str> {
        Ok(self.read(1)?[0])
    }

    pub fn read_u32(&mut self) -> Result<u32, &'static str> {
        let v = self.read(4)?;
        Ok(u32::from_le_bytes([v[0], v[1], v[2], v[3]]))
    }

    pub fn offset(&self) -> usize {
        self.bytes_consumed
    }

    pub fn is_empty(&self) -> bool {
        self.bytes_consumed >= self.buffer.len()
    }
}

impl<'a> From<&'a [u8]> for Reader<'a> {
    fn from(buffer: &'a [u8]) -> Self {
        Reader { buffer, bytes_consumed: 0 }
    }
}