-
Notifications
You must be signed in to change notification settings - Fork 20
/
decoder.rs
67 lines (58 loc) · 1.41 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
use std::vec::VecIterator;
pub enum TokenType {
Unsigned32,
Unsigned64,
VarInt,
Bytestring(u64)
}
pub enum Token {
Integer(u64),
String(~[u8]),
Invalid
}
fn decode_integer (iter: &mut VecIterator<u8>, width: int) -> Token {
let mut success = true;
let mut rv: u64 = 0;
for i in range (0, width) {
match iter.next() {
None => { success = false; break }
Some(&ch) => { rv += (ch as u64) << 8 * i; }
}
}
if success { Integer (rv) }
else { Invalid }
}
pub fn decode_token (iter: &mut VecIterator<u8>, expected_token: TokenType) -> Token {
match expected_token {
/* Fixed-width integers */
Unsigned32 => { decode_integer (iter, 4) }
Unsigned64 => { decode_integer (iter, 8) }
/* Variable-width integers */
VarInt => {
match iter.next() {
Some(&ch) => {
match ch {
0xff => decode_integer (iter, 8),
0xfe => decode_integer (iter, 4),
0xfd => decode_integer (iter, 2),
n => { Integer(n as u64) }
}
}
None => Invalid
}
}
/* Strings */
Bytestring(len) => {
let mut success = true;
let mut rv: ~[u8] = ~[];
for _ in range (0, len) {
match iter.next() {
None => { success = false; break }
Some(&ch) => { rv.push (ch); }
}
}
if success { String (rv) }
else { Invalid }
}
}
}