Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,19 @@ impl<T, const N: usize> SmallVec<T, N> {
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<Self, CollectionAllocErr> {
let mut this = Self::new();
if capacity > Self::inline_size() {
this.try_grow(capacity)?;
}
Ok(this)
}

Comment on lines +852 to +864

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this adds unnecessary overhead

the point of try_with_capacity is that it simplifies try_grow by realizing what its initial state is

for example, here try_with_capacity will call try_grow which will check things like "is the instance spilled??" "what is its length??"

all that overhead can be removed

#[inline]
pub const fn from_buf<const S: usize>(elements: [T; S]) -> Self {
const {
Expand Down
13 changes: 13 additions & 0 deletions tests/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,19 @@ fn test_with_capacity() {
assert_eq!(v.capacity(), 10);
}

#[test]
fn test_try_with_capacity() {
let v: SmallVec<u8, 3> = SmallVec::try_with_capacity(1).unwrap();
assert!(v.is_empty());
assert!(!v.spilled());
assert_eq!(v.capacity(), 3);

let v: SmallVec<u8, 3> = 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<u8, 2> = SmallVec::new();
Expand Down
Loading