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
use std::io;
use std::io::{Read, Result};
use fixed::FixedInt;
use varint::{VarInt, MSB};
pub trait VarIntReader {
fn read_varint<VI: VarInt>(&mut self) -> Result<VI>;
}
impl<R: Read> VarIntReader for R {
fn read_varint<VI: VarInt>(&mut self) -> Result<VI> {
const BUFLEN: usize = 10;
let mut buf = [0 as u8; BUFLEN];
let mut i = 0;
loop {
if i >= BUFLEN {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Unterminated varint",
));
}
let read = try!(self.read(&mut buf[i..i + 1]));
if read == 0 && i == 0 {
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "Reached EOF"));
}
if buf[i] & MSB == 0 {
break;
}
i += 1;
}
let (result, _) = VI::decode_var(&buf[0..i + 1]);
Ok(result)
}
}
pub trait FixedIntReader {
fn read_fixedint<FI: FixedInt>(&mut self) -> Result<FI>;
}
impl<R: Read> FixedIntReader for R {
fn read_fixedint<FI: FixedInt>(&mut self) -> Result<FI> {
let mut buf = [0 as u8; 8];
let read = try!(self.read(&mut buf[0..FI::required_space()]));
if read == 0 {
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "Reached EOF"));
}
Ok(FI::decode_fixed(&buf[0..read]))
}
}