Skip to content

Commit

Permalink
std: Add Vec.reserve for rounding-up reservation.
Browse files Browse the repository at this point in the history
`.reserve_exact` can cause pathological O(n^2) behaviour, so providing a
`.reserve` that ensures that capacity doubles (if you step 1, 2, ..., n)
is more efficient.

cc #11949
  • Loading branch information
huonw authored and alexcrichton committed Feb 25, 2014
1 parent 16e635c commit ac64db9
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/libstd/vec_ng.rs
Expand Up @@ -18,6 +18,7 @@ use container::Container;
use iter::{DoubleEndedIterator, FromIterator, Iterator};
use libc::{free, c_void};
use mem::{size_of, move_val_init};
use num;
use num::CheckedMul;
use ops::Drop;
use option::{None, Option, Some};
Expand Down Expand Up @@ -136,6 +137,12 @@ impl<T> Vec<T> {
self.cap
}

pub fn reserve(&mut self, capacity: uint) {
if capacity >= self.len {
self.reserve_exact(num::next_power_of_two(capacity))
}
}

pub fn reserve_exact(&mut self, capacity: uint) {
if capacity >= self.len {
let size = capacity.checked_mul(&size_of::<T>()).expect("capacity overflow");
Expand Down Expand Up @@ -296,7 +303,7 @@ impl<T> Vec<T> {
let len = self.len();
assert!(index <= len);
// space for the new element
self.reserve_exact(len + 1);
self.reserve(len + 1);

unsafe { // infallible
// The spot to put the new value
Expand Down

0 comments on commit ac64db9

Please sign in to comment.