Skip to content

Commit a535678

Browse files
committed
get rid of unsafe code and fix soundness issue
1 parent 9c41996 commit a535678

File tree

1 file changed

+8
-20
lines changed

1 file changed

+8
-20
lines changed

byte_struct/src/lib.rs

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@
5151
pub use byte_struct_derive::{ByteStruct, ByteStructBE, ByteStructLE};
5252
pub use generic_array::*;
5353

54+
use std::convert::TryInto;
55+
5456
/// A type that can be packed into or unpacked from fixed-size bytes, but the method is unknown yet.
5557
pub trait ByteStructLen {
5658
/// The length of the packed bytes of this type
@@ -408,17 +410,10 @@ macro_rules! byte_struct_array {
408410
}
409411
}
410412
fn read_bytes_default_le(bytes: &[u8]) -> Self {
411-
let mut pos = 0;
412413
let len = T::BYTE_LEN;
413-
let mut result: Self;
414-
unsafe {
415-
result = std::mem::uninitialized();
416-
for i in 0 .. ($x) {
417-
std::ptr::write(&mut result[i], <T>::read_bytes_default_le(&bytes[pos .. pos + len]));
418-
pos += len;
419-
}
420-
}
421-
result
414+
(0 .. ($x)).map(|i| {
415+
<T>::read_bytes_default_le(&bytes[i * len .. (i + 1) * len])
416+
}).collect::<Vec<_>>().try_into().map_err(|_|()).unwrap()
422417
}
423418
fn write_bytes_default_be(&self, bytes: &mut [u8]) {
424419
let mut pos = 0;
@@ -429,17 +424,10 @@ macro_rules! byte_struct_array {
429424
}
430425
}
431426
fn read_bytes_default_be(bytes: &[u8]) -> Self {
432-
let mut pos = 0;
433427
let len = T::BYTE_LEN;
434-
let mut result: Self;
435-
unsafe {
436-
result = std::mem::uninitialized();
437-
for i in 0 .. ($x) {
438-
std::ptr::write(&mut result[i], <T>::read_bytes_default_be(&bytes[pos .. pos + len]));
439-
pos += len;
440-
}
441-
}
442-
result
428+
(0 .. ($x)).map(|i| {
429+
<T>::read_bytes_default_be(&bytes[i * len .. (i + 1) * len])
430+
}).collect::<Vec<_>>().try_into().map_err(|_|()).unwrap()
443431
}
444432
}
445433
}

0 commit comments

Comments
 (0)