Skip to content

Commit faac3c5

Browse files
authored
Rollup merge of rust-lang#152502 - Dan54:heap-from-raw-vec, r=scottmcm
Implement `BinaryHeap::from_raw_vec` Implements rust-lang#152500. Adds a `BinaryHeap::from_raw_vec` function, which constructs a `BinaryHeap` without performing a heapify, for data that is already a max-heap.
2 parents 9376482 + 9383138 commit faac3c5

File tree

1 file changed

+34
-0
lines changed
  • library/alloc/src/collections/binary_heap

1 file changed

+34
-0
lines changed

library/alloc/src/collections/binary_heap/mod.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -581,6 +581,40 @@ impl<T, A: Allocator> BinaryHeap<T, A> {
581581
pub fn with_capacity_in(capacity: usize, alloc: A) -> BinaryHeap<T, A> {
582582
BinaryHeap { data: Vec::with_capacity_in(capacity, alloc) }
583583
}
584+
585+
/// Creates a `BinaryHeap` using the supplied `vec`. This does not rebuild the heap,
586+
/// so `vec` must already be a max-heap.
587+
///
588+
/// # Safety
589+
///
590+
/// The supplied `vec` must be a max-heap, i.e. for all indices `0 < i < vec.len()`,
591+
/// `vec[(i - 1) / 2] >= vec[i]`.
592+
///
593+
/// # Examples
594+
///
595+
/// Basic usage:
596+
///
597+
/// ```
598+
/// #![feature(binary_heap_from_raw_vec)]
599+
///
600+
/// use std::collections::BinaryHeap;
601+
/// let heap = BinaryHeap::from([1, 2, 3]);
602+
/// let vec = heap.into_vec();
603+
///
604+
/// // Safety: vec is the output of heap.from_vec(), so is a max-heap.
605+
/// let mut new_heap = unsafe {
606+
/// BinaryHeap::from_raw_vec(vec)
607+
/// };
608+
/// assert_eq!(new_heap.pop(), Some(3));
609+
/// assert_eq!(new_heap.pop(), Some(2));
610+
/// assert_eq!(new_heap.pop(), Some(1));
611+
/// assert_eq!(new_heap.pop(), None);
612+
/// ```
613+
#[unstable(feature = "binary_heap_from_raw_vec", issue = "152500")]
614+
#[must_use]
615+
pub unsafe fn from_raw_vec(vec: Vec<T, A>) -> BinaryHeap<T, A> {
616+
BinaryHeap { data: vec }
617+
}
584618
}
585619

586620
impl<T: Ord, A: Allocator> BinaryHeap<T, A> {

0 commit comments

Comments
 (0)