From ae8c162d49780f0ad0a9ffda065cb58813398d43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lena=20Hellstr=C3=B6m?= Date: Thu, 19 Mar 2020 17:46:13 -0700 Subject: [PATCH] remove unsafe code in IoReader (#309) --- src/de/read.rs | 23 +++-------------------- 1 file changed, 3 insertions(+), 20 deletions(-) diff --git a/src/de/read.rs b/src/de/read.rs index 9a0489a..107ce01 100644 --- a/src/de/read.rs +++ b/src/de/read.rs @@ -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(()) }