-
Notifications
You must be signed in to change notification settings - Fork 4
/
decoder.rs
565 lines (484 loc) · 18.6 KB
/
decoder.rs
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
/*
Copyright 2023 Loophole Labs
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
use crate::kind::Kind;
use byteorder::{BigEndian, ReadBytesExt};
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::io::{Cursor, Read};
use std::str;
#[derive(Debug, PartialEq)]
pub enum DecodingError {
InvalidNone,
InvalidArray,
InvalidMap,
InvalidBytes,
InvalidString,
InvalidError,
InvalidBool,
InvalidU8,
InvalidU16,
InvalidU32,
InvalidU64,
InvalidI32,
InvalidI64,
InvalidF32,
InvalidF64,
InvalidEnum,
InvalidStruct,
}
impl Display for DecodingError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
impl Error for DecodingError {}
const VARINT_LEN16: u16 = 3;
const VARINT_LEN32: u32 = 5;
const VARINT_LEN64: u64 = 10;
const CONTINUATION: u8 = 0x80;
pub trait Decoder {
fn decode_none(&mut self) -> bool;
fn decode_array(&mut self, val_kind: Kind) -> Result<usize, DecodingError>;
fn decode_map(&mut self, key_kind: Kind, val_kind: Kind) -> Result<usize, DecodingError>;
fn decode_bytes(&mut self) -> Result<Vec<u8>, DecodingError>;
fn decode_string(&mut self) -> Result<String, DecodingError>;
fn decode_error(&mut self) -> Result<Box<dyn Error>, DecodingError>;
fn decode_bool(&mut self) -> Result<bool, DecodingError>;
fn decode_u8(&mut self) -> Result<u8, DecodingError>;
fn decode_u16(&mut self) -> Result<u16, DecodingError>;
fn decode_u32(&mut self) -> Result<u32, DecodingError>;
fn decode_u64(&mut self) -> Result<u64, DecodingError>;
fn decode_i32(&mut self) -> Result<i32, DecodingError>;
fn decode_i64(&mut self) -> Result<i64, DecodingError>;
fn decode_f32(&mut self) -> Result<f32, DecodingError>;
fn decode_f64(&mut self) -> Result<f64, DecodingError>;
}
impl<T> Decoder for Cursor<T>
where
T: AsRef<[u8]>,
{
fn decode_none(&mut self) -> bool {
if let Ok(kind) = self.read_u8() {
if kind == Kind::None as u8 {
return true;
}
self.set_position(self.position() - 1);
}
false
}
fn decode_array(&mut self, val_kind: Kind) -> Result<usize, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidArray)?;
let defined_val_kind = self.read_u8().ok().ok_or(DecodingError::InvalidArray)?;
if kind == Kind::Array as u8 && val_kind as u8 == defined_val_kind {
return match self.decode_u32() {
Err(err) => Err(err),
Ok(val) => Ok(val as usize),
};
}
self.set_position(self.position() - 1);
Err(DecodingError::InvalidU32)
}
fn decode_map(&mut self, key_kind: Kind, val_kind: Kind) -> Result<usize, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidMap)?;
let defined_key_kind = self.read_u8().ok().ok_or(DecodingError::InvalidMap)?;
let defined_val_kind = self.read_u8().ok().ok_or(DecodingError::InvalidMap)?;
if kind == Kind::Map as u8
&& key_kind as u8 == defined_key_kind
&& val_kind as u8 == defined_val_kind
{
return match self.decode_u32() {
Err(err) => Err(err),
Ok(val) => Ok(val as usize),
};
}
self.set_position(self.position() - 1);
Err(DecodingError::InvalidMap)
}
fn decode_bytes(&mut self) -> Result<Vec<u8>, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidBytes)?;
if kind == Kind::Bytes as u8 {
let size = self.decode_u32()? as usize;
let mut buf = vec![0u8; size];
self.read_exact(&mut buf)
.ok()
.ok_or(DecodingError::InvalidBytes)?;
return Ok(buf);
}
self.set_position(self.position() - 1);
Err(DecodingError::InvalidBytes)
}
fn decode_string(&mut self) -> Result<String, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidString)?;
if kind == Kind::String as u8 {
let size = self.decode_u32()? as usize;
let mut str_buf = vec![0u8; size];
self.read_exact(&mut str_buf)
.ok()
.ok_or(DecodingError::InvalidString)?;
let result = str::from_utf8(&str_buf)
.ok()
.ok_or(DecodingError::InvalidString)?;
return Ok(result.to_owned());
}
self.set_position(self.position() - 1);
Err(DecodingError::InvalidString)
}
fn decode_error(&mut self) -> Result<Box<dyn Error>, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidError)?;
let nested_kind = self.read_u8().ok().ok_or(DecodingError::InvalidError)?;
if kind == Kind::Error as u8 && nested_kind == Kind::String as u8 {
let size = self.decode_u32()? as usize;
let mut str_buf = vec![0u8; size];
self.read_exact(&mut str_buf)
.ok()
.ok_or(DecodingError::InvalidError)?;
let result = str::from_utf8(&str_buf)
.ok()
.ok_or(DecodingError::InvalidError)?;
return Ok(Box::<dyn Error>::from(result.to_owned()));
}
self.set_position(self.position() - 2);
Err(DecodingError::InvalidError)
}
fn decode_bool(&mut self) -> Result<bool, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidBool)?;
if kind == Kind::Bool as u8 {
let val = self.read_u8().ok().ok_or(DecodingError::InvalidBool)?;
return Ok(val == 1);
}
self.set_position(self.position() - 1);
Err(DecodingError::InvalidBool)
}
fn decode_u8(&mut self) -> Result<u8, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidU8)?;
if kind == Kind::U8 as u8 {
return self.read_u8().ok().ok_or(DecodingError::InvalidU8);
}
self.set_position(self.position() - 1);
Err(DecodingError::InvalidU8)
}
fn decode_u16(&mut self) -> Result<u16, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidU16)?;
if kind == Kind::U16 as u8 {
let mut x: u16 = 0;
let mut s: u32 = 0;
for _ in 0..VARINT_LEN16 {
let byte = self.read_u8().ok().ok_or(DecodingError::InvalidU16)?;
if byte < CONTINUATION {
return Ok(x | (byte as u16) << s);
}
x |= (byte as u16 & ((CONTINUATION as u16) - 1)) << s;
s += 7;
}
}
self.set_position(self.position() - 1);
Err(DecodingError::InvalidU32)
}
fn decode_u32(&mut self) -> Result<u32, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidU32)?;
if kind == Kind::U32 as u8 {
let mut x: u32 = 0;
let mut s: u32 = 0;
for _ in 0..VARINT_LEN32 {
let byte = self.read_u8().ok().ok_or(DecodingError::InvalidU32)?;
if byte < CONTINUATION {
return Ok(x | (byte as u32) << s);
}
x |= (byte as u32 & ((CONTINUATION as u32) - 1)) << s;
s += 7;
}
}
self.set_position(self.position() - 1);
Err(DecodingError::InvalidU32)
}
fn decode_u64(&mut self) -> Result<u64, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidU64)?;
if kind == Kind::U64 as u8 {
let mut x: u64 = 0;
let mut s: u32 = 0;
for _ in 0..VARINT_LEN64 {
let byte = self.read_u8().ok().ok_or(DecodingError::InvalidU64)?;
if byte < CONTINUATION {
return Ok(x | (byte as u64) << s);
}
x |= (byte as u64 & ((CONTINUATION as u64) - 1)) << s;
s += 7;
}
}
self.set_position(self.position() - 1);
Err(DecodingError::InvalidU32)
}
fn decode_i32(&mut self) -> Result<i32, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidI32)?;
if kind == Kind::I32 as u8 {
let mut ux: u32 = 0;
let mut s: u32 = 0;
for _ in 0..VARINT_LEN32 {
let byte = self.read_u8().ok().ok_or(DecodingError::InvalidI32)?;
if byte < CONTINUATION {
ux |= (byte as u32) << s;
let mut x = (ux >> 1) as i32;
if ux & 1 != 0 {
x = x.wrapping_add(1).wrapping_neg();
}
return Ok(x);
}
ux |= (byte as u32 & ((CONTINUATION as u32) - 1)) << s;
s += 7;
}
}
self.set_position(self.position() - 1);
Err(DecodingError::InvalidI32)
}
fn decode_i64(&mut self) -> Result<i64, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidI64)?;
if kind == Kind::I64 as u8 {
let mut ux: u64 = 0;
let mut s: u32 = 0;
for _ in 0..VARINT_LEN64 {
let byte = self.read_u8().ok().ok_or(DecodingError::InvalidI64)?;
if byte < CONTINUATION {
ux |= (byte as u64) << s;
let mut x = (ux >> 1) as i64;
if ux & 1 != 0 {
x = x.wrapping_add(1).wrapping_neg();
}
return Ok(x);
}
ux |= (byte as u64 & ((CONTINUATION as u64) - 1)) << s;
s += 7;
}
}
self.set_position(self.position() - 1);
Err(DecodingError::InvalidI64)
}
fn decode_f32(&mut self) -> Result<f32, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidF32)?;
if kind == Kind::F32 as u8 {
return self
.read_f32::<BigEndian>()
.ok()
.ok_or(DecodingError::InvalidF32);
}
self.set_position(self.position() - 1);
Err(DecodingError::InvalidF32)
}
fn decode_f64(&mut self) -> Result<f64, DecodingError> {
let kind = self.read_u8().ok().ok_or(DecodingError::InvalidF64)?;
if kind == Kind::F64 as u8 {
return self
.read_f64::<BigEndian>()
.ok()
.ok_or(DecodingError::InvalidF64);
}
self.set_position(self.position() - 1);
Err(DecodingError::InvalidF64)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::encoder::Encoder;
use std::collections::HashMap;
#[test]
fn test_decode_nil() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
encoder.encode_none().unwrap();
let mut decoder = Cursor::new(encoder.get_mut());
let val = decoder.decode_none();
assert!(val);
assert_eq!(decoder.get_ref().len() - decoder.position() as usize, 0);
let next_val = decoder.decode_none();
assert!(!next_val);
}
#[test]
fn test_decode_array() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
let m = ["1".to_string(), "2".to_string(), "3".to_string()];
encoder.encode_array(m.len(), Kind::String).unwrap();
for i in m.clone() {
encoder.encode_string(&i).unwrap();
}
let mut decoder = Cursor::new(encoder.get_mut());
let size = decoder.decode_array(Kind::String).unwrap();
assert_eq!(size, m.len());
let mut mv: Vec<String> = Vec::with_capacity(size);
for i in 0..size {
let val = decoder.decode_string().unwrap();
mv.push(val.to_string());
assert_eq!(mv[i], m[i]);
}
assert_eq!(mv, m);
let error = decoder.decode_array(Kind::String).unwrap_err();
assert_eq!(error, DecodingError::InvalidArray);
}
#[test]
fn test_decode_map() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
let mut m: HashMap<String, u32> = HashMap::new();
m.insert(String::from("1"), 1);
m.insert(String::from("2"), 2);
m.insert(String::from("3"), 3);
encoder
.encode_map(m.len(), Kind::String, Kind::U32)
.unwrap();
for (k, v) in m.clone() {
encoder.encode_string(&k).unwrap().encode_u32(v).unwrap();
}
let mut decoder = Cursor::new(encoder.get_mut());
let size = decoder.decode_map(Kind::String, Kind::U32).unwrap();
assert_eq!(size, m.len());
let mut mv = HashMap::new();
for _ in 0..size {
let k = decoder.decode_string().unwrap();
let v = decoder.decode_u32().unwrap();
mv.insert(k, v);
}
assert_eq!(mv, m);
let error = decoder.decode_map(Kind::String, Kind::U32).unwrap_err();
assert_eq!(error, DecodingError::InvalidMap);
}
#[test]
fn test_decode_bytes() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
let v = "Test String".as_bytes();
encoder.encode_bytes(v).unwrap();
let mut decoder = Cursor::new(encoder.get_mut());
let bytes = decoder.decode_bytes().unwrap();
assert_eq!(bytes, v);
}
#[test]
fn test_decode_string() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
let v = "Test String".to_string();
encoder.encode_string(&v).unwrap();
let mut decoder = Cursor::new(encoder.get_mut());
let val = decoder.decode_string().unwrap();
assert_eq!(val, v);
let error = decoder.decode_string().unwrap_err();
assert_eq!(error, DecodingError::InvalidString);
}
#[test]
fn test_decode_error() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
let v = "Test String";
encoder.encode_error(Box::<dyn Error>::from(v)).unwrap();
let mut decoder = Cursor::new(encoder.get_mut());
let val = decoder.decode_error().unwrap();
assert_eq!(val.to_string(), v);
let error = decoder.decode_error().unwrap_err();
assert_eq!(error, DecodingError::InvalidError);
}
#[test]
fn test_decode_bool() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
encoder.encode_bool(true).unwrap();
let mut decoder = Cursor::new(encoder.get_mut());
let val = decoder.decode_bool().unwrap();
assert!(val);
let error = decoder.decode_bool().unwrap_err();
assert_eq!(error, DecodingError::InvalidBool);
}
#[test]
fn test_decode_u8() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
let v = 32_u8;
encoder.encode_u8(v).unwrap();
let mut decoder = Cursor::new(encoder.get_mut());
let val = decoder.decode_u8().unwrap();
assert_eq!(val, v);
let error = decoder.decode_u8().unwrap_err();
assert_eq!(error, DecodingError::InvalidU8);
}
#[test]
fn test_decode_u16() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
let v = 1024_u16;
encoder.encode_u16(v).unwrap();
let mut decoder = Cursor::new(encoder.get_mut());
let val = decoder.decode_u16().unwrap();
assert_eq!(val, v);
let error = decoder.decode_u16().unwrap_err();
assert_eq!(error, DecodingError::InvalidU16);
}
#[test]
fn test_decode_u32() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
let v = 4294967290_u32;
encoder.encode_u32(v).unwrap();
let mut decoder = Cursor::new(encoder.get_mut());
let val = decoder.decode_u32().unwrap();
assert_eq!(val, v);
let error = decoder.decode_u32().unwrap_err();
assert_eq!(error, DecodingError::InvalidU32);
}
#[test]
fn test_decode_u64() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
let v = 18446744073709551610_u64;
encoder.encode_u64(v).unwrap();
let mut decoder = Cursor::new(encoder.get_mut());
let val = decoder.decode_u64().unwrap();
assert_eq!(val, v);
let error = decoder.decode_u64().unwrap_err();
assert_eq!(error, DecodingError::InvalidU64);
}
#[test]
fn test_decode_i32() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
let v = -2147483648;
let vneg = -32;
encoder.encode_i32(v).unwrap();
encoder.encode_i32(vneg).unwrap();
let mut decoder = Cursor::new(encoder.get_mut());
let val = decoder.decode_i32().unwrap();
assert_eq!(val, v);
let val = decoder.decode_i32().unwrap();
assert_eq!(val, vneg);
let error = decoder.decode_i32().unwrap_err();
assert_eq!(error, DecodingError::InvalidI32);
}
#[test]
fn test_decode_i64() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
let v = -9223372036854775808_i64;
encoder.encode_i64(v).unwrap();
let mut decoder = Cursor::new(encoder.get_mut());
let val = decoder.decode_i64().unwrap();
assert_eq!(val, v);
let error = decoder.decode_i64().unwrap_err();
assert_eq!(error, DecodingError::InvalidI64);
}
#[test]
fn test_decode_f32() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
let v = -2_147_483.8_f32;
encoder.encode_f32(v).unwrap();
let mut decoder = Cursor::new(encoder.get_mut());
let val = decoder.decode_f32().unwrap();
assert_eq!(val, v);
let error = decoder.decode_f32().unwrap_err();
assert_eq!(error, DecodingError::InvalidF32);
}
#[test]
fn test_decode_f64() {
let mut encoder = Cursor::new(Vec::with_capacity(512));
let v = -922337203.477580_f64;
encoder.encode_f64(v).unwrap();
let mut decoder = Cursor::new(encoder.get_mut());
let val = decoder.decode_f64().unwrap();
assert_eq!(val, v);
let error = decoder.decode_f64().unwrap_err();
assert_eq!(error, DecodingError::InvalidF64);
}
}