Skip to content

Commit ac64db9

Browse files
huonwalexcrichton
authored andcommitted
std: Add Vec.reserve for rounding-up reservation.
`.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
1 parent 16e635c commit ac64db9

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

src/libstd/vec_ng.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use container::Container;
1818
use iter::{DoubleEndedIterator, FromIterator, Iterator};
1919
use libc::{free, c_void};
2020
use mem::{size_of, move_val_init};
21+
use num;
2122
use num::CheckedMul;
2223
use ops::Drop;
2324
use option::{None, Option, Some};
@@ -136,6 +137,12 @@ impl<T> Vec<T> {
136137
self.cap
137138
}
138139

140+
pub fn reserve(&mut self, capacity: uint) {
141+
if capacity >= self.len {
142+
self.reserve_exact(num::next_power_of_two(capacity))
143+
}
144+
}
145+
139146
pub fn reserve_exact(&mut self, capacity: uint) {
140147
if capacity >= self.len {
141148
let size = capacity.checked_mul(&size_of::<T>()).expect("capacity overflow");
@@ -296,7 +303,7 @@ impl<T> Vec<T> {
296303
let len = self.len();
297304
assert!(index <= len);
298305
// space for the new element
299-
self.reserve_exact(len + 1);
306+
self.reserve(len + 1);
300307

301308
unsafe { // infallible
302309
// The spot to put the new value

0 commit comments

Comments
 (0)