From f47c43b040403941d9ae3ad898bfd8b4d3fd2009 Mon Sep 17 00:00:00 2001 From: bolshoytoster Date: Thu, 3 Sep 2026 11:07:08 +0100 Subject: [PATCH] Implement try_with_capacity and improve with_capacity --- src/lib.rs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) 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]