Skip to main content

byteorder/
lib.rs

1//! The subset of the [`byteorder`][upstream] 1.x API that our dependencies use.
2//!
3//! The `[patch.crates-io]` section of the workspace manifest replaces crates.io `byteorder` with this crate. It keeps
4//! upstream's names, signatures, and behavior, but only for the items that our dependencies use. When a dependency
5//! needs an item that's missing here, the build fails instead of behaving differently, and the item can be added then.
6//!
7//! The API and behavior are derived from `byteorder` 1.5.0 by Andrew Gallant, licensed under `Unlicense OR MIT`.
8//!
9//! [upstream]: https://github.com/BurntSushi/byteorder
10
11// TODO: Remove this crate and its Cargo patch once a crates.io release includes the AIX alignment fix:
12// https://github.com/BurntSushi/byteorder/pull/223
13
14#![deny(missing_docs)]
15#![cfg_attr(not(feature = "std"), no_std)]
16
17#[cfg(feature = "std")]
18use std::io;
19
20/// Reads and writes numbers in a specific byte order.
21pub trait ByteOrder {
22    /// Reads an unsigned 32-bit integer from the first four bytes of `buf`.
23    ///
24    /// # Panics
25    ///
26    /// Panics when `buf.len() < 4`.
27    fn read_u32(buf: &[u8]) -> u32;
28
29    /// Writes an unsigned 32-bit integer to the first four bytes of `buf`.
30    ///
31    /// # Panics
32    ///
33    /// Panics when `buf.len() < 4`.
34    fn write_u32(buf: &mut [u8], n: u32);
35
36    /// Writes an unsigned 64-bit integer to the first eight bytes of `buf`.
37    ///
38    /// # Panics
39    ///
40    /// Panics when `buf.len() < 8`.
41    fn write_u64(buf: &mut [u8], n: u64);
42}
43
44/// Little-endian byte order.
45///
46/// This type has no values: use it as a type parameter.
47pub enum LittleEndian {}
48
49/// An alias for [`LittleEndian`].
50pub 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/// Extends [`io::Write`] with methods for writing numbers.
70///
71/// Each method writes the whole value with [`io::Write::write_all`], and returns its error if it fails.
72#[cfg(feature = "std")]
73pub trait WriteBytesExt: io::Write {
74    /// Writes an unsigned 8-bit integer.
75    #[inline]
76    fn write_u8(&mut self, n: u8) -> io::Result<()> {
77        self.write_all(&[n])
78    }
79
80    /// Writes an unsigned 32-bit integer in the byte order `T`.
81    #[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    /// Writes a signed 32-bit integer in the byte order `T`.
92    #[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    /// Writes an unsigned 64-bit integer in the byte order `T`.
101    #[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    /// Writes a signed 64-bit integer in the byte order `T`.
112    #[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    /// Writes an IEEE 754 single-precision floating point number in the byte order `T`.
121    #[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    /// Writes an IEEE 754 double-precision floating point number in the byte order `T`.
130    #[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    /// Every `WriteBytesExt` method, with a value whose encoding shows its byte order, and that encoding.
153    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        // A NaN with a payload, to check that the bits are written unchanged.
173        (
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    /// Accepts at most one byte per call, and fails every other call with `ErrorKind::Interrupted`.
191    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    /// Accepts `capacity` bytes, then answers every call with `full`.
212    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            // `write_all` reports a writer that stops accepting bytes as `WriteZero`.
288            (|| 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}