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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
#![no_std]

use core::ops::{BitAnd, BitOr, BitXor};
use core::{mem, slice};

///Type with a specified byte order.
pub trait Endian<T> {}

macro_rules! impl_Endian{
    ( for $e:ident) => {
        impl<T> BitAnd for $e<T>
        where
            T: BitAnd,
        {
            type Output = $e<<T as BitAnd>::Output>;

            #[inline]
            fn bitand(self, other: Self) -> Self::Output {
                $e(self.0 & other.0)
            }
        }

        impl<T> BitOr for $e<T>
        where
            T: BitOr,
        {
            type Output = $e<<T as BitOr>::Output>;

            #[inline]
            fn bitor(self, other: Self) -> Self::Output {
                $e(self.0 | other.0)
            }
        }

        impl<T> BitXor for $e<T>
        where
            T: BitXor,
        {
            type Output = $e<<T as BitXor>::Output>;

            #[inline]
            fn bitxor(self, other: Self) -> Self::Output {
                $e(self.0 ^ other.0)
            }
        }

        impl<T> $e<T>
        where
            T: Sized + Copy,
        {
            #[inline]
            pub const unsafe fn from_byte_slice(bytes: &[u8]) -> $e<T> {
                debug_assert!(bytes.len() >= mem::size_of::<T>());
                $e({ *(bytes.as_ptr() as *const T) })
            }

            #[inline]
            pub fn as_byte_slice(&self) -> &[u8] {
                unsafe { slice::from_raw_parts(&self.0 as *const T as *const u8, mem::size_of::<T>()) }
            }

            #[inline]
            pub fn as_byte_slice_mut(&mut self) -> &mut [u8] {
                unsafe { slice::from_raw_parts_mut(&mut self.0 as *mut T as *mut u8, mem::size_of::<T>()) }
            }
        }
    }
}

///Big endian byte order.
///
///Most significant byte first.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
#[repr(transparent)]
pub struct BigEndian<T>(T);

impl<T> Endian<T> for BigEndian<T> {}

macro_rules! impl_for_BigEndian {
    ( $t:ident ) => {
        impl From<BigEndian<$t>> for $t {
            #[inline]
            fn from(data: BigEndian<$t>) -> $t {
                $t::from_be(data.0)
            }
        }

        impl From<$t> for BigEndian<$t> {
            #[inline]
            fn from(data: $t) -> Self {
                BigEndian(data.to_be())
            }
        }

        impl From<LittleEndian<$t>> for BigEndian<$t> {
            #[inline]
            fn from(data: LittleEndian<$t>) -> Self {
                BigEndian(data.0.swap_bytes())
            }
        }

        //TODO: Move these to Endian when https://github.com/rust-lang/rust/issues/67792 stabilized in a few years
        impl BigEndian<$t>{
            ///Return the memory representation of this type as a byte array in its endian byte order.
            ///Note: This is just a transmute.
            #[inline]
            pub const fn to_bytes(self) -> [u8; mem::size_of::<BigEndian<$t>>()] {
                unsafe { mem::transmute(self) }
            }

            ///Construct a value from its memory representation as a byte array.
            ///Note: This is just a transmute.
            #[inline]
            pub const fn from_bytes(bytes: [u8; mem::size_of::<BigEndian<$t>>()]) -> BigEndian<$t> {
                unsafe { mem::transmute(bytes) }
            }
        }
    };
}

impl_Endian!(for BigEndian);
impl_for_BigEndian!(u16);
impl_for_BigEndian!(u32);
impl_for_BigEndian!(u64);
impl_for_BigEndian!(u128);
impl_for_BigEndian!(usize);
impl_for_BigEndian!(i16);
impl_for_BigEndian!(i32);
impl_for_BigEndian!(i64);
impl_for_BigEndian!(i128);
impl_for_BigEndian!(isize);

///Little endian byte order.
///
///Least significant byte first.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
#[repr(transparent)]
pub struct LittleEndian<T>(T);

impl<T> Endian<T> for LittleEndian<T> {}

macro_rules! impl_for_LittleEndian {
    ( $t:ident ) => {
        impl From<LittleEndian<$t>> for $t {
            #[inline]
            fn from(data: LittleEndian<$t>) -> $t {
                $t::from_le(data.0)
            }
        }

        impl From<$t> for LittleEndian<$t> {
            #[inline]
            fn from(data: $t) -> Self {
                LittleEndian(data.to_le())
            }
        }

        impl From<BigEndian<$t>> for LittleEndian<$t> {
            #[inline]
            fn from(data: BigEndian<$t>) -> Self {
                LittleEndian(data.0.swap_bytes())
            }
        }

        impl LittleEndian<$t>{
            ///Return the memory representation of this type as a byte array in its endian byte order.
            ///Note: This is just a transmute.
            #[inline]
            pub const fn to_bytes(self) -> [u8; mem::size_of::<LittleEndian<$t>>()] {
                unsafe { mem::transmute(self) }
            }

            ///Construct a value from its memory representation as a byte array.
            ///Note: This is just a transmute.
            #[inline]
            pub const fn from_bytes(bytes: [u8; mem::size_of::<LittleEndian<$t>>()]) -> LittleEndian<$t> {
                unsafe { mem::transmute(bytes) }
            }
        }
    };
}

impl_Endian!(for LittleEndian);
impl_for_LittleEndian!(u16);
impl_for_LittleEndian!(u32);
impl_for_LittleEndian!(u64);
impl_for_LittleEndian!(u128);
impl_for_LittleEndian!(usize);
impl_for_LittleEndian!(i16);
impl_for_LittleEndian!(i32);
impl_for_LittleEndian!(i64);
impl_for_LittleEndian!(i128);
impl_for_LittleEndian!(isize);

