Skip to content

Commit

Permalink
refactor: use error for overflow
Browse files Browse the repository at this point in the history
Reworks the overflow handling to return an error instead of using the
saturating arithmetic strategy.
  • Loading branch information
sno2 committed Sep 18, 2023
1 parent a1ed184 commit 7170c83
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions src/patch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ pub fn patch<T: Read>(old: &[u8], patch: &mut T, new: &mut Vec<u8>) -> io::Resul
let seek_len = offtin(buf[16..24].try_into().unwrap());

// Read diff string and literal data at once
let to_read = copy_len.saturating_add(mix_len);
let to_read = copy_len
.checked_add(mix_len)
.ok_or(io::Error::from(io::ErrorKind::InvalidData))?;
let mix_start = new.len();
let has_read = patch.take(to_read as u64).read_to_end(new)?;

Expand All @@ -58,15 +60,31 @@ pub fn patch<T: Read>(old: &[u8], patch: &mut T, new: &mut Vec<u8>) -> io::Resul
return Err(io::ErrorKind::UnexpectedEof.into());
}

let mix_slice = new.get_mut(mix_start..mix_start.saturating_add(mix_len)).ok_or(io::ErrorKind::UnexpectedEof)?;
let old_slice = old.get(oldpos..oldpos.saturating_add(mix_len)).ok_or(io::ErrorKind::UnexpectedEof)?;
let mix_slice = new
.get_mut(
mix_start
..mix_start
.checked_add(mix_len)
.ok_or(io::Error::from(io::ErrorKind::InvalidData))?,
)
.ok_or(io::ErrorKind::UnexpectedEof)?;
let old_slice = old
.get(
oldpos
..oldpos
.checked_add(mix_len)
.ok_or(io::Error::from(io::ErrorKind::InvalidData))?,
)
.ok_or(io::ErrorKind::UnexpectedEof)?;
for (n, o) in mix_slice.iter_mut().zip(old_slice) {
*n = n.wrapping_add(*o);
}

// Adjust pointers
oldpos += mix_len;
oldpos = (oldpos as i64).saturating_add(seek_len) as usize;
oldpos = (oldpos as i64)
.checked_add(seek_len)
.ok_or(io::Error::from(io::ErrorKind::InvalidData))? as usize;
}
}

Expand Down

0 comments on commit 7170c83

Please sign in to comment.