diff --git a/crates/datastructures/src/raw_vec.rs b/crates/datastructures/src/raw_vec.rs index da948a2..71bfa8a 100644 --- a/crates/datastructures/src/raw_vec.rs +++ b/crates/datastructures/src/raw_vec.rs @@ -18,19 +18,12 @@ impl RawVec { } // See rustonomicon, chapter 9.2 - pub(crate) fn grow(&mut self) { - let (new_cap, new_layout) = if self.capacity == 0 { - (1, Layout::array::(1).unwrap()) - } else { - // This can't overflow since self.cap <= isize::MAX. - let new_cap = 2 * self.capacity; - - // `Layout::array` checks that the number of bytes is <= usize::MAX, - // but this is redundant since old_layout.size() <= isize::MAX, - // so the `unwrap` should never fail. - let new_layout = Layout::array::(new_cap).unwrap(); - (new_cap, new_layout) - }; + pub(crate) fn grow_by(&mut self, added_capacity: usize) { + let new_cap = self.capacity + added_capacity; + // `Layout::array` checks that the number of bytes is <= usize::MAX, + // but this is redundant since old_layout.size() <= isize::MAX, + // so the `unwrap` should never fail. + let new_layout = Layout::array::(new_cap).unwrap(); // Ensure that the new allocation doesn't exceed `isize::MAX` bytes. if new_layout.size() > isize::MAX as usize { @@ -52,6 +45,14 @@ impl RawVec { }; self.capacity = new_cap; } + + pub(crate) fn grow(&mut self) { + if self.capacity == 0 { + self.grow_by(1); + } else { + self.grow_by(self.capacity); + } + } } impl Drop for RawVec { diff --git a/crates/datastructures/src/vec.rs b/crates/datastructures/src/vec.rs index 6d6dfb2..c741596 100644 --- a/crates/datastructures/src/vec.rs +++ b/crates/datastructures/src/vec.rs @@ -37,6 +37,16 @@ impl Vec { } } + pub fn with_capacity(capacity: usize) -> Self { + if mem::size_of::() == 0 { + panic!("We're not ready to handle ZSTs"); + } + + let mut v = Self::new(); + v.reserve(capacity); + v + } + pub fn pop(&mut self) -> Option { if self.used == 0 { None @@ -107,6 +117,10 @@ impl Vec { result } } + + pub fn reserve(&mut self, added_capacity: usize) { + self.buf.grow_by(added_capacity); + } } impl Index for Vec {