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
//! Reading data directly from a buffer
use displaydoc::Display;
use thiserror::Error;

/// Errors from casting a minimally-aligned type
#[derive(Debug, Error, Display)]
pub enum CastError {
    /// Some byte between start and end was outside of the given buffer
    OutOfBounds {
        /// The offset that failed
        offset: u32,
    },
}

/// Asserts that the type has a minimal ABI alignment of `1`
///
/// ## Safety
///
/// Implementor need to verify that [`std::mem::align_of`]`::<Self>() == 1`
pub unsafe trait MinimallyAligned: Sized {}

/// Cast a buffer to a reference
///
/// ## Panics
///
/// - If the `[offset, offset + size_of::<Self>]` is not contained by the buffer
pub fn cast<T: MinimallyAligned>(buffer: &[u8], offset: u32) -> &T {
    try_cast(buffer, offset).unwrap()
}

/// Try to cast a buffer to a reference
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 })
    }
}

/// Cast a buffer to a slice
///
/// ## Panics
///
/// - If the `[offset, offset + len]` is not contained by the buffer
pub fn cast_slice<T: MinimallyAligned>(buffer: &[u8], offset: u32, len: u32) -> &[T] {
    try_cast_slice(buffer, offset, len).unwrap()
}

/// Try to cast a buffer to a slice
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 })
    }
}

/// Additional methods on byte slices
pub trait Buffer {
    /// Try to cast to T
    fn try_cast<T: MinimallyAligned>(&self, offset: u32) -> Result<&T, CastError>;

    /// Try to cast to T
    fn try_cast_slice<T: MinimallyAligned>(&self, offset: u32, len: u32)
        -> Result<&[T], CastError>;

    /// Cast to T
    fn cast<T: MinimallyAligned>(&self, offset: u32) -> &T;

    /// Cast to slice of T
    fn cast_slice<T: MinimallyAligned>(&self, offset: u32, len: u32) -> &[T];
}

impl Buffer for [u8] {
    /// Try to cast to T
    fn try_cast<T: MinimallyAligned>(&self, offset: u32) -> Result<&T, CastError> {
        try_cast(self, offset)
    }

    /// Try to cast to T
    fn try_cast_slice<T: MinimallyAligned>(
        &self,
        offset: u32,
        len: u32,
    ) -> Result<&[T], CastError> {
        try_cast_slice(self, offset, len)
    }

    /// Cast to T
    fn cast<T: MinimallyAligned>(&self, offset: u32) -> &T {
        cast(self, offset)
    }

    /// Cast to slice of T
    fn cast_slice<T: MinimallyAligned>(&self, offset: u32, len: u32) -> &[T] {
        cast_slice(self, offset, len)
    }
}

/// Similar to `From<&U> for T`
pub trait Repr {
    /// The value that this struct encodes
    type Value;

    /// extract the contained value
    fn extract(&self) -> Self::Value;
}

/// little-endian u16
#[repr(C, align(1))]
pub struct LEU16([u8; 2]);

/// little-endian u32
#[repr(C, align(1))]
#[derive(Debug)]
pub struct LEU32([u8; 4]);

/// little-endian u64
#[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);
    }
}