Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
23 changes: 23 additions & 0 deletions library/alloc/src/collections/binary_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -889,6 +889,29 @@ impl<T> BinaryHeap<T> {
self.data.shrink_to(min_capacity)
}

/// Returns a slice of all values in the underlying vector, in arbitrary
/// order.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(binary_heap_as_slice)]
/// use std::collections::BinaryHeap;
/// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
/// let slice = heap.as_slice();
///
/// // Will print in some order
/// for x in slice {
/// println!("{}", x);
/// }
Copy link
Member

Choose a reason for hiding this comment

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

This is going to need a more realistic example. The point of example code is chiefly to show why you would want to call the method, not how to perform a method call. If someone is reading this documentation, we can assume they know how to make method calls. The example here does nothing to illustrate why as_slice would be used, since if you needed to do this, you should be writing for x in &heap {...} instead.

Copy link
Contributor Author

@frol frol Mar 1, 2021

Choose a reason for hiding this comment

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

@dtolnay Good question. I had bumped into it when I needed to efficiently serialize BinaryHeap. Some APIs (writer::write_all in my case) may expect a slice of data, and it is going to be quite inefficient to clone the data or iterate over it item by item (when you only have a reference to the BinaryHeap and cannot use into_vec)

/// ```
#[unstable(feature = "binary_heap_as_slice", issue = "82331")]
Copy link
Member

Choose a reason for hiding this comment

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

the number needs to be a tracking issue, not this PR

pub fn as_slice(&self) -> &[T] {
self.data.as_slice()
}

/// Consumes the `BinaryHeap` and returns the underlying vector
/// in arbitrary order.
///
Expand Down
1 change: 1 addition & 0 deletions library/alloc/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#![feature(binary_heap_drain_sorted)]
#![feature(slice_ptr_get)]
#![feature(binary_heap_retain)]
#![feature(binary_heap_as_slice)]
#![feature(inplace_iteration)]
#![feature(iter_map_while)]
#![feature(int_bits_const)]
Expand Down