byte_conv/
lib.rs

1use std::{mem,slice};
2
3///A type which is representable as bytes
4pub trait As{
5	///Represent a pointer to a type as an array of bytes
6	fn as_bytes(&self) -> &[u8];
7
8	///Represent a mutable pointer to a type as a mutable array of bytes
9	unsafe fn as_bytes_mut(&mut self) -> &mut [u8];
10}
11
12///A type which can be constructed from bytes unsafely
13pub trait From{
14	///Construct a type from an array of bytes
15	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
38//TODO: This is safe if all values are valid, but not otherwise (What is this called? Total relation/mapping for bytes?)
39impl<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}