Skip to content

Add try_with_capacity fallible constructor - #500

Closed
Jorge-Polanco-Roque wants to merge 1 commit into
servo:v2from
Jorge-Polanco-Roque:feat/try-with-capacity
Closed

Add try_with_capacity fallible constructor#500
Jorge-Polanco-Roque wants to merge 1 commit into
servo:v2from
Jorge-Polanco-Roque:feat/try-with-capacity

Conversation

@Jorge-Polanco-Roque

Copy link
Copy Markdown
Contributor

Closes #416.

Adds try_with_capacity, the fallible analogue to with_capacity. It mirrors the existing try_reserve path: uses try_grow and returns Result<Self, CollectionAllocErr>.

pub fn try_with_capacity(capacity: usize) -> Result<Self, CollectionAllocErr>

I kept it ungated, matching try_reserve/try_grow (also ungated). You mentioned it might live behind a feature gate — happy to move it if you'd prefer; just let me know which feature.

Test added in tests/main.rs covering the inline and spilled cases.

Fallible analogue to with_capacity, mirroring the existing try_reserve
path (uses try_grow, returns Result<Self, CollectionAllocErr>).

Fixes servo#416

Signed-off-by: Jorge Polanco <55784702+Jorge-Polanco-Roque@users.noreply.github.com>
Comment thread src/lib.rs
Comment on lines +852 to +864
/// 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)
}

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

@alejandro-vaz

alejandro-vaz commented Aug 29, 2026

Copy link
Copy Markdown
Collaborator

also, AI contributions are not allowed in any @servo repository, I'm closing this PR

https://book.servo.org/contributing/getting-started.html#ai-contributions

please read it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement try_with_capacity

2 participants