perf(data_structures): optimize NonEmptyStack::pop (#7021)

Shave a few bytes off `NonEmptyStack::pop`.
This commit is contained in:
overlookmotel 2024-10-30 13:00:21 +00:00
parent b8daab3663
commit c58ec89b81

View file

@ -263,8 +263,22 @@ impl<T> NonEmptyStack<T> {
/// Panics if the stack has only 1 entry on it.
#[inline]
pub fn pop(&mut self) -> T {
// Panic if trying to remove last entry from stack
assert!(self.cursor != self.start, "Cannot pop all entries");
// Panic if trying to remove last entry from stack.
//
// Putting the panic in an `#[inline(never)]` + `#[cold]` function removes a 6-byte `lea`
// instruction vs `assert!(self.cursor != self.start, "Cannot pop all entries")`.
// This reduces this function on x86_64 from 32 bytes to 26 bytes.
// This function is commonly used, and we want it to be inlined, so every byte counts.
// https://godbolt.org/z/5587z99rM
#[inline(never)]
#[cold]
fn error() -> ! {
panic!("Cannot pop all entries");
}
if self.cursor == self.start {
error();
}
// SAFETY: Assertion above ensures stack has at least 2 entries
unsafe { self.pop_unchecked() }