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
use core::convert::TryInto;
use core::fmt::{Debug, Display, Formatter};
use super::types::Endianness;
pub trait TryFromBytes: Sized {
/// Creates number from its byte array representation in given endianness.
/// ```
/// use traiter::numbers::{Endianness, TryFromBytes};
/// /// signed integers
/// assert_eq!(
/// <i8 as TryFromBytes>::try_from_bytes(&[255u8], Endianness::Big),
/// Ok(-1i8)
/// );
/// assert_eq!(
/// <i8 as TryFromBytes>::try_from_bytes(&[0u8], Endianness::Big),
/// Ok(0i8)
/// );
/// assert_eq!(
/// <i8 as TryFromBytes>::try_from_bytes(&[1u8], Endianness::Big),
/// Ok(1i8)
/// );
/// assert!(
/// <i8 as TryFromBytes>::try_from_bytes(&[], Endianness::Big).is_err()
/// );
/// /// unsigned integers
/// assert_eq!(
/// <u8 as TryFromBytes>::try_from_bytes(&[0u8], Endianness::Big),
/// Ok(0u8)
/// );
/// assert_eq!(
/// <u8 as TryFromBytes>::try_from_bytes(&[1u8], Endianness::Big),
/// Ok(1u8)
/// );
/// assert_eq!(
/// <u8 as TryFromBytes>::try_from_bytes(&[2u8], Endianness::Big),
/// Ok(2u8)
/// );
/// assert!(
/// <u8 as TryFromBytes>::try_from_bytes(&[], Endianness::Big).is_err()
/// );
/// ```
type Error;
fn try_from_bytes(
bytes: &[u8],
endianness: Endianness,
) -> Result<Self, Self::Error>;
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum TryFromBytesError {
NotEnoughBytes,
TooManyBytes,
}
impl TryFromBytesError {
fn description(&self) -> &str {
match self {
TryFromBytesError::NotEnoughBytes => {
"Not enough bytes were provided."
}
TryFromBytesError::TooManyBytes => "Too many bytes were provided.",
}
}
}
impl Debug for TryFromBytesError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> core::fmt::Result {
formatter.write_str(self.description())
}
}
impl Display for TryFromBytesError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> core::fmt::Result {
Display::fmt(&self.description(), formatter)
}
}
macro_rules! integer_try_from_bytes_impl {
($($integer:ty)*) => ($(
impl TryFromBytes for $integer {
type Error = TryFromBytesError;
#[inline(always)]
fn try_from_bytes(
bytes: &[u8],
endianness: Endianness,
) -> Result<Self, Self::Error> {
bytes
.try_into()
.map(|value| match endianness {
Endianness::Big => <$integer>::from_be_bytes(value),
Endianness::Little => <$integer>::from_le_bytes(value),
})
.map_err(|_| {
if bytes.len() < (<$integer>::BITS as usize) / 8 {
TryFromBytesError::NotEnoughBytes
} else {
TryFromBytesError::TooManyBytes
}
})
}
}
)*)
}
integer_try_from_bytes_impl!(
i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize
);