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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
pub use reader::{ExpectedSize, Reader};
pub use writer::Writer;
mod reader {
use std::convert::TryFrom;
type Result<T> = std::result::Result<T, InsufficientBuffer>;
pub struct Reader<'a>(&'a [u8]);
#[derive(Debug)]
pub struct InsufficientBuffer;
pub struct ReadError;
pub enum ExpectedSize {
Exact(usize),
NotLessThan(usize),
}
impl<'a> Reader<'a> {
pub fn new(data: &'a [u8]) -> Self {
Reader(data)
}
pub fn read<R, F: FnOnce(&mut Self) -> Result<R>>(&mut self, expected_size: ExpectedSize, job: F) -> std::result::Result<R, ReadError> {
let len_before_read = self.len();
match expected_size {
ExpectedSize::Exact(count) => {
if self.len() != count {
return Err(ReadError);
}
let res = job(self).expect("reading data more than could be");
assert_eq!(self.len(), len_before_read - count, "reading data less than stated");
Ok(res)
}
ExpectedSize::NotLessThan(count) => {
if self.len() < count {
return Err(ReadError);
}
let res = job(self).expect("reading data more than could be");
assert!(len_before_read - count >= self.len(), "reading data less than stated");
Ok(res)
}
}
}
pub fn read_u8(&mut self) -> Result<u8> {
let bytes = self.read_slice(1)?;
Ok(bytes[0])
}
pub fn read_u16_be(&mut self) -> Result<u16> {
let bytes = self.read_slice(2)?;
let bytes_array = <[u8; 2]>::try_from(bytes).expect("invalid slice size");
Ok(u16::from_be_bytes(bytes_array))
}
pub fn read_u32_be(&mut self) -> Result<u32> {
let bytes = self.read_slice(4)?;
let bytes_array = <[u8; 4]>::try_from(bytes).expect("invalid slice size");
Ok(u32::from_be_bytes(bytes_array))
}
pub fn read_u64_be(&mut self) -> Result<u64> {
let bytes = self.read_slice(8)?;
let bytes_array = <[u8; 8]>::try_from(bytes).expect("invalid slice size");
Ok(u64::from_be_bytes(bytes_array))
}
pub fn read_array_32(&mut self) -> Result<[u8; 32]> {
let bytes_32_slice = self.read_slice(32)?;
let bytes_32_array = <[u8; 32]>::try_from(bytes_32_slice).expect("invalid slice size");
Ok(bytes_32_array)
}
pub fn peek_remainder(&self) -> &'a [u8] {
self.0
}
pub fn read_remainder(&mut self) -> &'a [u8] {
self.read_slice(self.len()).expect("attempting to read data more than slice have")
}
pub fn skip(&mut self, count: usize) -> Result<()> {
let _ = self.read_slice(count)?;
Ok(())
}
pub fn read_slice(&mut self, count: usize) -> Result<&'a [u8]> {
if self.len() < count {
return Err(InsufficientBuffer);
}
let (ret_bytes, rest_bytes) = self.0.split_at(count);
self.0 = rest_bytes;
Ok(ret_bytes)
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn len(&self) -> usize {
self.0.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_reader() {
let bytes = (0..64).collect::<Vec<u8>>();
let mut reader = Reader::new(&bytes);
let num8 = reader.read_u8().expect("bytes are read out");
assert_eq!(num8, 0);
let num16 = reader.read_u16_be().expect("bytes are read out");
assert_eq!(num16.to_be_bytes(), [1, 2]);
let num32 = reader.read_u32_be().expect("bytes are read out");
assert_eq!(num32.to_be_bytes(), [3, 4, 5, 6]);
let num64 = reader.read_u64_be().expect("bytes are read out");
assert_eq!(num64.to_be_bytes(), [7, 8, 9, 10, 11, 12, 13, 14]);
let array_32 = reader.read_array_32().expect("bytes are read out");
assert_eq!(array_32.to_vec(), (15..47).collect::<Vec<u8>>());
assert!(reader.read_slice(20).is_err());
reader.read_slice(17).expect("bytes are read out");
assert_eq!(reader.len(), 0);
}
#[test]
fn test_remainder() {
let bytes = (0..32).collect::<Vec<u8>>();
let mut reader = Reader::new(&bytes);
assert_eq!(&bytes, &reader.peek_remainder());
let _ = reader.read_u16_be();
assert_eq!(&bytes[2..], reader.peek_remainder());
let _ = reader.read_u16_be();
assert_eq!(&bytes[4..], reader.read_remainder());
assert_eq!(0, reader.len())
}
#[test]
fn test_custom_read() {
let bytes = vec![0; 32];
let mut reader = Reader::new(&bytes);
assert!(reader.read(ExpectedSize::Exact(35), |_| Ok(())).is_err());
assert!(reader.read(ExpectedSize::NotLessThan(35), |_| Ok(())).is_err());
}
#[test]
#[should_panic]
fn test_read_more_for_exact() {
let bytes = vec![0; 32];
let mut reader = Reader::new(&bytes);
let _ = reader.read(ExpectedSize::Exact(32), |r| {
let invalid_res = r.read_slice(35)?;
Ok(invalid_res)
});
}
#[test]
#[should_panic]
fn test_read_less_for_exact() {
let bytes = vec![0; 32];
let mut reader = Reader::new(&bytes);
let _ = reader.read(ExpectedSize::Exact(32), |r| {
let invalid_res = r.read_slice(20)?;
Ok(invalid_res)
});
}
#[test]
#[should_panic]
fn test_read_more_for_not_less_than() {
let bytes = vec![0; 32];
let mut reader = Reader::new(&bytes);
let _ = reader.read(ExpectedSize::NotLessThan(32), |r| {
let invalid_res = r.read_slice(35)?;
Ok(invalid_res)
});
}
#[test]
#[should_panic]
fn test_read_less_for_not_less_than() {
let bytes = vec![0; 32];
let mut reader = Reader::new(&bytes);
let _ = reader.read(ExpectedSize::NotLessThan(32), |r| {
let invalid_res = r.read_slice(20)?;
Ok(invalid_res)
});
}
}
}
mod writer {
pub struct Writer(Vec<u8>);
impl Writer {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn with_capacity(capacity: usize) -> Self {
Self(Vec::with_capacity(capacity))
}
pub fn into_vec(self) -> Vec<u8> {
self.0
}
pub fn write_u8(&mut self, data: u8) {
self.write_slice(&[data]);
}
pub fn write_u16_be(&mut self, data: u16) {
self.write_slice(&data.to_be_bytes());
}
pub fn write_u32_be(&mut self, data: u32) {
self.write_slice(&data.to_be_bytes())
}
pub fn write_u64_be(&mut self, data: u64) {
self.write_slice(&data.to_be_bytes());
}
pub fn write_slice(&mut self, data: &[u8]) {
self.0.extend_from_slice(data);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_writer() {
let initial_capacity = 64;
let mut writer = Writer::with_capacity(64);
writer.write_u8(0);
writer.write_u16_be(258);
writer.write_u32_be(50595078);
writer.write_u64_be(506664896818842894);
let data = (15..64).collect::<Vec<u8>>();
writer.write_slice(&data);
let bytes = writer.into_vec();
assert_eq!(bytes.len(), initial_capacity);
assert_eq!(bytes, (0..64).collect::<Vec<u8>>());
}
}
}