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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use std::str;

pub struct OutputBuffer {
    bytes: Vec<u8>,
}

impl OutputBuffer {
    pub fn new() -> Self {
        OutputBuffer { bytes: Vec::new() }
    }

    pub fn write_u8(&mut self, value: u8) {
        self.bytes.push(value);
    }

    pub fn write_u16(&mut self, value: u16) {
        self.bytes.extend_from_slice(&value.to_le_bytes());
    }

    pub fn write_u32(&mut self, value: u32) {
        self.bytes.extend_from_slice(&value.to_le_bytes());
    }

    pub fn write_str(&mut self, value: &str) {
        self.bytes.extend_from_slice(value.as_bytes());
    }

    pub fn into_bytes(self) -> Vec<u8> {
        self.bytes
    }
}

pub struct InputBuffer<'a> {
    bytes: &'a [u8],
}

impl<'a> InputBuffer<'a> {
    pub fn new(bytes: &'a [u8]) -> Self {
        InputBuffer { bytes }
    }

    pub fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    pub fn read_u8(&mut self) -> u8 {
        let (first, rest) = self.bytes.split_first().unwrap();
        self.bytes = rest;
        *first
    }

    pub fn read_u16(&mut self) -> u16 {
        let (value, rest) = self.bytes.split_at(2);
        self.bytes = rest;
        u16::from_le_bytes([value[0], value[1]])
    }

    pub fn read_u32(&mut self) -> u32 {
        let (value, rest) = self.bytes.split_at(4);
        self.bytes = rest;
        u32::from_le_bytes([value[0], value[1], value[2], value[3]])
    }

    pub fn read_str(&mut self, len: usize) -> &'a str {
        let (string, rest) = self.bytes.split_at(len);
        self.bytes = rest;
        str::from_utf8(string).unwrap()
    }
}