///Network byte order as defined by IETF RFC1700 <http://tools.ietf.org/html/rfc1700>.
pub type NetworkOrder<T> = BigEndian<T>;

///Type aliases for primitive types.
pub mod types {
    #![allow(non_camel_case_types)]

    use super::*;

    pub type i16_be = BigEndian<i16>;
    pub type i32_be = BigEndian<i32>;
    pub type i64_be = BigEndian<i64>;
    pub type i128_be = BigEndian<i128>;
    pub type isize_be = BigEndian<isize>;

    pub type u16_be = BigEndian<u16>;
    pub type u32_be = BigEndian<u32>;
    pub type u64_be = BigEndian<u64>;
    pub type u128_be = BigEndian<u128>;
    pub type usize_be = BigEndian<usize>;

    pub type i16_le = LittleEndian<i16>;
    pub type i32_le = LittleEndian<i32>;
    pub type i64_le = LittleEndian<i64>;
    pub type i128_le = LittleEndian<i128>;
    pub type isize_le = LittleEndian<isize>;

    pub type u16_le = LittleEndian<u16>;
    pub type u32_le = LittleEndian<u32>;
    pub type u64_le = LittleEndian<u64>;
    pub type u128_le = LittleEndian<u128>;
    pub type usize_le = LittleEndian<usize>;

    pub type i16_net = NetworkOrder<i16>;
    pub type i32_net = NetworkOrder<i32>;
    pub type i128_net = NetworkOrder<i128>;
    pub type isize_net = NetworkOrder<isize>;

    pub type u16_net = NetworkOrder<u16>;
    pub type u32_net = NetworkOrder<u32>;
    pub type u64_net = NetworkOrder<u64>;
    pub type u128_net = NetworkOrder<u128>;
    pub type usize_net = NetworkOrder<usize>;
}

#[cfg(test)]
mod tests{
    use super::*;
    use super::types::*;

    #[test]
    fn from_to_bytes(){
        macro_rules! test{
            ($e:ident for $t:ident in $r:expr) => {
                for i in $r{
                    let j = $e::<$t>::from(i);
                    assert_eq!($e::<$t>::from_bytes(j.to_bytes()) , j);
                }
            }
        }

        test!(BigEndian for i16  in -10000..10000);
        test!(BigEndian for i32  in -10000..10000);
        test!(BigEndian for i64  in -10000..10000);
        test!(BigEndian for i128 in -10000..10000);

        test!(LittleEndian for i16  in -10000..10000);
        test!(LittleEndian for i32  in -10000..10000);
        test!(LittleEndian for i64  in -10000..10000);
        test!(LittleEndian for i128 in -10000..10000);

        test!(BigEndian for u16  in 0..20000);
        test!(BigEndian for u32  in 0..20000);
        test!(BigEndian for u64  in 0..20000);
        test!(BigEndian for u128 in 0..20000);

        test!(LittleEndian for u16  in 0..20000);
        test!(LittleEndian for u32  in 0..20000);
        test!(LittleEndian for u64  in 0..20000);
        test!(LittleEndian for u128 in 0..20000);
    }

    #[test]
    fn to_bytes_std(){
        macro_rules! test{
            ( for $t:ident in $r:expr) => {
                for i in $r{
                    assert_eq!(   BigEndian::<$t>::from(i).to_bytes() , i.to_be_bytes());
                    assert_eq!(LittleEndian::<$t>::from(i).to_bytes() , i.to_le_bytes());
                }
            }
        }

        test!(for i16  in -10000..10000);
        test!(for i32  in -10000..10000);
        test!(for i64  in -10000..10000);
        test!(for i128 in -10000..10000);

        test!(for i16  in 0..20000);
        test!(for i32  in 0..20000);
        test!(for i64  in 0..20000);
        test!(for i128 in 0..20000);
    }

    #[test]
    fn as_to_byte_slice(){
        macro_rules! test{
            ($e:ident for $t:ident in $r:expr) => {
                for i in $r{
                    let mut j = $e::<$t>::from(i);
                    assert_eq!(unsafe{$e::<$t>::from_byte_slice(j.as_byte_slice())} , j);
                    assert_eq!(unsafe{$e::<$t>::from_byte_slice(j.as_byte_slice_mut())} , j);
                }
            }
        }

        test!(BigEndian for i16  in -10000..10000);
        test!(BigEndian for i32  in -10000..10000);
        test!(BigEndian for i64  in -10000..10000);
        test!(BigEndian for i128 in -10000..10000);

        test!(LittleEndian for i16  in -10000..10000);
        test!(LittleEndian for i32  in -10000..10000);
        test!(LittleEndian for i64  in -10000..10000);
        test!(LittleEndian for i128 in -10000..10000);

        test!(BigEndian for u16  in 0..20000);
        test!(BigEndian for u32  in 0..20000);
        test!(BigEndian for u64  in 0..20000);
        test!(BigEndian for u128 in 0..20000);

        test!(LittleEndian for u16  in 0..20000);
        test!(LittleEndian for u32  in 0..20000);
        test!(LittleEndian for u64  in 0..20000);
        test!(LittleEndian for u128 in 0..20000);
    }

}

#[cfg(doctest)]
mod test_readme {
    macro_rules! external_doc_test {
        ($x:expr) => {
            #[doc = $x]
            extern {}
        };
    }
    external_doc_test!(include_str!("../README.md"));
}