Skip to content

Commit

Permalink
Auto merge of #23670 - cmr:vec-push-slowpath, r=pcwalton
Browse files Browse the repository at this point in the history
Makes Vec::push considerably smaller: 25 instructions, rather than 42, on
x86_64.
  • Loading branch information
bors committed Mar 25, 2015
2 parents 593db00 + 0e838f7 commit 928e2e2
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions src/libcollections/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -646,23 +646,30 @@ impl<T> Vec<T> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push(&mut self, value: T) {
#[cold]
#[inline(never)]
fn resize<T>(vec: &mut Vec<T>) {
let old_size = vec.cap * mem::size_of::<T>();
let size = max(old_size, 2 * mem::size_of::<T>()) * 2;
if old_size > size { panic!("capacity overflow") }
unsafe {
let ptr = alloc_or_realloc(*vec.ptr, old_size, size);
if ptr.is_null() { ::alloc::oom() }
vec.ptr = Unique::new(ptr);
}
vec.cap = max(vec.cap, 2) * 2;
}

if mem::size_of::<T>() == 0 {
// zero-size types consume no memory, so we can't rely on the
// address space running out
self.len = self.len.checked_add(1).expect("length overflow");
unsafe { mem::forget(value); }
return
}

if self.len == self.cap {
let old_size = self.cap * mem::size_of::<T>();
let size = max(old_size, 2 * mem::size_of::<T>()) * 2;
if old_size > size { panic!("capacity overflow") }
unsafe {
let ptr = alloc_or_realloc(*self.ptr, old_size, size);
if ptr.is_null() { ::alloc::oom() }
self.ptr = Unique::new(ptr);
}
self.cap = max(self.cap, 2) * 2;
resize(self);
}

unsafe {
Expand Down

0 comments on commit 928e2e2

Please sign in to comment.