Skip to content

Commit e8c2c43

Browse files
committed
Ensure we always grow by 1
1 parent 12557d4 commit e8c2c43

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

library/alloc/src/raw_vec.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -394,9 +394,12 @@ impl<T, A: Allocator> RawVec<T, A> {
394394
// Nothing we can really do about these checks, sadly.
395395
let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
396396

397-
// This guarantees exponential growth. The doubling cannot overflow
398-
// because `cap <= isize::MAX` and the type of `cap` is `usize`.
399-
let cap = cmp::max(self.cap + (self.cap / 2), required_cap);
397+
// Increase the capacity by 1.5x each time (exponential growth). The
398+
// `(self.cap <= 1) as usize` is to ensure in the case that self.cap is
399+
// 1, we still grow by 1 (without introducing an additional branch on
400+
// most processors).
401+
let next_cap = self.cap + (self.cap / 2) + (self.cap <= 1) as usize;
402+
let cap = cmp::max(next_cap, required_cap);
400403
let cap = cmp::max(Self::MIN_NON_ZERO_CAP, cap);
401404

402405
let new_layout = Layout::array::<T>(cap);

0 commit comments

Comments
 (0)