1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use crate::{FromStream, ToStream};

use std::io::{Read, Result, Write};

/// The endian encoding of numbers.
pub enum Endian {
    /// Little endian encoding.
    Little,
    /// Big endian encoding.
    Big,
    /// The native endian encoding of the system.
    Native,
}

/// The endian settings required for reading and writing numbers.
pub trait EndianSettings: Sized {
    /// The endian used by these endian settings.
    const ENDIAN: Endian;
}

/// Simple settings for using little endian encoding.
pub struct LittleEndian;
/// Simple settings for using big endian encoding.
pub struct BigEndian;
/// Simple settings for using native endian encoding.
pub struct NativeEndian;

impl EndianSettings for LittleEndian {
    const ENDIAN: Endian = Endian::Little;
}

impl EndianSettings for BigEndian {
    const ENDIAN: Endian = Endian::Big;
}

impl EndianSettings for NativeEndian {
    const ENDIAN: Endian = Endian::Native;
}

macro_rules! impl_num {
    ($t: ty) => {
        impl<S: EndianSettings> ToStream<S> for $t {
            fn to_stream<W: Write>(&self, stream: &mut W) -> Result<()> {
                use Endian::*;
                let bytes = match S::ENDIAN {
                    Little => self.to_le_bytes(),
                    Big => self.to_be_bytes(),
                    Native => self.to_ne_bytes(),
                };

                stream.write_all(&bytes)?;

                Ok(())
            }
        }

        impl<S: EndianSettings> FromStream<S> for $t {
            fn from_stream<R: Read>(stream: &mut R) -> Result<Self> {
                const SIZE: usize = std::mem::size_of::<$t>();
                let mut bytes = [0; SIZE];

                stream.read_exact(&mut bytes)?;

                use Endian::*;
                Ok(match S::ENDIAN {
                    Little => Self::from_le_bytes(bytes),
                    Big => Self::from_be_bytes(bytes),
                    Native => Self::from_ne_bytes(bytes),
                })
           }
        }
    };
    ($t: ty, $($rest: ty),+) => {
        impl_num!($t);
        impl_num!($($rest),+);
    };
}

impl_num!(u8, u16, u32, u64, u128);
impl_num!(i8, i16, i32, i64, i128);
impl_num!(f32, f64);
impl_num!(usize);