From d47e388843f682f57262f020edd9909c850a0c49 Mon Sep 17 00:00:00 2001 From: EFanZh Date: Thu, 3 Oct 2024 22:15:52 +0800 Subject: [PATCH] Avoid emptiness check in `PeekMut::pop` --- library/alloc/src/collections/binary_heap/mod.rs | 5 ++++- tests/codegen/binary-heap-peek-mut-pop-no-panic.rs | 13 +++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 tests/codegen/binary-heap-peek-mut-pop-no-panic.rs diff --git a/library/alloc/src/collections/binary_heap/mod.rs b/library/alloc/src/collections/binary_heap/mod.rs index 5e59abf54ee..59f10b09c73 100644 --- a/library/alloc/src/collections/binary_heap/mod.rs +++ b/library/alloc/src/collections/binary_heap/mod.rs @@ -374,7 +374,10 @@ impl<'a, T: Ord, A: Allocator> PeekMut<'a, T, A> { // the caller could've mutated the element. It is removed from the // heap on the next line and pop() is not sensitive to its value. } - this.heap.pop().unwrap() + + // SAFETY: Have a `PeekMut` element proves that the associated binary heap being non-empty, + // so the `pop` operation will not fail. + unsafe { this.heap.pop().unwrap_unchecked() } } } diff --git a/tests/codegen/binary-heap-peek-mut-pop-no-panic.rs b/tests/codegen/binary-heap-peek-mut-pop-no-panic.rs new file mode 100644 index 00000000000..9cf4f210e52 --- /dev/null +++ b/tests/codegen/binary-heap-peek-mut-pop-no-panic.rs @@ -0,0 +1,13 @@ +//@ compile-flags: -O +//@ ignore-debug +#![crate_type = "lib"] + +use std::collections::binary_heap::PeekMut; + +// CHECK-LABEL: @peek_mut_pop +#[no_mangle] +pub fn peek_mut_pop(peek_mut: PeekMut) -> u32 { + // CHECK-NOT: panic + // CHECK-NOT: unwrap_failed + PeekMut::pop(peek_mut) +}