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
use super::*;
#[repr(transparent)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct PlainOldULE<const N: usize>(pub [u8; N]);
macro_rules! impl_byte_slice_size {
($size:literal) => {
impl From<[u8; $size]> for PlainOldULE<$size> {
#[inline]
fn from(le_bytes: [u8; $size]) -> Self {
Self(le_bytes)
}
}
impl PlainOldULE<$size> {
#[inline]
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
}
impl ULE for PlainOldULE<$size> {
type Error = std::convert::Infallible;
#[inline]
fn parse_byte_slice(bytes: &[u8]) -> Result<&[Self], Self::Error> {
let data = bytes.as_ptr();
let len = bytes.len() / $size;
Ok(unsafe { std::slice::from_raw_parts(data as *const Self, len) })
}
#[inline]
fn as_byte_slice(slice: &[Self]) -> &[u8] {
let data = slice.as_ptr();
let len = slice.len() * $size;
unsafe { std::slice::from_raw_parts(data as *const u8, len) }
}
}
};
}
macro_rules! impl_byte_slice_type {
($type:ty, $size:literal) => {
impl From<$type> for PlainOldULE<$size> {
#[inline]
fn from(value: $type) -> Self {
Self(value.to_le_bytes())
}
}
impl AsULE for $type {
type ULE = PlainOldULE<$size>;
#[inline]
fn as_unaligned(&self) -> Self::ULE {
PlainOldULE(self.to_le_bytes())
}
#[inline]
fn from_unaligned(unaligned: &Self::ULE) -> Self {
<$type>::from_le_bytes(unaligned.0)
}
}
};
}
impl_byte_slice_size!(2);
impl_byte_slice_size!(4);
impl_byte_slice_size!(8);
impl_byte_slice_size!(16);
impl_byte_slice_type!(u16, 2);
impl_byte_slice_type!(u32, 4);
impl_byte_slice_type!(u64, 8);
impl_byte_slice_type!(u128, 16);
impl_byte_slice_type!(i16, 2);
impl_byte_slice_type!(i32, 4);
impl_byte_slice_type!(i64, 8);
impl_byte_slice_type!(i128, 16);