cameleon_impl/
bytes_io.rs1use std::io;
2
3pub trait ReadBytes {
4 fn read_bytes_be<T>(&mut self) -> io::Result<T>
5 where
6 T: BytesConvertible;
7
8 fn read_bytes_le<T>(&mut self) -> io::Result<T>
9 where
10 T: BytesConvertible;
11}
12
13pub trait WriteBytes {
14 fn write_bytes_be<T>(&mut self, value: T) -> io::Result<usize>
15 where
16 T: BytesConvertible;
17
18 fn write_bytes_le<T>(&mut self, value: T) -> io::Result<usize>
19 where
20 T: BytesConvertible;
21}
22
23impl<R> ReadBytes for R
24where
25 R: io::Read,
26{
27 fn read_bytes_be<T>(&mut self) -> io::Result<T>
28 where
29 T: BytesConvertible,
30 {
31 T::read_bytes_be(self)
32 }
33
34 fn read_bytes_le<T>(&mut self) -> io::Result<T>
35 where
36 T: BytesConvertible,
37 {
38 T::read_bytes_le(self)
39 }
40}
41
42impl<W> WriteBytes for W
43where
44 W: io::Write,
45{
46 fn write_bytes_be<T>(&mut self, value: T) -> io::Result<usize>
47 where
48 T: BytesConvertible,
49 {
50 value.write_bytes_be(self)
51 }
52
53 fn write_bytes_le<T>(&mut self, value: T) -> io::Result<usize>
54 where
55 T: BytesConvertible,
56 {
57 value.write_bytes_le(self)
58 }
59}
60
61pub trait BytesConvertible {
62 fn read_bytes_be<R>(buf: &mut R) -> io::Result<Self>
63 where
64 Self: Sized,
65 R: io::Read;
66
67 fn read_bytes_le<R>(buf: &mut R) -> io::Result<Self>
68 where
69 Self: Sized,
70 R: io::Read;
71
72 fn write_bytes_be<W>(self, buf: &mut W) -> io::Result<usize>
73 where
74 Self: Sized,
75 W: io::Write;
76
77 fn write_bytes_le<W>(self, buf: &mut W) -> io::Result<usize>
78 where
79 Self: Sized,
80 W: io::Write;
81}
82
83macro_rules! impl_bytes_convertible {
84 ($($ty:ty,)*) => {
85 $(
86 impl BytesConvertible for $ty {
87 fn read_bytes_be<R>(buf: &mut R) -> io::Result<Self>
88 where
89 R: io::Read,
90 {
91 let mut tmp = [0; std::mem::size_of::<$ty>()];
92 buf.read_exact(&mut tmp)?;
93 Ok(<$ty>::from_be_bytes(tmp))
94 }
95
96 fn read_bytes_le<R>(buf: &mut R) -> io::Result<Self>
97 where
98 R: io::Read,
99 {
100 let mut tmp = [0; std::mem::size_of::<$ty>()];
101 buf.read_exact(&mut tmp)?;
102 Ok(<$ty>::from_le_bytes(tmp))
103 }
104
105 fn write_bytes_be<W>(self, buf: &mut W) -> io::Result<usize>
106 where
107 W: io::Write,
108 {
109 let tmp = self.to_be_bytes();
110 buf.write(&tmp)
111 }
112
113 fn write_bytes_le<W>(self, buf: &mut W) -> io::Result<usize>
114 where
115 W: io::Write,
116 {
117 let tmp = self.to_le_bytes();
118 buf.write(&tmp)
119 }
120 }
121 )*
122 };
123}
124
125impl_bytes_convertible! {
126 u8,
127 u16,
128 u32,
129 u64,
130 i8,
131 i16,
132 i32,
133 i64,
134 f32,
135 f64,
136}