1 | use std::io; |
2 | |
3 | macro_rules! read_bytes_ext { |
4 | ($output_type:ty) => { |
5 | impl<W: io::Read + ?Sized> ReadBytesExt<$output_type> for W { |
6 | #[inline] |
7 | fn read_be(&mut self) -> io::Result<$output_type> { |
8 | let mut bytes = [0u8; std::mem::size_of::<$output_type>()]; |
9 | self.read_exact(&mut bytes)?; |
10 | Ok(<$output_type>::from_be_bytes(bytes)) |
11 | } |
12 | } |
13 | }; |
14 | } |
15 | |
16 | macro_rules! write_bytes_ext { |
17 | ($input_type:ty) => { |
18 | impl<W: io::Write + ?Sized> WriteBytesExt<$input_type> for W { |
19 | #[inline] |
20 | fn write_be(&mut self, n: $input_type) -> io::Result<()> { |
21 | self.write_all(&n.to_be_bytes()) |
22 | } |
23 | } |
24 | }; |
25 | } |
26 | |
27 | /// Read extension to read big endian data |
28 | pub trait ReadBytesExt<T>: io::Read { |
29 | /// Read `T` from a bytes stream. Most significant byte first. |
30 | fn read_be(&mut self) -> io::Result<T>; |
31 | } |
32 | |
33 | /// Write extension to write big endian data |
34 | pub trait WriteBytesExt<T>: io::Write { |
35 | /// Writes `T` to a bytes stream. Most significant byte first. |
36 | fn write_be(&mut self, _: T) -> io::Result<()>; |
37 | } |
38 | |
39 | read_bytes_ext!(u8); |
40 | read_bytes_ext!(u16); |
41 | read_bytes_ext!(u32); |
42 | |
43 | write_bytes_ext!(u32); |
44 | |