Skip to content

Mutable access to the top element of a BinaryHeap #33830

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions src/libcollections/binary_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@
#![allow(missing_docs)]
#![stable(feature = "rust1", since = "1.0.0")]

use core::ops::{Drop, Deref, DerefMut};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it actually necessary to import Drop?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC it is in libstd - the prelude isn't injected here.

use core::iter::FromIterator;
use core::mem::swap;
use core::mem::size_of;
Expand Down Expand Up @@ -218,6 +219,37 @@ pub struct BinaryHeap<T> {
data: Vec<T>,
}

/// A container object that represents the result of the [`peek_mut()`] method
/// on `BinaryHeap`. See its documentation for details.
///
/// [`peek_mut()`]: struct.BinaryHeap.html#method.peek_mut
#[unstable(feature = "binary_heap_peek_mut", issue = "34392")]
pub struct PeekMut<'a, T: 'a + Ord> {
heap: &'a mut BinaryHeap<T>
}

#[unstable(feature = "binary_heap_peek_mut", issue = "34392")]
impl<'a, T: Ord> Drop for PeekMut<'a, T> {
fn drop(&mut self) {
self.heap.sift_down(0);
}
}

#[unstable(feature = "binary_heap_peek_mut", issue = "34392")]
impl<'a, T: Ord> Deref for PeekMut<'a, T> {
type Target = T;
fn deref(&self) -> &T {
&self.heap.data[0]
}
}

#[unstable(feature = "binary_heap_peek_mut", issue = "34392")]
impl<'a, T: Ord> DerefMut for PeekMut<'a, T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.heap.data[0]
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for BinaryHeap<T> {
fn clone(&self) -> Self {
Expand Down Expand Up @@ -323,6 +355,42 @@ impl<T: Ord> BinaryHeap<T> {
self.data.get(0)
}

/// Returns a mutable reference to the greatest item in the binary heap, or
/// `None` if it is empty.
///
/// Note: If the `PeekMut` value is leaked, the heap may be in an
/// inconsistent state.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(binary_heap_peek_mut)]
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
/// assert!(heap.peek_mut().is_none());
///
/// heap.push(1);
/// heap.push(5);
/// heap.push(2);
/// {
/// let mut val = heap.peek_mut().unwrap();
/// *val = 0;
/// }
/// assert_eq!(heap.peek(), Some(&2));
/// ```
#[unstable(feature = "binary_heap_peek_mut", issue = "34392")]
pub fn peek_mut(&mut self) -> Option<PeekMut<T>> {
if self.is_empty() {
None
} else {
Some(PeekMut {
heap: self
})
}
}

/// Returns the number of elements the binary heap can hold without reallocating.
///
/// # Examples
Expand Down
18 changes: 18 additions & 0 deletions src/libcollectionstest/binary_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,18 @@ fn test_peek_and_pop() {
}
}

#[test]
fn test_peek_mut() {
let data = vec![2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1];
let mut heap = BinaryHeap::from(data);
assert_eq!(heap.peek(), Some(&10));
{
let mut top = heap.peek_mut().unwrap();
*top -= 2;
}
assert_eq!(heap.peek(), Some(&9));
}

#[test]
fn test_push() {
let mut heap = BinaryHeap::from(vec![2, 4, 9]);
Expand Down Expand Up @@ -192,6 +204,12 @@ fn test_empty_peek() {
assert!(empty.peek().is_none());
}

#[test]
fn test_empty_peek_mut() {
let mut empty = BinaryHeap::<i32>::new();
assert!(empty.peek_mut().is_none());
}

#[test]
fn test_empty_replace() {
let mut heap = BinaryHeap::new();
Expand Down
1 change: 1 addition & 0 deletions src/libcollectionstest/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

#![feature(binary_heap_extras)]
#![feature(binary_heap_append)]
#![feature(binary_heap_peek_mut)]
#![feature(box_syntax)]
#![feature(btree_append)]
#![feature(btree_split_off)]
Expand Down