From 9a55d7a8c0dbdc0cf609ec3647c00202bf898a91 Mon Sep 17 00:00:00 2001 From: Kornel Date: Mon, 9 Oct 2023 15:05:32 +0100 Subject: [PATCH] Hint optimizer about reserved capacity --- library/alloc/src/raw_vec.rs | 22 ++++++++++++++++++---- tests/ui/hygiene/panic-location.run.stderr | 2 +- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/library/alloc/src/raw_vec.rs b/library/alloc/src/raw_vec.rs index 01b03de6acb5e..bc994694ad7ef 100644 --- a/library/alloc/src/raw_vec.rs +++ b/library/alloc/src/raw_vec.rs @@ -291,6 +291,10 @@ impl RawVec { if self.needs_to_grow(len, additional) { do_reserve_and_handle(self, len, additional); + unsafe { + // Inform the optimizer that the reservation has succeeded + core::intrinsics::assume(!self.needs_to_grow(len, additional)); + } } } @@ -305,10 +309,13 @@ impl RawVec { /// The same as `reserve`, but returns on errors instead of panicking or aborting. pub fn try_reserve(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { if self.needs_to_grow(len, additional) { - self.grow_amortized(len, additional) - } else { - Ok(()) + self.grow_amortized(len, additional)?; + unsafe { + // Inform the optimizer that the reservation has succeeded + core::intrinsics::assume(!self.needs_to_grow(len, additional)); + } } + Ok(()) } /// Ensures that the buffer contains at least enough space to hold `len + @@ -339,7 +346,14 @@ impl RawVec { len: usize, additional: usize, ) -> Result<(), TryReserveError> { - if self.needs_to_grow(len, additional) { self.grow_exact(len, additional) } else { Ok(()) } + if self.needs_to_grow(len, additional) { + self.grow_exact(len, additional)?; + unsafe { + // Inform the optimizer that the reservation has succeeded + core::intrinsics::assume(!self.needs_to_grow(len, additional)); + } + } + Ok(()) } /// Shrinks the buffer down to the specified capacity. If the given amount diff --git a/tests/ui/hygiene/panic-location.run.stderr b/tests/ui/hygiene/panic-location.run.stderr index 5ed0d9fcf1ef1..25ec67a40dd22 100644 --- a/tests/ui/hygiene/panic-location.run.stderr +++ b/tests/ui/hygiene/panic-location.run.stderr @@ -1,3 +1,3 @@ -thread 'main' panicked at library/alloc/src/raw_vec.rs:534:5: +thread 'main' panicked at library/alloc/src/raw_vec.rs:548:5: capacity overflow note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace