Skip to content

Commit feb42bd

Browse files
author
bors-servo
authored
Auto merge of #112 - mbrubeck:reserve, r=emilio
Use `reserve` instead of unchecked math in `push` `push` currently uses this line to reserve space in the vector: ``` self.grow(cmp::max(cap * 2, 1)) ``` This risks overflowing `usize`. In practice this can't happen currently, because `cap` can't be larger than `isize::MAX` because of invariants upheld in liballoc, but this is not easy to see. Replacing this with `self.reserve(1)` is clearer, easier to reason about safety (because `reserve` uses checked arithmetic), and will make it easier to change the growth strategy in the future. This does not regress any of the `push` benchmarks. Marking `reserve` as inline is necessary to prevent `insert` benchmarks from regressing because of a change in the optimizer's inlining decisions there. <!-- Reviewable:start --> --- This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/rust-smallvec/112) <!-- Reviewable:end -->
2 parents 371531f + d2b1900 commit feb42bd

File tree

1 file changed

+2
-1
lines changed

1 file changed

+2
-1
lines changed

lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -560,7 +560,7 @@ impl<A: Array> SmallVec<A> {
560560
unsafe {
561561
let (_, &mut len, cap) = self.triple_mut();
562562
if len == cap {
563-
self.grow(cmp::max(cap * 2, 1))
563+
self.reserve(1);
564564
}
565565
let (ptr, len_ptr, _) = self.triple_mut();
566566
*len_ptr = len + 1;
@@ -618,6 +618,7 @@ impl<A: Array> SmallVec<A> {
618618
/// If the new capacity would overflow `usize` then it will be set to `usize::max_value()`
619619
/// instead. (This means that inserting `additional` new elements is not guaranteed to be
620620
/// possible after calling this function.)
621+
#[inline]
621622
pub fn reserve(&mut self, additional: usize) {
622623
// prefer triple_mut() even if triple() would work
623624
// so that the optimizer removes duplicated calls to it

0 commit comments

Comments
 (0)