Skip to content

Commit

Permalink
Make to_u32 safe and sound
Browse files Browse the repository at this point in the history
  • Loading branch information
dodomorandi committed Feb 1, 2021
1 parent e88c6ff commit 8ff7218
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
8 changes: 4 additions & 4 deletions src/cfb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,15 @@ impl Cfb {
debug!("load difat");
let mut sector_id = h.difat_start;
while sector_id < RESERVED_SECTORS {
difat.extend_from_slice(to_u32(sectors.get(sector_id, reader)?));
difat.extend(to_u32(sectors.get(sector_id, reader)?));
sector_id = difat.pop().unwrap(); //TODO: check if in infinite loop
}

// load the FATs
debug!("load fat");
let mut fats = Vec::with_capacity(h.fat_len);
for id in difat.into_iter().filter(|id| *id != FREESECT) {
fats.extend_from_slice(to_u32(sectors.get(id, reader)?));
fats.extend(to_u32(sectors.get(id, reader)?));
}

// get the list of directory sectors
Expand All @@ -116,7 +116,7 @@ impl Cfb {
reader,
h.mini_fat_len * h.sector_size,
)?;
let minifat = to_u32(&minifat).to_vec();
let minifat = to_u32(&minifat).collect();
Ok(Cfb {
directories: dirs,
sectors,
Expand Down Expand Up @@ -208,7 +208,7 @@ impl Header {
let difat_len = read_usize(&buf[62..76]);

let mut difat = Vec::with_capacity(difat_len);
difat.extend_from_slice(to_u32(&buf[76..512]));
difat.extend(to_u32(&buf[76..512]));

Ok((
Header {
Expand Down
12 changes: 7 additions & 5 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ macro_rules! from_err {
};
}

/// Converts a &[u8] into a &[u32]
pub fn to_u32(s: &[u8]) -> &[u32] {
/// Converts a &[u8] into an iterator of `u32`s
pub fn to_u32(s: &[u8]) -> impl ExactSizeIterator<Item = u32> + '_ {
assert_eq!(s.len() % 4, 0);
unsafe { std::slice::from_raw_parts(s as *const [u8] as *const u32, s.len() / 4) }
s.chunks(4)
.map(|data| u32::from_ne_bytes([data[0], data[1], data[2], data[3]]))
}

pub fn read_slice<T>(s: &[u8]) -> T {
unsafe { std::ptr::read(&s[..std::mem::size_of::<T>()] as *const [u8] as *const T) }
}
Expand Down Expand Up @@ -1039,8 +1041,8 @@ mod tests {
fn sound_to_u32() {
let data = b"ABCDEFGH";
assert_eq!(
to_u32(data),
&[u32::from_ne_bytes(*b"ABCD"), u32::from_ne_bytes(*b"EFGH")]
to_u32(data).collect::<Vec<_>>(),
[u32::from_ne_bytes(*b"ABCD"), u32::from_ne_bytes(*b"EFGH")]
);
}

Expand Down

0 comments on commit 8ff7218

Please sign in to comment.