remove unsafe code in IoReader (#309)

This commit is contained in:
Lena Hellström 2020-03-19 17:46:13 -07:00 committed by GitHub
parent 15379ee5b2
commit ae8c162d49
1 changed files with 3 additions and 20 deletions

View File

@ -141,31 +141,14 @@ where
R: io::Read,
{
fn fill_buffer(&mut self, length: usize) -> Result<()> {
// We first reserve the space needed in our buffer.
// Reserve and fill extra space if needed
let current_length = self.temp_buffer.len();
if length > current_length {
self.temp_buffer.reserve_exact(length - current_length);
self.temp_buffer.resize(length, 0);
}
// Then create a slice with the length as our desired length. This is
// safe as long as we only write (no reads) to this buffer, because
// `reserve_exact` above has allocated this space.
let buf = unsafe {
slice::from_raw_parts_mut(self.temp_buffer.as_mut_ptr(), length)
};
// This method is assumed to properly handle slices which include
// uninitialized bytes (as ours does). See discussion at the link below.
// https://github.com/servo/bincode/issues/260
self.reader.read_exact(buf)?;
// Only after `read_exact` successfully returns do we set the buffer
// length. By doing this after the call to `read_exact`, we can avoid
// exposing uninitialized memory in the case of `read_exact` returning
// an error.
unsafe {
self.temp_buffer.set_len(length);
}
self.reader.read_exact(&mut self.temp_buffer)?;
Ok(())
}