From cab72ae27878f7433c446a358981c061d75b4257 Mon Sep 17 00:00:00 2001 From: usamoi Date: Wed, 18 Mar 2026 02:03:31 +0800 Subject: [PATCH] implement `BinaryHeap::as_mut_slice` --- .../alloc/src/collections/binary_heap/mod.rs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/library/alloc/src/collections/binary_heap/mod.rs b/library/alloc/src/collections/binary_heap/mod.rs index 4ddfcde57280..d46b1972b5b0 100644 --- a/library/alloc/src/collections/binary_heap/mod.rs +++ b/library/alloc/src/collections/binary_heap/mod.rs @@ -1364,6 +1364,37 @@ pub fn as_slice(&self) -> &[T] { self.data.as_slice() } + /// Returns a mutable slice of all values in the underlying vector. + /// + /// # Safety + /// + /// The caller must ensure that the slice remains a max-heap, i.e. for all indices + /// `0 < i < slice.len()`, `slice[(i - 1) / 2] >= slice[i]`, before the borrow ends + /// and the binary heap is used. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(binary_heap_as_mut_slice)] + /// + /// use std::collections::BinaryHeap; + /// + /// let mut heap = BinaryHeap::::from([1, 2, 3, 4, 5, 6, 7]); + /// + /// unsafe { + /// for value in heap.as_mut_slice() { + /// *value = (*value).saturating_mul(2); + /// } + /// } + /// ``` + #[must_use] + #[unstable(feature = "binary_heap_as_mut_slice", issue = "154009")] + pub unsafe fn as_mut_slice(&mut self) -> &mut [T] { + self.data.as_mut_slice() + } + /// Consumes the `BinaryHeap` and returns the underlying vector /// in arbitrary order. ///