@@ -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
0 commit comments