Eager prealloc no inline (#127)

* make SizeLimit a trait

* always preallocate
This commit is contained in:
Ty Overby 2017-03-17 18:14:59 -07:00 committed by GitHub
parent 461a694bac
commit 2b465047b9
2 changed files with 6 additions and 4 deletions

View File

@ -142,6 +142,7 @@ impl SizeLimit for Bounded {
Err(Box::new(ErrorKind::SizeLimit)) Err(Box::new(ErrorKind::SizeLimit))
} }
} }
#[inline(always)] #[inline(always)]
fn limit(&self) -> Option<u64> { Some(self.0) } fn limit(&self) -> Option<u64> { Some(self.0) }
} }
@ -149,6 +150,7 @@ impl SizeLimit for Bounded {
impl SizeLimit for Infinite { impl SizeLimit for Infinite {
#[inline(always)] #[inline(always)]
fn add(&mut self, _: u64) -> Result<()> { Ok (()) } fn add(&mut self, _: u64) -> Result<()> { Ok (()) }
#[inline(always)] #[inline(always)]
fn limit(&self) -> Option<u64> { None } fn limit(&self) -> Option<u64> { None }
} }

View File

@ -137,15 +137,15 @@ pub fn serialize_into<W: ?Sized, T: ?Sized, S, E>(writer: &mut W, value: &T, siz
pub fn serialize<T: ?Sized, S, E>(value: &T, size_limit: S) -> Result<Vec<u8>> pub fn serialize<T: ?Sized, S, E>(value: &T, size_limit: S) -> Result<Vec<u8>>
where T: serde::Serialize, S: SizeLimit, E: ByteOrder where T: serde::Serialize, S: SizeLimit, E: ByteOrder
{ {
// Since we are putting values directly into a vector, we can do size
// computation out here and pre-allocate a buffer of *exactly*
// the right size.
let mut writer = match size_limit.limit() { let mut writer = match size_limit.limit() {
Some(size_limit) => { Some(size_limit) => {
let actual_size = try!(serialized_size_bounded(value, size_limit).ok_or(ErrorKind::SizeLimit)); let actual_size = try!(serialized_size_bounded(value, size_limit).ok_or(ErrorKind::SizeLimit));
Vec::with_capacity(actual_size as usize) Vec::with_capacity(actual_size as usize)
} }
None => Vec::new() None => {
let size = serialized_size(value) as usize;
Vec::with_capacity(size)
}
}; };
try!(serialize_into::<_, _, _, E>(&mut writer, value, super::Infinite)); try!(serialize_into::<_, _, _, E>(&mut writer, value, super::Infinite));