binbin/
endian.rs

1/// A sealed trait that has only [`LittleEndian`](LittleEndian) and
2/// [`BigEndian`](BigEndian) as its implementations.
3pub trait Endian: private::Sealed {
4    /// Writes the least significant `into.len()` bytes from `v` into the
5    /// buffer that `into` refers to.
6    fn write_integer(v: u64, into: &mut [u8]);
7}
8
9/// Selects little-endian encoding in type parameters that represent selectable
10/// endianness.
11///
12/// There are no values of this type.
13pub enum LittleEndian {}
14
15impl Endian for LittleEndian {
16    fn write_integer(v: u64, into: &mut [u8]) {
17        let l = into.len();
18        for i in 0..l {
19            into[i] = (v >> (8 * i)) as u8;
20        }
21    }
22}
23
24/// Selects big-endian encoding in type parameters that represent selectable
25/// endianness.
26///
27/// There are no values of this type.
28pub enum BigEndian {}
29
30impl Endian for BigEndian {
31    fn write_integer(v: u64, into: &mut [u8]) {
32        let l = into.len();
33        for i in 0..l {
34            let shift = 8 * (l - i - 1);
35            into[i] = (v >> shift) as u8;
36        }
37    }
38}
39
40mod private {
41    pub trait Sealed {}
42
43    impl Sealed for super::BigEndian {}
44    impl Sealed for super::LittleEndian {}
45}