Add try_with_capacity fallible constructor - #500
Conversation
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>
| /// 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) | ||
| } | ||
|
|
There was a problem hiding this comment.
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
There was a problem hiding this comment.
This is just the mirror of the implementation for with_capacity. Should I see if that could benefit from using this information as well?
There was a problem hiding this comment.
I've benchmarked it, and it seems with_capacity can be improved by ~12% by changing it to:
let mut this = Self::new();
if capacity > Self::inline_size() {
infallible(unsafe { this.raw.try_grow_raw(0, capacity) });
unsafe { this.set_on_heap() };
}
this|
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 |
Closes #416.
Adds
try_with_capacity, the fallible analogue towith_capacity. It mirrors the existingtry_reservepath: usestry_growand returnsResult<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.rscovering the inline and spilled cases.