Make read_vec more robust (#134)

* Make read_vec more robust

* Remove check for overflowing add

* Let the two read_vec functions become one again
This commit is contained in:
slyrz 2017-03-09 20:04:51 +01:00 committed by Ty Overby
parent 6c3b677dd7
commit 05d1936caf
1 changed files with 17 additions and 5 deletions

View File

@ -1,3 +1,4 @@
use std::cmp;
use std::io::Read; use std::io::Read;
use std::marker::PhantomData; use std::marker::PhantomData;
@ -8,6 +9,8 @@ use serde_crate::de::Error as DeError;
use ::SizeLimit; use ::SizeLimit;
use super::{Result, Error, ErrorKind}; use super::{Result, Error, ErrorKind};
const BLOCK_SIZE: usize = 65536;
/// A Deserializer that reads bytes from a buffer. /// A Deserializer that reads bytes from a buffer.
/// ///
/// This struct should rarely be used. /// This struct should rarely be used.
@ -58,11 +61,20 @@ impl<R: Read, E: ByteOrder> Deserializer<R, E> {
let len = try!(serde::Deserialize::deserialize(&mut *self)); let len = try!(serde::Deserialize::deserialize(&mut *self));
try!(self.read_bytes(len)); try!(self.read_bytes(len));
let len = len as usize; let mut result = Vec::new();
let mut bytes = Vec::with_capacity(len); let mut len = len as usize;
unsafe { bytes.set_len(len); } let mut off = 0;
try!(self.reader.read_exact(&mut bytes)); while len > 0 {
Ok(bytes) let reserve = cmp::min(len, BLOCK_SIZE);
unsafe {
result.reserve(reserve);
result.set_len(off + reserve);
}
try!(self.reader.read_exact(&mut result[off..]));
len -= reserve;
off += reserve;
}
Ok(result)
} }
fn read_string(&mut self) -> Result<String> { fn read_string(&mut self) -> Result<String> {