@@ -46,14 +46,16 @@ pub trait FromBytes {
46
46
47
47
impl < T > FromBytes for T
48
48
where
49
- T : Byteable + Clone ,
49
+ T : Byteable + Copy ,
50
50
{
51
51
fn from_bytes ( bytes : & [ u8 ] ) -> Self {
52
- unsafe {
53
- let byte_ptr = bytes. as_ptr ( ) ;
54
- let ptr = byte_ptr as * const Self ;
55
- ( * ptr) . clone ( )
56
- }
52
+ assert_eq ! (
53
+ bytes. len( ) ,
54
+ std:: mem:: size_of:: <T >( ) ,
55
+ "Cannot convert byte slice `&[u8]` to type `{}`. They are not the same size." ,
56
+ std:: any:: type_name:: <T >( )
57
+ ) ;
58
+ unsafe { bytes. as_ptr ( ) . cast :: < T > ( ) . read_unaligned ( ) }
57
59
}
58
60
}
59
61
62
64
T : Byteable ,
63
65
{
64
66
fn as_bytes ( & self ) -> & [ u8 ] {
65
- let len = std:: mem:: size_of_val ( self ) ;
67
+ let len = std:: mem:: size_of :: < T > ( ) ;
66
68
unsafe { core:: slice:: from_raw_parts ( self as * const Self as * const u8 , len) }
67
69
}
68
70
}
@@ -166,15 +168,23 @@ where
166
168
167
169
impl < T > FromBytes for Vec < T >
168
170
where
169
- T : Sized + Clone + Byteable ,
171
+ T : Sized + Copy + Byteable ,
170
172
{
171
173
fn from_bytes ( bytes : & [ u8 ] ) -> Self {
174
+ assert_eq ! (
175
+ bytes. len( ) % std:: mem:: size_of:: <T >( ) ,
176
+ 0 ,
177
+ "Cannot convert byte slice `&[u8]` to type `Vec<{0}>`. Slice length is not a multiple of std::mem::size_of::<{0}>." ,
178
+ std:: any:: type_name:: <T >( ) ,
179
+ ) ;
180
+
181
+ let len = bytes. len ( ) / std:: mem:: size_of :: < T > ( ) ;
182
+ let mut vec = Vec :: < T > :: with_capacity ( len) ;
172
183
unsafe {
173
- let byte_ptr = bytes. as_ptr ( ) as * const T ;
174
- let len = bytes. len ( ) / std:: mem:: size_of :: < T > ( ) ;
175
- let slice = core:: slice:: from_raw_parts :: < T > ( byte_ptr, len) ;
176
- slice. to_vec ( )
184
+ std:: ptr:: copy_nonoverlapping ( bytes. as_ptr ( ) , vec. as_mut_ptr ( ) as * mut u8 , bytes. len ( ) ) ;
185
+ vec. set_len ( len) ;
177
186
}
187
+ vec
178
188
}
179
189
}
180
190
0 commit comments