From 6cb6d1b59dfd96fe2cf10c2acb18e791c1b077e4 Mon Sep 17 00:00:00 2001 From: bluurryy <164359728+bluurryy@users.noreply.github.com> Date: Tue, 29 Oct 2024 23:48:00 +0100 Subject: [PATCH] perf: use regular `mul` instead of `checked_mul` when doubling capacity --- src/bump_vec.rs | 5 +++-- src/mut_bump_vec.rs | 5 +++-- src/mut_bump_vec_rev.rs | 5 +++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/bump_vec.rs b/src/bump_vec.rs index a40d878..801e132 100644 --- a/src/bump_vec.rs +++ b/src/bump_vec.rs @@ -1616,8 +1616,9 @@ where return Ok(()); } - let new_cap = self.capacity().checked_mul(2).unwrap_or(required_cap).max(required_cap); - let new_cap = new_cap.max(min_non_zero_cap(T::SIZE)); + // This guarantees exponential growth. The doubling cannot overflow + // because `capacity <= isize::MAX` and the type of `capacity` is usize; + let new_cap = (self.capacity() * 2).max(required_cap).max(min_non_zero_cap(T::SIZE)); self.generic_grow_to(new_cap) } diff --git a/src/mut_bump_vec.rs b/src/mut_bump_vec.rs index f5bd03c..05a256c 100644 --- a/src/mut_bump_vec.rs +++ b/src/mut_bump_vec.rs @@ -1309,8 +1309,9 @@ where return Ok(()); } - let new_cap = self.capacity().checked_mul(2).unwrap_or(required_cap).max(required_cap); - let new_cap = new_cap.max(min_non_zero_cap(T::SIZE)); + // This guarantees exponential growth. The doubling cannot overflow + // because `capacity <= isize::MAX` and the type of `capacity` is usize; + let new_cap = (self.capacity() * 2).max(required_cap).max(min_non_zero_cap(T::SIZE)); unsafe { self.generic_grow_to(new_cap) } } diff --git a/src/mut_bump_vec_rev.rs b/src/mut_bump_vec_rev.rs index 327b2f6..3bdec7d 100644 --- a/src/mut_bump_vec_rev.rs +++ b/src/mut_bump_vec_rev.rs @@ -1334,8 +1334,9 @@ where return Ok(()); } - let new_cap = self.capacity().checked_mul(2).unwrap_or(required_cap).max(required_cap); - let new_cap = new_cap.max(min_non_zero_cap(T::SIZE)); + // This guarantees exponential growth. The doubling cannot overflow + // because `capacity <= isize::MAX` and the type of `capacity` is usize; + let new_cap = (self.capacity() * 2).max(required_cap).max(min_non_zero_cap(T::SIZE)); unsafe { self.generic_grow_to(new_cap) } }