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
#![allow(unused_parens)]

use core::convert::TryInto;
use core::mem;
use {check_len, Error, Result, TryRead, TryWrite};

/// Endian of numbers.
///
/// Default to machine's native endian.
///
/// # Example
///
/// ```
/// use byte::*;
///
/// let bytes: &[u8] = &[0x00, 0xff];
///
/// let num_be: u16 = bytes.read_with(&mut 0, BE).unwrap();
/// assert_eq!(num_be, 0x00ff);
///
/// let num_le: u16 = bytes.read_with(&mut 0, LE).unwrap();
/// assert_eq!(num_le, 0xff00);
/// ```
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Endian {
    /// Little Endian byte order context
    Little,
    /// Big Endian byte order context
    Big,
}

impl Default for Endian {
    #[inline]
    fn default() -> Self {
        NATIVE
    }
}

/// Little Endian byte order
pub const LE: Endian = Endian::Little;
/// Big Endian byte order
pub const BE: Endian = Endian::Big;

/// Network endian
pub const NETWORK: Endian = Endian::Little;

/// The machine's native endian
#[cfg(target_endian = "little")]
pub const NATIVE: Endian = LE;
/// The machine's native endian
#[cfg(target_endian = "big")]
pub const NATIVE: Endian = BE;

macro_rules! num_impl {
    ($ty: ty, $size: tt) => {
        impl<'a> TryRead<'a, Endian> for $ty {
            #[inline]
            fn try_read(bytes: &'a [u8], endian: Endian) -> Result<(Self, usize)> {
                check_len(bytes, $size)?;

                let val = match endian {
                    Endian::Big => {
                      <$ty>::from_be_bytes(bytes[..$size].try_into().map_err(|_e| Error::BadInput {
                        err: "TryIntoSliceError",
                      })?)
                    }
                    Endian::Little => {
                      <$ty>::from_le_bytes(bytes[..$size].try_into().map_err(|_e| Error::BadInput {
                        err: "TryIntoSliceError",
                      })?)
                    }
                };

                Ok((val, $size))
            }
        }

        impl TryWrite<Endian> for $ty {
            #[inline]
            fn try_write(self, bytes: &mut [u8], endian: Endian) -> Result<usize> {
                check_len(bytes, $size)?;

                let _val = match endian {
                    Endian::Big => bytes[..$size].copy_from_slice(&self.to_be_bytes()),
                    Endian::Little => bytes[..$size].copy_from_slice(&self.to_le_bytes()),
                };

                Ok($size)
            }
        }
    };
}

num_impl!(u8, 1);
num_impl!(u16, 2);
num_impl!(u32, 4);
num_impl!(u64, 8);
num_impl!(i8, 1);
num_impl!(i16, 2);
num_impl!(i32, 4);
num_impl!(i64, 8);
num_impl!(usize, (mem::size_of::<usize>()));
num_impl!(isize, (mem::size_of::<isize>()));

macro_rules! float_impl {
    ($ty: ty, $base: ty) => {
        impl<'a> TryRead<'a, Endian> for $ty {
            #[inline]
            fn try_read(bytes: &'a [u8], endian: Endian) -> Result<(Self, usize)> {
                <$base as TryRead<'a, Endian>>::try_read(bytes, endian)
                    .map(|(val, size)| (unsafe { mem::transmute(val) }, size))
            }
        }

        impl<'a> TryWrite<Endian> for $ty {
            #[inline]
            fn try_write(self, bytes: &mut [u8], endian: Endian) -> Result<usize> {
                <$base as TryWrite<Endian>>::try_write(
                    unsafe { mem::transmute(self) },
                    bytes,
                    endian,
                )
            }
        }
    };
}

float_impl!(f32, u32);
float_impl!(f64, u64);