1#![deny(missing_docs)]
15#![cfg_attr(not(feature = "std"), no_std)]
16
17#[cfg(feature = "std")]
18use std::io;
19
20pub trait ByteOrder {
22 fn read_u32(buf: &[u8]) -> u32;
28
29 fn write_u32(buf: &mut [u8], n: u32);
35
36 fn write_u64(buf: &mut [u8], n: u64);
42}
43
44pub enum LittleEndian {}
48
49pub type LE = LittleEndian;
51
52impl ByteOrder for LittleEndian {
53 #[inline]
54 fn read_u32(buf: &[u8]) -> u32 {
55 u32::from_le_bytes(buf[..4].try_into().unwrap())
56 }
57
58 #[inline]
59 fn write_u32(buf: &mut [u8], n: u32) {
60 buf[..4].copy_from_slice(&n.to_le_bytes());
61 }
62
63 #[inline]
64 fn write_u64(buf: &mut [u8], n: u64) {
65 buf[..8].copy_from_slice(&n.to_le_bytes());
66 }
67}
68
69#[cfg(feature = "std")]
73pub trait WriteBytesExt: io::Write {
74 #[inline]
76 fn write_u8(&mut self, n: u8) -> io::Result<()> {
77 self.write_all(&[n])
78 }
79
80 #[inline]
82 fn write_u32<T>(&mut self, n: u32) -> io::Result<()>
83 where
84 T: ByteOrder,
85 {
86 let mut buf = [0; 4];
87 T::write_u32(&mut buf, n);
88 self.write_all(&buf)
89 }
90
91 #[inline]
93 fn write_i32<T>(&mut self, n: i32) -> io::Result<()>
94 where
95 T: ByteOrder,
96 {
97 self.write_u32::<T>(n as u32)
98 }
99
100 #[inline]
102 fn write_u64<T>(&mut self, n: u64) -> io::Result<()>
103 where
104 T: ByteOrder,
105 {
106 let mut buf = [0; 8];
107 T::write_u64(&mut buf, n);
108 self.write_all(&buf)
109 }
110
111 #[inline]
113 fn write_i64<T>(&mut self, n: i64) -> io::Result<()>
114 where
115 T: ByteOrder,
116 {
117 self.write_u64::<T>(n as u64)
118 }
119
120 #[inline]
122 fn write_f32<T>(&mut self, n: f32) -> io::Result<()>
123 where
124 T: ByteOrder,
125 {
126 self.write_u32::<T>(n.to_bits())
127 }
128
129 #[inline]
131 fn write_f64<T>(&mut self, n: f64) -> io::Result<()>
132 where
133 T: ByteOrder,
134 {
135 self.write_u64::<T>(n.to_bits())
136 }
137}
138
139#[cfg(feature = "std")]
140impl<W> WriteBytesExt for W where W: io::Write + ?Sized {}
141
142#[cfg(all(test, feature = "std"))]
143mod tests {
144 use std::io::{self, Write};
145
146 use super::*;
147
148 type WriteFn = fn(&mut dyn Write) -> io::Result<()>;
149 type WriteCase = (&'static str, WriteFn, &'static [u8]);
150 type FullFn = fn() -> io::Result<usize>;
151
152 const WRITE_CASES: &[WriteCase] = &[
154 ("write_u8", |w| w.write_u8(0xAB), &[0xAB]),
155 (
156 "write_u32",
157 |w| w.write_u32::<LE>(0x0102_0304),
158 &[0x04, 0x03, 0x02, 0x01],
159 ),
160 ("write_i32", |w| w.write_i32::<LE>(-2), &[0xFE, 0xFF, 0xFF, 0xFF]),
161 (
162 "write_u64",
163 |w| w.write_u64::<LE>(0x0102_0304_0506_0708),
164 &[0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01],
165 ),
166 (
167 "write_i64",
168 |w| w.write_i64::<LE>(-2),
169 &[0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
170 ),
171 ("write_f32", |w| w.write_f32::<LE>(-1.5), &[0x00, 0x00, 0xC0, 0xBF]),
172 (
174 "write_f32",
175 |w| w.write_f32::<LE>(f32::from_bits(0x7FC0_0001)),
176 &[0x01, 0x00, 0xC0, 0x7F],
177 ),
178 (
179 "write_f64",
180 |w| w.write_f64::<LE>(-1.5),
181 &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xBF],
182 ),
183 (
184 "write_f64",
185 |w| w.write_f64::<LE>(-0.0),
186 &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80],
187 ),
188 ];
189
190 struct TricklingWriter {
192 written: Vec<u8>,
193 interrupt: bool,
194 }
195
196 impl Write for TricklingWriter {
197 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
198 self.interrupt = !self.interrupt;
199 if self.interrupt {
200 return Err(io::ErrorKind::Interrupted.into());
201 }
202 self.written.extend_from_slice(&buf[..1]);
203 Ok(1)
204 }
205
206 fn flush(&mut self) -> io::Result<()> {
207 Ok(())
208 }
209 }
210
211 struct FullWriter {
213 capacity: usize,
214 full: FullFn,
215 }
216
217 impl Write for FullWriter {
218 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
219 if self.capacity == 0 {
220 return (self.full)();
221 }
222 let n = buf.len().min(self.capacity);
223 self.capacity -= n;
224 Ok(n)
225 }
226
227 fn flush(&mut self) -> io::Result<()> {
228 Ok(())
229 }
230 }
231
232 #[test]
233 fn little_endian_uses_only_the_leading_bytes_of_the_buffer() {
234 assert_eq!(LE::read_u32(&[0x04, 0x03, 0x02, 0x01, 0xFF]), 0x0102_0304);
235
236 let mut buf = [0xEE; 9];
237 LE::write_u32(&mut buf, 0x0102_0304);
238 assert_eq!(buf, [0x04, 0x03, 0x02, 0x01, 0xEE, 0xEE, 0xEE, 0xEE, 0xEE]);
239
240 let mut buf = [0xEE; 9];
241 LE::write_u64(&mut buf, 0x0102_0304_0506_0708);
242 assert_eq!(buf, [0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0xEE]);
243 }
244
245 #[test]
246 #[should_panic]
247 fn read_u32_panics_on_a_short_buffer() {
248 LE::read_u32(&[0; 3]);
249 }
250
251 #[test]
252 #[should_panic]
253 fn write_u32_panics_on_a_short_buffer() {
254 LE::write_u32(&mut [0; 3], 0);
255 }
256
257 #[test]
258 #[should_panic]
259 fn write_u64_panics_on_a_short_buffer() {
260 LE::write_u64(&mut [0; 7], 0);
261 }
262
263 #[test]
264 fn write_bytes_ext_writes_little_endian() {
265 for (name, write, expected) in WRITE_CASES {
266 let mut written = Vec::new();
267 write(&mut written).unwrap();
268 assert_eq!(written, *expected, "{name}");
269 }
270 }
271
272 #[test]
273 fn write_bytes_ext_completes_partial_and_interrupted_writes() {
274 for (name, write, expected) in WRITE_CASES {
275 let mut writer = TricklingWriter {
276 written: Vec::new(),
277 interrupt: false,
278 };
279 write(&mut writer).unwrap();
280 assert_eq!(writer.written, *expected, "{name}");
281 }
282 }
283
284 #[test]
285 fn write_bytes_ext_returns_write_errors() {
286 let cases: [(FullFn, io::ErrorKind); 2] = [
287 (|| Ok(0), io::ErrorKind::WriteZero),
289 (|| Err(io::ErrorKind::BrokenPipe.into()), io::ErrorKind::BrokenPipe),
290 ];
291 for (name, write, expected) in WRITE_CASES {
292 for (full, kind) in cases {
293 let mut writer = FullWriter {
294 capacity: expected.len() - 1,
295 full,
296 };
297 assert_eq!(write(&mut writer).unwrap_err().kind(), kind, "{name}");
298 }
299 }
300 }
301}