1use std::alloc::Layout;
4use std::mem::{ManuallyDrop, MaybeUninit};
5
6pub unsafe trait ToByteArray: Copy {
13 type Align: AsRef<[u8]>;
15
16 type Bytes: AsRef<[u8]>;
18
19 fn to_bytes(self) -> Self::Bytes;
23}
24
25macro_rules! impl_to_byte_array {
26 ($type:ty) => {
27 unsafe impl ToByteArray for $type {
28 type Align = [u8; align_of::<$type>()];
29 type Bytes = [u8; size_of::<$type>()];
30
31 fn to_bytes(self) -> Self::Bytes {
32 self.to_ne_bytes()
33 }
34 }
35 };
36}
37
38impl_to_byte_array!(i8);
39impl_to_byte_array!(u8);
40impl_to_byte_array!(i16);
41impl_to_byte_array!(u16);
42impl_to_byte_array!(i32);
43impl_to_byte_array!(u32);
44impl_to_byte_array!(i64);
45impl_to_byte_array!(u64);
46impl_to_byte_array!(f32);
47impl_to_byte_array!(f64);
48
49unsafe impl ToByteArray for bool {
50 type Align = [u8; 1];
51 type Bytes = [u8; 1];
52
53 fn to_bytes(self) -> [u8; 1] {
54 [self as u8]
55 }
56}
57
58pub unsafe trait FromByteArray: ToByteArray {
67 fn from_bytes(bytes: Self::Bytes) -> Self;
71
72 fn cast_bytes<Dst>(self) -> Dst
76 where
77 Dst: FromByteArray<Bytes = Self::Bytes>,
78 {
79 Dst::from_bytes(self.to_bytes())
80 }
81}
82
83macro_rules! impl_from_byte_array {
84 ($type:ty) => {
85 unsafe impl FromByteArray for $type {
86 fn from_bytes(val: Self::Bytes) -> Self {
87 Self::from_ne_bytes(val)
88 }
89 }
90 };
91}
92
93impl_from_byte_array!(i8);
94impl_from_byte_array!(u8);
95impl_from_byte_array!(i16);
96impl_from_byte_array!(u16);
97impl_from_byte_array!(i32);
98impl_from_byte_array!(u32);
99impl_from_byte_array!(i64);
100impl_from_byte_array!(u64);
101impl_from_byte_array!(f32);
102impl_from_byte_array!(f64);
103
104fn transmuted_slice_len<Src, Dst>(src: &[Src]) -> Option<usize> {
107 if !(src.as_ptr() as usize).is_multiple_of(align_of::<Dst>()) {
108 return None;
109 }
110
111 let src_byte_len = std::mem::size_of_val(src);
112 if !src_byte_len.is_multiple_of(size_of::<Dst>()) {
113 return None;
114 }
115
116 Some(src_byte_len / size_of::<Dst>())
117}
118
119pub fn cast_slice<Src: ToByteArray, Dst: FromByteArray>(src: &[Src]) -> Option<&[Dst]> {
127 if src.is_empty() {
130 return Some(&[]);
131 }
132
133 let new_len = transmuted_slice_len::<_, Dst>(src)?;
134
135 Some(unsafe { std::slice::from_raw_parts(src.as_ptr() as *const Dst, new_len) })
139}
140
141#[allow(unused)]
149pub fn cast_mut_slice<Src: ToByteArray, Dst: FromByteArray>(src: &mut [Src]) -> Option<&mut [Dst]> {
150 if src.is_empty() {
153 return Some(&mut []);
154 }
155
156 let new_len = transmuted_slice_len::<_, Dst>(src)?;
157
158 Some(unsafe { std::slice::from_raw_parts_mut(src.as_mut_ptr() as *mut Dst, new_len) })
162}
163
164pub fn cast_uninit_mut_slice<Src: ToByteArray, Dst: FromByteArray>(
169 src: &mut [MaybeUninit<Src>],
170) -> Option<&mut [MaybeUninit<Dst>]> {
171 if src.is_empty() {
174 return Some(&mut []);
175 }
176
177 let new_len = transmuted_slice_len::<_, Dst>(src)?;
178
179 Some(unsafe {
183 std::slice::from_raw_parts_mut(src.as_mut_ptr() as *mut MaybeUninit<Dst>, new_len)
184 })
185}
186
187pub fn cast_vec<Src: ToByteArray, Dst: FromByteArray>(src: Vec<Src>) -> Option<Vec<Dst>> {
192 if src.capacity() == 0 {
195 return Some(Vec::new());
196 }
197
198 let mut src = ManuallyDrop::new(src);
200 let (src_ptr, src_len, src_cap) = (src.as_mut_ptr(), src.len(), src.capacity());
201
202 if Layout::array::<Src>(src_cap) != Layout::array::<Dst>(src_cap) {
203 return None;
204 }
205
206 Some(unsafe { Vec::from_raw_parts(src_ptr as *mut Dst, src_len, src_cap) })
210}
211
212pub unsafe trait AsBytes: Sized {
222 fn as_bytes(&self) -> &[u8] {
224 unsafe { std::slice::from_raw_parts(self as *const Self as *const u8, size_of::<Self>()) }
225 }
226
227 fn as_signed_bytes(&self) -> &[i8] {
229 unsafe { std::slice::from_raw_parts(self as *const Self as *const i8, size_of::<Self>()) }
230 }
231}
232
233pub unsafe trait FromBytes: Sized {
242 fn from_bytes(bytes: &[u8]) -> &Self {
247 assert!(
248 bytes.len() == size_of::<Self>()
249 && (bytes.as_ptr() as usize).is_multiple_of(align_of::<Self>())
250 );
251 unsafe { &*bytes.as_ptr().cast::<Self>() }
252 }
253}
254
255#[cfg(test)]
256mod tests {
257 use std::mem::MaybeUninit;
258
259 use super::{
260 AsBytes, FromByteArray, FromBytes, cast_mut_slice, cast_slice, cast_uninit_mut_slice,
261 cast_vec,
262 };
263
264 #[test]
265 fn test_cast_bytes() {
266 let float_val = 1.2f32;
267 let int_val: i32 = float_val.cast_bytes();
268 assert_eq!(int_val, i32::from_ne_bytes(float_val.to_ne_bytes()));
269 }
270
271 #[test]
272 fn test_cast_slice() {
273 let i32s = [1, 2, 3];
275 let i8s = cast_slice::<i32, i8>(&i32s).unwrap();
276 assert_eq!(i8s.as_ptr(), i32s.as_ptr() as *const i8);
277 assert_eq!(i8s.len(), i32s.len() * 4);
278
279 let i32s_v2 = cast_slice::<i8, i32>(i8s).unwrap();
281 assert_eq!(i32s_v2, i32s);
282 }
283
284 #[test]
285 fn test_cast_empty() {
286 let empty: Vec<u8> = Vec::new();
289 assert_eq!(cast_slice::<u8, i32>(&empty), Some([].as_slice()));
290
291 let mut empty: Vec<u8> = Vec::new();
292 assert_eq!(
293 cast_mut_slice::<u8, i32>(&mut empty),
294 Some([].as_mut_slice())
295 );
296
297 let mut empty: Vec<MaybeUninit<u8>> = Vec::new();
298 assert!(cast_uninit_mut_slice::<u8, i32>(&mut empty).is_some_and(|s| s.is_empty()));
299
300 let empty: Vec<u8> = Vec::new();
301 assert_eq!(cast_vec::<u8, i32>(empty), Some(Vec::new()));
302 }
303
304 #[test]
305 fn test_cast_vec() {
306 let i32s = Vec::from([1, 2, 3]);
308 let (ptr, len, cap) = (i32s.as_ptr(), i32s.len(), i32s.capacity());
309 let f32s = cast_vec::<i32, f32>(i32s).unwrap();
310 assert_eq!(f32s.as_ptr(), ptr as *const f32);
311 assert_eq!(f32s.len(), len);
312 assert_eq!(f32s.capacity(), cap);
313
314 let i32s = Vec::from([1, 2, 3]);
316 let i8s = cast_vec::<i32, i8>(i32s);
317 assert!(i8s.is_none());
318 }
319
320 #[test]
321 fn test_cast_slice_fails_if_unaligned() {
322 let i8s = [1, 2, 3, 4, 5];
323 let i32s_a = cast_slice::<i8, i32>(&i8s);
324 let i32s_b = cast_slice::<i8, i32>(&i8s[1..]);
325
326 assert!(i32s_a.is_none() || i32s_b.is_none());
328 }
329
330 #[test]
331 fn test_cast_slice_fails_if_size_not_multiple_of_dst_size() {
332 let i8s = [1, 2, 3, 4, 5];
333 let i32s = cast_slice::<i8, i32>(&i8s);
334 assert!(i32s.is_none());
335 }
336
337 #[test]
338 fn test_cast_mut_slice() {
339 let mut i32s = [1, 2, 3];
340 let i32s_ptr = i32s.as_ptr();
341 let i8s = cast_mut_slice::<i32, i8>(&mut i32s).unwrap();
342 assert_eq!(i8s.as_ptr(), i32s_ptr as *const i8);
343 assert_eq!(i8s.len(), i32s.len() * 4);
344 }
345
346 #[test]
347 fn test_cast_uninit_mut_slice() {
348 let mut i32s = [1, 2, 3].map(MaybeUninit::new);
349 let i32s_ptr = i32s.as_ptr();
350 let i8s = cast_uninit_mut_slice::<i32, i8>(&mut i32s).unwrap();
351 assert_eq!(i8s.as_ptr(), i32s_ptr as *const MaybeUninit<i8>);
352 assert_eq!(i8s.len(), i32s.len() * 4);
353 }
354
355 #[test]
356 fn test_as_bytes_and_from_bytes() {
357 #[derive(Debug, PartialEq)]
358 struct SomeData {
359 field_a: [i32; 2],
360 field_b: [i32; 2],
361 }
362 unsafe impl AsBytes for SomeData {}
364 unsafe impl FromBytes for SomeData {}
365
366 let data = SomeData {
367 field_a: [1, 2],
368 field_b: [3, 4],
369 };
370 let bytes = data.as_bytes();
371
372 let recreated_data = SomeData::from_bytes(bytes);
373 assert_eq!(recreated_data, &data);
374 }
375}