From 589c60492b6ff11a1256b80e7b22dced33126559 Mon Sep 17 00:00:00 2001 From: Jorge Polanco <55784702+Jorge-Polanco-Roque@users.noreply.github.com> Date: Sat, 29 Aug 2026 17:42:30 -0600 Subject: [PATCH] Add try_with_capacity fallible constructor Fallible analogue to with_capacity, mirroring the existing try_reserve path (uses try_grow, returns Result). Fixes #416 Signed-off-by: Jorge Polanco <55784702+Jorge-Polanco-Roque@users.noreply.github.com> --- src/lib.rs | 13 +++++++++++++ tests/main.rs | 13 +++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 9aa7009..f5f000f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -849,6 +849,19 @@ impl SmallVec { this } + /// Constructs a new, empty `SmallVec` with at least the specified capacity, + /// returning an error if the allocation fails. + /// + /// This is the fallible version of [`with_capacity`](Self::with_capacity). + #[inline] + pub fn try_with_capacity(capacity: usize) -> Result { + let mut this = Self::new(); + if capacity > Self::inline_size() { + this.try_grow(capacity)?; + } + Ok(this) + } + #[inline] pub const fn from_buf(elements: [T; S]) -> Self { const { diff --git a/tests/main.rs b/tests/main.rs index a1a0508..3d9745b 100644 --- a/tests/main.rs +++ b/tests/main.rs @@ -125,6 +125,19 @@ fn test_with_capacity() { assert_eq!(v.capacity(), 10); } +#[test] +fn test_try_with_capacity() { + let v: SmallVec = SmallVec::try_with_capacity(1).unwrap(); + assert!(v.is_empty()); + assert!(!v.spilled()); + assert_eq!(v.capacity(), 3); + + let v: SmallVec = SmallVec::try_with_capacity(10).unwrap(); + assert!(v.is_empty()); + assert!(v.spilled()); + assert_eq!(v.capacity(), 10); +} + #[test] fn drain() { let mut v: SmallVec = SmallVec::new();