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
use std::io;
pub trait Parameter<Object> {
fn set_param(self, &mut Object);
}
pub trait HasParameters: Sized {
fn set<T: Parameter<Self>>(&mut self, value: T) -> &mut Self {
value.set_param(self);
self
}
}
fn read_all<R: io::Read + ?Sized>(this: &mut R, buf: &mut [u8]) -> io::Result<()> {
let mut total = 0;
while total < buf.len() {
match this.read(&mut buf[total..]) {
Ok(0) => return Err(io::Error::new(io::ErrorKind::Other,
"failed to read the whole buffer")),
Ok(n) => total += n,
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(())
}
pub trait ReadBytesExt<T>: io::Read {
fn read_be(&mut self) -> io::Result<T>;
}
pub trait WriteBytesExt<T>: io::Write {
fn write_be(&mut self, T) -> io::Result<()>;
}
impl<W: io::Read + ?Sized> ReadBytesExt<u8> for W {
#[inline]
fn read_be(&mut self) -> io::Result<u8> {
let mut byte = [0];
try!(read_all(self, &mut byte));
Ok(byte[0])
}
}
impl<W: io::Read + ?Sized> ReadBytesExt<u16> for W {
#[inline]
fn read_be(&mut self) -> io::Result<u16> {
let mut bytes = [0, 0];
try!(read_all(self, &mut bytes));
Ok((bytes[0] as u16) << 8 | bytes[1] as u16)
}
}
impl<W: io::Read + ?Sized> ReadBytesExt<u32> for W {
#[inline]
fn read_be(&mut self) -> io::Result<u32> {
let mut bytes = [0, 0, 0, 0];
try!(read_all(self, &mut bytes));
Ok( (bytes[0] as u32) << 24
| (bytes[1] as u32) << 16
| (bytes[2] as u32) << 8
| bytes[3] as u32
)
}
}
impl<W: io::Write + ?Sized> WriteBytesExt<u32> for W {
#[inline]
fn write_be(&mut self, n: u32) -> io::Result<()> {
self.write_all(&[
(n >> 24) as u8,
(n >> 16) as u8,
(n >> 8) as u8,
n as u8
])
}
}