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
//! Tools for decoding and encoding integers.

#[cfg(rust_v_1_51)]
use crate::{Decoder, decoders::ByteArrayDecoder};

pub trait Int: sealed::Int {
    #[doc(hidden)]
    #[cfg(rust_v_1_51)]
    type Decoder: Decoder<Value = Self::Bytes, Error = crate::error::UnexpectedEnd> + Default;
    #[doc(hidden)]
    type Bytes: AsRef<[u8]>;

    #[doc(hidden)]
    fn from_le_bytes(bytes: Self::Bytes) -> Self;
    #[doc(hidden)]
    fn from_be_bytes(bytes: Self::Bytes) -> Self;
    #[doc(hidden)]
    fn to_le_bytes(self) -> Self::Bytes;
    #[doc(hidden)]
    fn to_be_bytes(self) -> Self::Bytes;
}

pub trait ByteOrder: sealed::ByteOrder {}

macro_rules! impl_int {
    ($($int:ty),+) => {
        $(
            impl Int for $int {
                #[cfg(rust_v_1_51)]
                type Decoder = ByteArrayDecoder<{ core::mem::size_of::<Self>() }>;
                type Bytes = [u8; { core::mem::size_of::<Self>() }];

                fn from_le_bytes(bytes: Self::Bytes) -> Self {
                    <$int>::from_le_bytes(bytes)
                }

                fn from_be_bytes(bytes: Self::Bytes) -> Self {
                    <$int>::from_be_bytes(bytes)
                }

                fn to_le_bytes(self) -> Self::Bytes {
                    <$int>::to_le_bytes(self)
                }

                fn to_be_bytes(self) -> Self::Bytes {
                    <$int>::to_be_bytes(self)
                }
            }

            impl sealed::Int for $int {}
        )+
    }
}

impl_int!(u8, i8, u16, i16, u32, i32, u64, i64, u128, i128);

mod sealed {
    pub trait Int {}
    pub trait ByteOrder {}
}

pub struct BigEndian {}
pub struct LittleEndian {}

impl ByteOrder for BigEndian {}
impl sealed::ByteOrder for BigEndian {}
impl ByteOrder for LittleEndian {}
impl sealed::ByteOrder for LittleEndian {}