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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use crate::tag::ValueType;
use std::fmt::{Debug, Formatter};
pub struct Reader<'a> {
buffer: &'a [u8],
cursor: usize,
marker: usize,
}
impl<'a> Reader<'a> {
pub fn new(buffer: &[u8]) -> Reader {
Reader {
buffer,
cursor: 0,
marker: 0,
}
}
pub fn take(&mut self, count: usize) -> CodecResult<&[u8]> {
if self.remaining() < count {
return Err(CodecError::NotEnoughBytes(
self.cursor,
count,
self.remaining(),
));
}
let current = self.cursor;
self.cursor += count;
Ok(&self.buffer[current..current + count])
}
pub fn take_one(&mut self) -> CodecResult<u8> {
if self.remaining() < 1 {
return Err(CodecError::NotEnoughBytes(self.cursor, 1, 0));
}
let byte = self.buffer[self.cursor];
self.cursor += 1;
Ok(byte)
}
pub fn consume_while<F: Fn(u8) -> bool>(&mut self, test: F) {
while self.cursor < self.buffer.len() {
let byte = self.buffer[self.cursor];
if !test(byte) {
break;
}
self.cursor += 1;
}
}
pub fn step_back(&mut self) {
self.cursor -= 1;
}
pub fn remaining(&self) -> usize {
self.buffer.len() - self.cursor
}
pub fn mark(&mut self) {
self.marker = self.cursor;
}
pub fn reset_marker(&mut self) {
self.cursor = self.marker;
}
}
pub enum CodecError {
MissingField(String),
DecodeFail(&'static str, Box<CodecError>),
UnexpectedType(ValueType, ValueType),
UnexpectedFieldType(String, ValueType, ValueType),
NotEnoughBytes(usize, usize, usize),
UnknownError,
DecodedTwice,
InvalidAction(&'static str),
Other(&'static str),
}
impl Debug for CodecError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
CodecError::MissingField(field) => write!(f, "Missing field {field}"),
CodecError::DecodeFail(field, err) => {
write!(f, "Unable to decode field {}: {:?}", field, err)
}
CodecError::UnexpectedType(expected, got) => {
write!(
f,
"Unexpected type; expected {:?} but got {:?}",
expected, got
)
}
CodecError::UnexpectedFieldType(field, expected, got) => {
write!(
f,
"Unexpected type for field {} expected {:?} but got {:?}",
field, expected, got
)
}
CodecError::NotEnoughBytes(cursor, wanted, remaining) => {
write!(
f,
"Didn't have enough bytes (cursor: {}, wanted: {}, remaining: {})",
cursor, wanted, remaining
)
}
CodecError::UnknownError => {
f.write_str("Unknown error occurred when trying to fit bytes")
}
CodecError::DecodedTwice => f.write_str("Attempted to decode packet contents twice"),
CodecError::InvalidAction(value) => {
write!(f, "Attempt invalid action: {value}")
}
CodecError::Other(err) => f.write_str(err),
}
}
}
pub type CodecResult<T> = Result<T, CodecError>;
pub trait Codec: Sized {
fn encode(&self, _output: &mut Vec<u8>) {}
fn decode(_reader: &mut Reader) -> CodecResult<Self> {
Err(CodecError::InvalidAction(
"Not allowed to decode this codec type",
))
}
fn skip(reader: &mut Reader) -> CodecResult<()> {
Self::decode(reader)?;
Ok(())
}
#[inline]
fn value_type() -> ValueType {
ValueType::Unknown(0)
}
fn encode_bytes(&self) -> Vec<u8> {
let mut output = Vec::new();
self.encode(&mut output);
output
}
}
pub fn decode_u16_be(value: &[u8]) -> CodecResult<u16> {
Ok(u16::from_be_bytes(
value.try_into().map_err(|_| CodecError::UnknownError)?,
))
}
pub fn encode_u16_be(value: &u16, output: &mut Vec<u8>) {
let bytes = value.to_be_bytes();
output.extend_from_slice(&bytes);
}
#[cfg(test)]
mod test {
use crate::codec::Reader;
#[test]
pub fn test_reader_take_one() {
let bytes = [0, 15, 23, 5, 10, 0];
let mut reader = Reader::new(&bytes);
for i in 0..bytes.len() {
let byte = bytes[i];
let got = reader.take_one().unwrap();
assert_eq!(byte, got)
}
}
}