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
use displaydoc::Display;
use thiserror::Error;
#[derive(Debug, Error, Display)]
pub enum CastError {
OutOfBounds {
offset: u32,
},
}
pub unsafe trait MinimallyAligned: Sized {}
pub fn cast<T: MinimallyAligned>(buffer: &[u8], offset: u32) -> &T {
try_cast(buffer, offset).unwrap()
}
pub fn try_cast<T: MinimallyAligned>(buffer: &[u8], offset: u32) -> Result<&T, CastError> {
let base = buffer.as_ptr();
let len = buffer.len();
if offset as usize + std::mem::size_of::<T>() <= len {
unsafe {
let addr = base.offset(offset as isize);
Ok(&*(addr as *const T))
}
} else {
Err(CastError::OutOfBounds { offset })
}
}
pub fn cast_slice<T: MinimallyAligned>(buffer: &[u8], offset: u32, len: u32) -> &[T] {
try_cast_slice(buffer, offset, len).unwrap()
}
pub fn try_cast_slice<T: MinimallyAligned>(
buffer: &[u8],
offset: u32,
len: u32,
) -> Result<&[T], CastError> {
let base = buffer.as_ptr();
let buf_len = buffer.len();
let ulen = len as usize;
let needed = std::mem::size_of::<T>() * ulen;
if offset as usize + needed <= buf_len {
unsafe {
let addr = base.offset(offset as isize) as *const T;
Ok(std::slice::from_raw_parts(addr, ulen))
}
} else {
Err(CastError::OutOfBounds { offset })
}
}
pub trait Repr {
type Value;
fn extract(&self) -> Self::Value;
}
#[repr(C, align(1))]
pub struct LEU16([u8; 2]);
#[repr(C, align(1))]
pub struct LEU32([u8; 4]);
#[repr(C, align(1))]
pub struct LEI64([u8; 8]);
unsafe impl MinimallyAligned for LEU16 {}
impl Repr for LEU16 {
type Value = u16;
fn extract(&self) -> Self::Value {
u16::from_le_bytes(self.0)
}
}
unsafe impl MinimallyAligned for LEU32 {}
impl Repr for LEU32 {
type Value = u32;
fn extract(&self) -> Self::Value {
u32::from_le_bytes(self.0)
}
}
unsafe impl MinimallyAligned for LEI64 {}
impl Repr for LEI64 {
type Value = i64;
fn extract(&self) -> Self::Value {
i64::from_le_bytes(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let buffer: &[u8] = &[0, 20, 0, 30, 0, 1, 1];
let le: &LEU16 = cast(buffer, 1);
assert_eq!(le.extract(), 20);
let le: &LEU16 = cast(buffer, 3);
assert_eq!(le.extract(), 30);
let le: &LEU16 = cast(buffer, 5);
assert_eq!(le.extract(), 257);
let les: &[LEU16] = cast_slice(buffer, 1, 3);
assert_eq!(les[0].extract(), 20);
assert_eq!(les[1].extract(), 30);
assert_eq!(les[2].extract(), 257);
assert_eq!(std::mem::align_of::<LEU16>(), 1);
}
}