diff --git a/src/lib.rs b/src/lib.rs index ba2302a..7d14446 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -706,13 +706,21 @@ impl SmallVec { } } - #[inline] - pub fn with_capacity(capacity: usize) -> Self { + pub fn try_with_capacity(capacity: usize) -> Result { let mut this = Self::new(); - if capacity > Self::inline_size() { - this.grow(capacity); + if capacity > Self::inline_size() && !Self::IS_ZST { + // SAFETY: we checked all the preconditions + unsafe { this.raw.try_grow_raw(TaggedLen::new(0, false), capacity) }?; + + // SAFETY: the allocation succeeded, so self.raw.heap is now active + unsafe { this.set_on_heap() }; } - this + Ok(this) + } + + #[inline] + pub fn with_capacity(capacity: usize) -> Self { + infallible(Self::try_with_capacity(capacity)) } #[inline]