Skip to content

Commit b3d7823

Browse files
committed
core: Add and use vec::reserve_at_least
This reserves in powers of two
1 parent 8e743b2 commit b3d7823

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

src/libcore/vec.rs

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
#[doc = "Vectors"];
22

33
import option::{some, none};
4-
import uint::next_power_of_two;
54
import ptr::addr_of;
65

76
export init_op;
87
export is_empty;
98
export is_not_empty;
109
export same_length;
1110
export reserve;
11+
export reserve_at_least;
1212
export len;
1313
export from_fn;
1414
export from_elem;
@@ -115,6 +115,25 @@ fn reserve<T>(&v: [const T], n: uint) {
115115
rustrt::vec_reserve_shared(sys::get_type_desc::<T>(), v, n);
116116
}
117117

118+
#[doc = "
119+
Reserves capacity for at least `n` elements in the given vector.
120+
121+
This function will over-allocate in order to amortize the allocation costs
122+
in scenarios where the caller may need to repeatedly reserve additional
123+
space.
124+
125+
If the capacity for `v` is already equal to or greater than the requested
126+
capacity, then no action is taken.
127+
128+
# Arguments
129+
130+
* v - A vector
131+
* n - The number of elements to reserve space for
132+
"]
133+
fn reserve_at_least<T>(&v: [const T], n: uint) {
134+
reserve(v, uint::next_power_of_two(n));
135+
}
136+
118137
#[doc = "Returns the length of a vector"]
119138
#[inline(always)]
120139
pure fn len<T>(&&v: [const T]) -> uint unsafe {
@@ -364,7 +383,7 @@ Expands a vector in place, initializing the new elements to a given value
364383
* initval - The value for the new elements
365384
"]
366385
fn grow<T: copy>(&v: [const T], n: uint, initval: T) {
367-
reserve(v, next_power_of_two(len(v) + n));
386+
reserve_at_least(v, len(v) + n);
368387
let mut i: uint = 0u;
369388
while i < n { v += [initval]; i += 1u; }
370389
}
@@ -383,7 +402,7 @@ Function `init_op` is called `n` times with the values [0..`n`)
383402
value
384403
"]
385404
fn grow_fn<T>(&v: [const T], n: uint, op: init_op<T>) {
386-
reserve(v, next_power_of_two(len(v) + n));
405+
reserve_at_least(v, len(v) + n);
387406
let mut i: uint = 0u;
388407
while i < n { v += [op(i)]; i += 1u; }
389408
}

0 commit comments

Comments
 (0)