Skip to content

Commit 471ec70

Browse files
committed
Hint optimizer about reserved capacity
1 parent 5cee4f3 commit 471ec70

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

library/alloc/src/raw_vec.rs

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,14 @@ impl<T, A: Allocator> RawVec<T, A> {
292292
if self.needs_to_grow(len, additional) {
293293
do_reserve_and_handle(self, len, additional);
294294
}
295+
296+
// SAFETY: The call to `do_reserve_and_handle` ensured this
297+
// (or it panicked) and thus the addition cannot overflow.
298+
unsafe {
299+
// Inform the optimizer that the reservation has succeeded
300+
let min_cap = len.unchecked_add(additional);
301+
core::intrinsics::assume(self.cap >= min_cap);
302+
}
295303
}
296304

297305
/// A specialized version of `reserve()` used only by the hot and
@@ -305,10 +313,13 @@ impl<T, A: Allocator> RawVec<T, A> {
305313
/// The same as `reserve`, but returns on errors instead of panicking or aborting.
306314
pub fn try_reserve(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
307315
if self.needs_to_grow(len, additional) {
308-
self.grow_amortized(len, additional)
309-
} else {
310-
Ok(())
316+
self.grow_amortized(len, additional)?;
317+
}
318+
unsafe {
319+
// Inform the optimizer that the reservation has succeeded
320+
core::intrinsics::assume(!self.needs_to_grow(len, additional));
311321
}
322+
Ok(())
312323
}
313324

314325
/// Ensures that the buffer contains at least enough space to hold `len +
@@ -339,7 +350,14 @@ impl<T, A: Allocator> RawVec<T, A> {
339350
len: usize,
340351
additional: usize,
341352
) -> Result<(), TryReserveError> {
342-
if self.needs_to_grow(len, additional) { self.grow_exact(len, additional) } else { Ok(()) }
353+
if self.needs_to_grow(len, additional) {
354+
self.grow_exact(len, additional)?;
355+
}
356+
unsafe {
357+
// Inform the optimizer that the reservation has succeeded
358+
core::intrinsics::assume(!self.needs_to_grow(len, additional));
359+
}
360+
Ok(())
343361
}
344362

345363
/// Shrinks the buffer down to the specified capacity. If the given amount
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
thread 'main' panicked at library/alloc/src/raw_vec.rs:535:5:
1+
thread 'main' panicked at library/alloc/src/raw_vec.rs:553:5:
22
capacity overflow
33
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

0 commit comments

Comments
 (0)