1use std::{mem,slice};
2
3pub trait As{
5 fn as_bytes(&self) -> &[u8];
7
8 unsafe fn as_bytes_mut(&mut self) -> &mut [u8];
10}
11
12pub trait From{
14 unsafe fn from_bytes(bytes: &[u8]) -> Self;
16}
17
18impl<T> As for T
19 where T: Sized + Copy
20{
21 #[inline(always)]
22 fn as_bytes(&self) -> &[u8]{
23 unsafe{slice::from_raw_parts(
24 self as *const T as *const u8,
25 mem::size_of::<T>()
26 )}
27 }
28
29 #[inline(always)]
30 unsafe fn as_bytes_mut(&mut self) -> &mut [u8]{
31 slice::from_raw_parts_mut(
32 self as *mut T as *mut u8,
33 mem::size_of::<T>()
34 )
35 }
36}
37
38impl<T> From for T
40 where T: Sized + Copy
41{
42 #[inline(always)]
43 unsafe fn from_bytes(bytes: &[u8]) -> Self{
44 debug_assert!(bytes.len() >= mem::size_of::<T>());
45 *(bytes.as_ptr() as *const T)
46 }
47}
48
49#[test]
50fn test(){
51 let list: [u8;4] = [0x00,0x01,0x02,0x03];
52 assert_eq!((list[0],list[1],list[2],list[3]),(0x00,0x01,0x02,0x03));
53
54 let bytes = list.as_bytes();
55 assert_eq!((bytes[0],bytes[1],bytes[2],bytes[3]),(0x00,0x01,0x02,0x03));
56
57 let list: [u8;4] = unsafe{From::from_bytes(bytes)};
58 assert_eq!((list[0],list[1],list[2],list[3]),(0x00,0x01,0x02,0x03));
59}