alloc/collections/binary_heap/
mod.rs

1//! A priority queue implemented with a binary heap.
2//!
3//! Insertion and popping the largest element have *O*(log(*n*)) time complexity.
4//! Checking the largest element is *O*(1). Converting a vector to a binary heap
5//! can be done in-place, and has *O*(*n*) complexity. A binary heap can also be
6//! converted to a sorted vector in-place, allowing it to be used for an *O*(*n* * log(*n*))
7//! in-place heapsort.
8//!
9//! # Examples
10//!
11//! This is a larger example that implements [Dijkstra's algorithm][dijkstra]
12//! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
13//! It shows how to use [`BinaryHeap`] with custom types.
14//!
15//! [dijkstra]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
16//! [sssp]: https://en.wikipedia.org/wiki/Shortest_path_problem
17//! [dir_graph]: https://en.wikipedia.org/wiki/Directed_graph
18//!
19//! ```
20//! use std::cmp::Ordering;
21//! use std::collections::BinaryHeap;
22//!
23//! #[derive(Copy, Clone, Eq, PartialEq)]
24//! struct State {
25//!     cost: usize,
26//!     position: usize,
27//! }
28//!
29//! // The priority queue depends on `Ord`.
30//! // Explicitly implement the trait so the queue becomes a min-heap
31//! // instead of a max-heap.
32//! impl Ord for State {
33//!     fn cmp(&self, other: &Self) -> Ordering {
34//!         // Notice that we flip the ordering on costs.
35//!         // In case of a tie we compare positions - this step is necessary
36//!         // to make implementations of `PartialEq` and `Ord` consistent.
37//!         other.cost.cmp(&self.cost)
38//!             .then_with(|| self.position.cmp(&other.position))
39//!     }
40//! }
41//!
42//! // `PartialOrd` needs to be implemented as well.
43//! impl PartialOrd for State {
44//!     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
45//!         Some(self.cmp(other))
46//!     }
47//! }
48//!
49//! // Each node is represented as a `usize`, for a shorter implementation.
50//! struct Edge {
51//!     node: usize,
52//!     cost: usize,
53//! }
54//!
55//! // Dijkstra's shortest path algorithm.
56//!
57//! // Start at `start` and use `dist` to track the current shortest distance
58//! // to each node. This implementation isn't memory-efficient as it may leave duplicate
59//! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
60//! // for a simpler implementation.
61//! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
62//!     // dist[node] = current shortest distance from `start` to `node`
63//!     let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
64//!
65//!     let mut heap = BinaryHeap::new();
66//!
67//!     // We're at `start`, with a zero cost
68//!     dist[start] = 0;
69//!     heap.push(State { cost: 0, position: start });
70//!
71//!     // Examine the frontier with lower cost nodes first (min-heap)
72//!     while let Some(State { cost, position }) = heap.pop() {
73//!         // Alternatively we could have continued to find all shortest paths
74//!         if position == goal { return Some(cost); }
75//!
76//!         // Important as we may have already found a better way
77//!         if cost > dist[position] { continue; }
78//!
79//!         // For each node we can reach, see if we can find a way with
80//!         // a lower cost going through this node
81//!         for edge in &adj_list[position] {
82//!             let next = State { cost: cost + edge.cost, position: edge.node };
83//!
84//!             // If so, add it to the frontier and continue
85//!             if next.cost < dist[next.position] {
86//!                 heap.push(next);
87//!                 // Relaxation, we have now found a better way
88//!                 dist[next.position] = next.cost;
89//!             }
90//!         }
91//!     }
92//!
93//!     // Goal not reachable
94//!     None
95//! }
96//!
97//! fn main() {
98//!     // This is the directed graph we're going to use.
99//!     // The node numbers correspond to the different states,
100//!     // and the edge weights symbolize the cost of moving
101//!     // from one node to another.
102//!     // Note that the edges are one-way.
103//!     //
104//!     //                  7
105//!     //          +-----------------+
106//!     //          |                 |
107//!     //          v   1        2    |  2
108//!     //          0 -----> 1 -----> 3 ---> 4
109//!     //          |        ^        ^      ^
110//!     //          |        | 1      |      |
111//!     //          |        |        | 3    | 1
112//!     //          +------> 2 -------+      |
113//!     //           10      |               |
114//!     //                   +---------------+
115//!     //
116//!     // The graph is represented as an adjacency list where each index,
117//!     // corresponding to a node value, has a list of outgoing edges.
118//!     // Chosen for its efficiency.
119//!     let graph = vec![
120//!         // Node 0
121//!         vec![Edge { node: 2, cost: 10 },
122//!              Edge { node: 1, cost: 1 }],
123//!         // Node 1
124//!         vec![Edge { node: 3, cost: 2 }],
125//!         // Node 2
126//!         vec![Edge { node: 1, cost: 1 },
127//!              Edge { node: 3, cost: 3 },
128//!              Edge { node: 4, cost: 1 }],
129//!         // Node 3
130//!         vec![Edge { node: 0, cost: 7 },
131//!              Edge { node: 4, cost: 2 }],
132//!         // Node 4
133//!         vec![]];
134//!
135//!     assert_eq!(shortest_path(&graph, 0, 1), Some(1));
136//!     assert_eq!(shortest_path(&graph, 0, 3), Some(3));
137//!     assert_eq!(shortest_path(&graph, 3, 0), Some(7));
138//!     assert_eq!(shortest_path(&graph, 0, 4), Some(5));
139//!     assert_eq!(shortest_path(&graph, 4, 0), None);
140//! }
141//! ```
142
143#![allow(missing_docs)]
144#![stable(feature = "rust1", since = "1.0.0")]
145
146use core::alloc::Allocator;
147use core::iter::{FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen};
148use core::mem::{self, ManuallyDrop, swap};
149use core::num::NonZero;
150use core::ops::{Deref, DerefMut};
151use core::{fmt, ptr};
152
153use crate::alloc::Global;
154use crate::collections::TryReserveError;
155use crate::slice;
156#[cfg(not(test))]
157use crate::vec::AsVecIntoIter;
158use crate::vec::{self, Vec};
159
160/// A priority queue implemented with a binary heap.
161///
162/// This will be a max-heap.
163///
164/// It is a logic error for an item to be modified in such a way that the
165/// item's ordering relative to any other item, as determined by the [`Ord`]
166/// trait, changes while it is in the heap. This is normally only possible
167/// through interior mutability, global state, I/O, or unsafe code. The
168/// behavior resulting from such a logic error is not specified, but will
169/// be encapsulated to the `BinaryHeap` that observed the logic error and not
170/// result in undefined behavior. This could include panics, incorrect results,
171/// aborts, memory leaks, and non-termination.
172///
173/// As long as no elements change their relative order while being in the heap
174/// as described above, the API of `BinaryHeap` guarantees that the heap
175/// invariant remains intact i.e. its methods all behave as documented. For
176/// example if a method is documented as iterating in sorted order, that's
177/// guaranteed to work as long as elements in the heap have not changed order,
178/// even in the presence of closures getting unwinded out of, iterators getting
179/// leaked, and similar foolishness.
180///
181/// # Examples
182///
183/// ```
184/// use std::collections::BinaryHeap;
185///
186/// // Type inference lets us omit an explicit type signature (which
187/// // would be `BinaryHeap<i32>` in this example).
188/// let mut heap = BinaryHeap::new();
189///
190/// // We can use peek to look at the next item in the heap. In this case,
191/// // there's no items in there yet so we get None.
192/// assert_eq!(heap.peek(), None);
193///
194/// // Let's add some scores...
195/// heap.push(1);
196/// heap.push(5);
197/// heap.push(2);
198///
199/// // Now peek shows the most important item in the heap.
200/// assert_eq!(heap.peek(), Some(&5));
201///
202/// // We can check the length of a heap.
203/// assert_eq!(heap.len(), 3);
204///
205/// // We can iterate over the items in the heap, although they are returned in
206/// // a random order.
207/// for x in &heap {
208///     println!("{x}");
209/// }
210///
211/// // If we instead pop these scores, they should come back in order.
212/// assert_eq!(heap.pop(), Some(5));
213/// assert_eq!(heap.pop(), Some(2));
214/// assert_eq!(heap.pop(), Some(1));
215/// assert_eq!(heap.pop(), None);
216///
217/// // We can clear the heap of any remaining items.
218/// heap.clear();
219///
220/// // The heap should now be empty.
221/// assert!(heap.is_empty())
222/// ```
223///
224/// A `BinaryHeap` with a known list of items can be initialized from an array:
225///
226/// ```
227/// use std::collections::BinaryHeap;
228///
229/// let heap = BinaryHeap::from([1, 5, 2]);
230/// ```
231///
232/// ## Min-heap
233///
234/// Either [`core::cmp::Reverse`] or a custom [`Ord`] implementation can be used to
235/// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest
236/// value instead of the greatest one.
237///
238/// ```
239/// use std::collections::BinaryHeap;
240/// use std::cmp::Reverse;
241///
242/// let mut heap = BinaryHeap::new();
243///
244/// // Wrap values in `Reverse`
245/// heap.push(Reverse(1));
246/// heap.push(Reverse(5));
247/// heap.push(Reverse(2));
248///
249/// // If we pop these scores now, they should come back in the reverse order.
250/// assert_eq!(heap.pop(), Some(Reverse(1)));
251/// assert_eq!(heap.pop(), Some(Reverse(2)));
252/// assert_eq!(heap.pop(), Some(Reverse(5)));
253/// assert_eq!(heap.pop(), None);
254/// ```
255///
256/// # Time complexity
257///
258/// | [push]  | [pop]         | [peek]/[peek\_mut] |
259/// |---------|---------------|--------------------|
260/// | *O*(1)~ | *O*(log(*n*)) | *O*(1)             |
261///
262/// The value for `push` is an expected cost; the method documentation gives a
263/// more detailed analysis.
264///
265/// [`core::cmp::Reverse`]: core::cmp::Reverse
266/// [`Cell`]: core::cell::Cell
267/// [`RefCell`]: core::cell::RefCell
268/// [push]: BinaryHeap::push
269/// [pop]: BinaryHeap::pop
270/// [peek]: BinaryHeap::peek
271/// [peek\_mut]: BinaryHeap::peek_mut
272#[stable(feature = "rust1", since = "1.0.0")]
273#[cfg_attr(not(test), rustc_diagnostic_item = "BinaryHeap")]
274pub struct BinaryHeap<
275    T,
276    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
277> {
278    data: Vec<T, A>,
279}
280
281/// Structure wrapping a mutable reference to the greatest item on a
282/// `BinaryHeap`.
283///
284/// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
285/// its documentation for more.
286///
287/// [`peek_mut`]: BinaryHeap::peek_mut
288#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
289pub struct PeekMut<
290    'a,
291    T: 'a + Ord,
292    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
293> {
294    heap: &'a mut BinaryHeap<T, A>,
295    // If a set_len + sift_down are required, this is Some. If a &mut T has not
296    // yet been exposed to peek_mut()'s caller, it's None.
297    original_len: Option<NonZero<usize>>,
298}
299
300#[stable(feature = "collection_debug", since = "1.17.0")]
301impl<T: Ord + fmt::Debug, A: Allocator> fmt::Debug for PeekMut<'_, T, A> {
302    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303        f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish()
304    }
305}
306
307#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
308impl<T: Ord, A: Allocator> Drop for PeekMut<'_, T, A> {
309    fn drop(&mut self) {
310        if let Some(original_len) = self.original_len {
311            // SAFETY: That's how many elements were in the Vec at the time of
312            // the PeekMut::deref_mut call, and therefore also at the time of
313            // the BinaryHeap::peek_mut call. Since the PeekMut did not end up
314            // getting leaked, we are now undoing the leak amplification that
315            // the DerefMut prepared for.
316            unsafe { self.heap.data.set_len(original_len.get()) };
317
318            // SAFETY: PeekMut is only instantiated for non-empty heaps.
319            unsafe { self.heap.sift_down(0) };
320        }
321    }
322}
323
324#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
325impl<T: Ord, A: Allocator> Deref for PeekMut<'_, T, A> {
326    type Target = T;
327    fn deref(&self) -> &T {
328        debug_assert!(!self.heap.is_empty());
329        // SAFE: PeekMut is only instantiated for non-empty heaps
330        unsafe { self.heap.data.get_unchecked(0) }
331    }
332}
333
334#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
335impl<T: Ord, A: Allocator> DerefMut for PeekMut<'_, T, A> {
336    fn deref_mut(&mut self) -> &mut T {
337        debug_assert!(!self.heap.is_empty());
338
339        let len = self.heap.len();
340        if len > 1 {
341            // Here we preemptively leak all the rest of the underlying vector
342            // after the currently max element. If the caller mutates the &mut T
343            // we're about to give them, and then leaks the PeekMut, all these
344            // elements will remain leaked. If they don't leak the PeekMut, then
345            // either Drop or PeekMut::pop will un-leak the vector elements.
346            //
347            // This is technique is described throughout several other places in
348            // the standard library as "leak amplification".
349            unsafe {
350                // SAFETY: len > 1 so len != 0.
351                self.original_len = Some(NonZero::new_unchecked(len));
352                // SAFETY: len > 1 so all this does for now is leak elements,
353                // which is safe.
354                self.heap.data.set_len(1);
355            }
356        }
357
358        // SAFE: PeekMut is only instantiated for non-empty heaps
359        unsafe { self.heap.data.get_unchecked_mut(0) }
360    }
361}
362
363impl<'a, T: Ord, A: Allocator> PeekMut<'a, T, A> {
364    /// Sifts the current element to its new position.
365    ///
366    /// Afterwards refers to the new element. Returns if the element changed.
367    ///
368    /// ## Examples
369    ///
370    /// The condition can be used to upper bound all elements in the heap. When only few elements
371    /// are affected, the heap's sort ensures this is faster than a reconstruction from the raw
372    /// element list and requires no additional allocation.
373    ///
374    /// ```
375    /// #![feature(binary_heap_peek_mut_refresh)]
376    /// use std::collections::BinaryHeap;
377    ///
378    /// let mut heap: BinaryHeap<u32> = (0..128).collect();
379    /// let mut peek = heap.peek_mut().unwrap();
380    ///
381    /// loop {
382    ///     *peek = 99;
383    ///
384    ///     if !peek.refresh() {
385    ///         break;
386    ///     }
387    /// }
388    ///
389    /// // Post condition, this is now an upper bound.
390    /// assert!(*peek < 100);
391    /// ```
392    ///
393    /// When the element remains the maximum after modification, the peek remains unchanged:
394    ///
395    /// ```
396    /// #![feature(binary_heap_peek_mut_refresh)]
397    /// use std::collections::BinaryHeap;
398    ///
399    /// let mut heap: BinaryHeap<u32> = [1, 2, 3].into();
400    /// let mut peek = heap.peek_mut().unwrap();
401    ///
402    /// assert_eq!(*peek, 3);
403    /// *peek = 42;
404    ///
405    /// // When we refresh, the peek is updated to the new maximum.
406    /// assert!(!peek.refresh(), "42 is even larger than 3");
407    /// assert_eq!(*peek, 42);
408    /// ```
409    #[unstable(feature = "binary_heap_peek_mut_refresh", issue = "138355")]
410    #[must_use = "is equivalent to dropping and getting a new PeekMut except for return information"]
411    pub fn refresh(&mut self) -> bool {
412        // The length of the underlying heap is unchanged by sifting down. The value stored for leak
413        // amplification thus remains accurate. We erase the leak amplification firstly because the
414        // operation is then equivalent to constructing a new PeekMut and secondly this avoids any
415        // future complication where original_len being non-empty would be interpreted as the heap
416        // having been leak amplified instead of checking the heap itself.
417        if let Some(original_len) = self.original_len.take() {
418            // SAFETY: This is how many elements were in the Vec at the time of
419            // the BinaryHeap::peek_mut call.
420            unsafe { self.heap.data.set_len(original_len.get()) };
421
422            // The length of the heap did not change by sifting, upholding our own invariants.
423
424            // SAFETY: PeekMut is only instantiated for non-empty heaps.
425            (unsafe { self.heap.sift_down(0) }) != 0
426        } else {
427            // The element was not modified.
428            false
429        }
430    }
431
432    /// Removes the peeked value from the heap and returns it.
433    #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
434    pub fn pop(mut this: PeekMut<'a, T, A>) -> T {
435        if let Some(original_len) = this.original_len.take() {
436            // SAFETY: This is how many elements were in the Vec at the time of
437            // the BinaryHeap::peek_mut call.
438            unsafe { this.heap.data.set_len(original_len.get()) };
439
440            // Unlike in Drop, here we don't also need to do a sift_down even if
441            // the caller could've mutated the element. It is removed from the
442            // heap on the next line and pop() is not sensitive to its value.
443        }
444
445        // SAFETY: Have a `PeekMut` element proves that the associated binary heap being non-empty,
446        // so the `pop` operation will not fail.
447        unsafe { this.heap.pop().unwrap_unchecked() }
448    }
449}
450
451#[stable(feature = "rust1", since = "1.0.0")]
452impl<T: Clone, A: Allocator + Clone> Clone for BinaryHeap<T, A> {
453    fn clone(&self) -> Self {
454        BinaryHeap { data: self.data.clone() }
455    }
456
457    /// Overwrites the contents of `self` with a clone of the contents of `source`.
458    ///
459    /// This method is preferred over simply assigning `source.clone()` to `self`,
460    /// as it avoids reallocation if possible.
461    ///
462    /// See [`Vec::clone_from()`] for more details.
463    fn clone_from(&mut self, source: &Self) {
464        self.data.clone_from(&source.data);
465    }
466}
467
468#[stable(feature = "rust1", since = "1.0.0")]
469impl<T> Default for BinaryHeap<T> {
470    /// Creates an empty `BinaryHeap<T>`.
471    #[inline]
472    fn default() -> BinaryHeap<T> {
473        BinaryHeap::new()
474    }
475}
476
477#[stable(feature = "binaryheap_debug", since = "1.4.0")]
478impl<T: fmt::Debug, A: Allocator> fmt::Debug for BinaryHeap<T, A> {
479    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480        f.debug_list().entries(self.iter()).finish()
481    }
482}
483
484struct RebuildOnDrop<
485    'a,
486    T: Ord,
487    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
488> {
489    heap: &'a mut BinaryHeap<T, A>,
490    rebuild_from: usize,
491}
492
493impl<T: Ord, A: Allocator> Drop for RebuildOnDrop<'_, T, A> {
494    fn drop(&mut self) {
495        self.heap.rebuild_tail(self.rebuild_from);
496    }
497}
498
499impl<T> BinaryHeap<T> {
500    /// Creates an empty `BinaryHeap` as a max-heap.
501    ///
502    /// # Examples
503    ///
504    /// Basic usage:
505    ///
506    /// ```
507    /// use std::collections::BinaryHeap;
508    /// let mut heap = BinaryHeap::new();
509    /// heap.push(4);
510    /// ```
511    #[stable(feature = "rust1", since = "1.0.0")]
512    #[rustc_const_stable(feature = "const_binary_heap_constructor", since = "1.80.0")]
513    #[must_use]
514    pub const fn new() -> BinaryHeap<T> {
515        BinaryHeap { data: vec![] }
516    }
517
518    /// Creates an empty `BinaryHeap` with at least the specified capacity.
519    ///
520    /// The binary heap will be able to hold at least `capacity` elements without
521    /// reallocating. This method is allowed to allocate for more elements than
522    /// `capacity`. If `capacity` is zero, the binary heap will not allocate.
523    ///
524    /// # Examples
525    ///
526    /// Basic usage:
527    ///
528    /// ```
529    /// use std::collections::BinaryHeap;
530    /// let mut heap = BinaryHeap::with_capacity(10);
531    /// heap.push(4);
532    /// ```
533    #[stable(feature = "rust1", since = "1.0.0")]
534    #[must_use]
535    pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
536        BinaryHeap { data: Vec::with_capacity(capacity) }
537    }
538}
539
540impl<T, A: Allocator> BinaryHeap<T, A> {
541    /// Creates an empty `BinaryHeap` as a max-heap, using `A` as allocator.
542    ///
543    /// # Examples
544    ///
545    /// Basic usage:
546    ///
547    /// ```
548    /// #![feature(allocator_api)]
549    ///
550    /// use std::alloc::System;
551    /// use std::collections::BinaryHeap;
552    /// let mut heap = BinaryHeap::new_in(System);
553    /// heap.push(4);
554    /// ```
555    #[unstable(feature = "allocator_api", issue = "32838")]
556    #[must_use]
557    pub const fn new_in(alloc: A) -> BinaryHeap<T, A> {
558        BinaryHeap { data: Vec::new_in(alloc) }
559    }
560
561    /// Creates an empty `BinaryHeap` with at least the specified capacity, using `A` as allocator.
562    ///
563    /// The binary heap will be able to hold at least `capacity` elements without
564    /// reallocating. This method is allowed to allocate for more elements than
565    /// `capacity`. If `capacity` is zero, the binary heap will not allocate.
566    ///
567    /// # Examples
568    ///
569    /// Basic usage:
570    ///
571    /// ```
572    /// #![feature(allocator_api)]
573    ///
574    /// use std::alloc::System;
575    /// use std::collections::BinaryHeap;
576    /// let mut heap = BinaryHeap::with_capacity_in(10, System);
577    /// heap.push(4);
578    /// ```
579    #[unstable(feature = "allocator_api", issue = "32838")]
580    #[must_use]
581    pub fn with_capacity_in(capacity: usize, alloc: A) -> BinaryHeap<T, A> {
582        BinaryHeap { data: Vec::with_capacity_in(capacity, alloc) }
583    }
584}
585
586impl<T: Ord, A: Allocator> BinaryHeap<T, A> {
587    /// Returns a mutable reference to the greatest item in the binary heap, or
588    /// `None` if it is empty.
589    ///
590    /// Note: If the `PeekMut` value is leaked, some heap elements might get
591    /// leaked along with it, but the remaining elements will remain a valid
592    /// heap.
593    ///
594    /// # Examples
595    ///
596    /// Basic usage:
597    ///
598    /// ```
599    /// use std::collections::BinaryHeap;
600    /// let mut heap = BinaryHeap::new();
601    /// assert!(heap.peek_mut().is_none());
602    ///
603    /// heap.push(1);
604    /// heap.push(5);
605    /// heap.push(2);
606    /// if let Some(mut val) = heap.peek_mut() {
607    ///     *val = 0;
608    /// }
609    /// assert_eq!(heap.peek(), Some(&2));
610    /// ```
611    ///
612    /// # Time complexity
613    ///
614    /// If the item is modified then the worst case time complexity is *O*(log(*n*)),
615    /// otherwise it's *O*(1).
616    #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
617    pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, A>> {
618        if self.is_empty() { None } else { Some(PeekMut { heap: self, original_len: None }) }
619    }
620
621    /// Removes the greatest item from the binary heap and returns it, or `None` if it
622    /// is empty.
623    ///
624    /// # Examples
625    ///
626    /// Basic usage:
627    ///
628    /// ```
629    /// use std::collections::BinaryHeap;
630    /// let mut heap = BinaryHeap::from([1, 3]);
631    ///
632    /// assert_eq!(heap.pop(), Some(3));
633    /// assert_eq!(heap.pop(), Some(1));
634    /// assert_eq!(heap.pop(), None);
635    /// ```
636    ///
637    /// # Time complexity
638    ///
639    /// The worst case cost of `pop` on a heap containing *n* elements is *O*(log(*n*)).
640    #[stable(feature = "rust1", since = "1.0.0")]
641    pub fn pop(&mut self) -> Option<T> {
642        self.data.pop().map(|mut item| {
643            if !self.is_empty() {
644                swap(&mut item, &mut self.data[0]);
645                // SAFETY: !self.is_empty() means that self.len() > 0
646                unsafe { self.sift_down_to_bottom(0) };
647            }
648            item
649        })
650    }
651
652    /// Pushes an item onto the binary heap.
653    ///
654    /// # Examples
655    ///
656    /// Basic usage:
657    ///
658    /// ```
659    /// use std::collections::BinaryHeap;
660    /// let mut heap = BinaryHeap::new();
661    /// heap.push(3);
662    /// heap.push(5);
663    /// heap.push(1);
664    ///
665    /// assert_eq!(heap.len(), 3);
666    /// assert_eq!(heap.peek(), Some(&5));
667    /// ```
668    ///
669    /// # Time complexity
670    ///
671    /// The expected cost of `push`, averaged over every possible ordering of
672    /// the elements being pushed, and over a sufficiently large number of
673    /// pushes, is *O*(1). This is the most meaningful cost metric when pushing
674    /// elements that are *not* already in any sorted pattern.
675    ///
676    /// The time complexity degrades if elements are pushed in predominantly
677    /// ascending order. In the worst case, elements are pushed in ascending
678    /// sorted order and the amortized cost per push is *O*(log(*n*)) against a heap
679    /// containing *n* elements.
680    ///
681    /// The worst case cost of a *single* call to `push` is *O*(*n*). The worst case
682    /// occurs when capacity is exhausted and needs a resize. The resize cost
683    /// has been amortized in the previous figures.
684    #[stable(feature = "rust1", since = "1.0.0")]
685    #[rustc_confusables("append", "put")]
686    pub fn push(&mut self, item: T) {
687        let old_len = self.len();
688        self.data.push(item);
689        // SAFETY: Since we pushed a new item it means that
690        //  old_len = self.len() - 1 < self.len()
691        unsafe { self.sift_up(0, old_len) };
692    }
693
694    /// Consumes the `BinaryHeap` and returns a vector in sorted
695    /// (ascending) order.
696    ///
697    /// # Examples
698    ///
699    /// Basic usage:
700    ///
701    /// ```
702    /// use std::collections::BinaryHeap;
703    ///
704    /// let mut heap = BinaryHeap::from([1, 2, 4, 5, 7]);
705    /// heap.push(6);
706    /// heap.push(3);
707    ///
708    /// let vec = heap.into_sorted_vec();
709    /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
710    /// ```
711    #[must_use = "`self` will be dropped if the result is not used"]
712    #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
713    pub fn into_sorted_vec(mut self) -> Vec<T, A> {
714        let mut end = self.len();
715        while end > 1 {
716            end -= 1;
717            // SAFETY: `end` goes from `self.len() - 1` to 1 (both included),
718            //  so it's always a valid index to access.
719            //  It is safe to access index 0 (i.e. `ptr`), because
720            //  1 <= end < self.len(), which means self.len() >= 2.
721            unsafe {
722                let ptr = self.data.as_mut_ptr();
723                ptr::swap(ptr, ptr.add(end));
724            }
725            // SAFETY: `end` goes from `self.len() - 1` to 1 (both included) so:
726            //  0 < 1 <= end <= self.len() - 1 < self.len()
727            //  Which means 0 < end and end < self.len().
728            unsafe { self.sift_down_range(0, end) };
729        }
730        self.into_vec()
731    }
732
733    // The implementations of sift_up and sift_down use unsafe blocks in
734    // order to move an element out of the vector (leaving behind a
735    // hole), shift along the others and move the removed element back into the
736    // vector at the final location of the hole.
737    // The `Hole` type is used to represent this, and make sure
738    // the hole is filled back at the end of its scope, even on panic.
739    // Using a hole reduces the constant factor compared to using swaps,
740    // which involves twice as many moves.
741
742    /// # Safety
743    ///
744    /// The caller must guarantee that `pos < self.len()`.
745    ///
746    /// Returns the new position of the element.
747    unsafe fn sift_up(&mut self, start: usize, pos: usize) -> usize {
748        // Take out the value at `pos` and create a hole.
749        // SAFETY: The caller guarantees that pos < self.len()
750        let mut hole = unsafe { Hole::new(&mut self.data, pos) };
751
752        while hole.pos() > start {
753            let parent = (hole.pos() - 1) / 2;
754
755            // SAFETY: hole.pos() > start >= 0, which means hole.pos() > 0
756            //  and so hole.pos() - 1 can't underflow.
757            //  This guarantees that parent < hole.pos() so
758            //  it's a valid index and also != hole.pos().
759            if hole.element() <= unsafe { hole.get(parent) } {
760                break;
761            }
762
763            // SAFETY: Same as above
764            unsafe { hole.move_to(parent) };
765        }
766
767        hole.pos()
768    }
769
770    /// Take an element at `pos` and move it down the heap,
771    /// while its children are larger.
772    ///
773    /// Returns the new position of the element.
774    ///
775    /// # Safety
776    ///
777    /// The caller must guarantee that `pos < end <= self.len()`.
778    unsafe fn sift_down_range(&mut self, pos: usize, end: usize) -> usize {
779        // SAFETY: The caller guarantees that pos < end <= self.len().
780        let mut hole = unsafe { Hole::new(&mut self.data, pos) };
781        let mut child = 2 * hole.pos() + 1;
782
783        // Loop invariant: child == 2 * hole.pos() + 1.
784        while child <= end.saturating_sub(2) {
785            // compare with the greater of the two children
786            // SAFETY: child < end - 1 < self.len() and
787            //  child + 1 < end <= self.len(), so they're valid indexes.
788            //  child == 2 * hole.pos() + 1 != hole.pos() and
789            //  child + 1 == 2 * hole.pos() + 2 != hole.pos().
790            // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
791            //  if T is a ZST
792            child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
793
794            // if we are already in order, stop.
795            // SAFETY: child is now either the old child or the old child+1
796            //  We already proven that both are < self.len() and != hole.pos()
797            if hole.element() >= unsafe { hole.get(child) } {
798                return hole.pos();
799            }
800
801            // SAFETY: same as above.
802            unsafe { hole.move_to(child) };
803            child = 2 * hole.pos() + 1;
804        }
805
806        // SAFETY: && short circuit, which means that in the
807        //  second condition it's already true that child == end - 1 < self.len().
808        if child == end - 1 && hole.element() < unsafe { hole.get(child) } {
809            // SAFETY: child is already proven to be a valid index and
810            //  child == 2 * hole.pos() + 1 != hole.pos().
811            unsafe { hole.move_to(child) };
812        }
813
814        hole.pos()
815    }
816
817    /// # Safety
818    ///
819    /// The caller must guarantee that `pos < self.len()`.
820    unsafe fn sift_down(&mut self, pos: usize) -> usize {
821        let len = self.len();
822        // SAFETY: pos < len is guaranteed by the caller and
823        //  obviously len = self.len() <= self.len().
824        unsafe { self.sift_down_range(pos, len) }
825    }
826
827    /// Take an element at `pos` and move it all the way down the heap,
828    /// then sift it up to its position.
829    ///
830    /// Note: This is faster when the element is known to be large / should
831    /// be closer to the bottom.
832    ///
833    /// # Safety
834    ///
835    /// The caller must guarantee that `pos < self.len()`.
836    unsafe fn sift_down_to_bottom(&mut self, mut pos: usize) {
837        let end = self.len();
838        let start = pos;
839
840        // SAFETY: The caller guarantees that pos < self.len().
841        let mut hole = unsafe { Hole::new(&mut self.data, pos) };
842        let mut child = 2 * hole.pos() + 1;
843
844        // Loop invariant: child == 2 * hole.pos() + 1.
845        while child <= end.saturating_sub(2) {
846            // SAFETY: child < end - 1 < self.len() and
847            //  child + 1 < end <= self.len(), so they're valid indexes.
848            //  child == 2 * hole.pos() + 1 != hole.pos() and
849            //  child + 1 == 2 * hole.pos() + 2 != hole.pos().
850            // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
851            //  if T is a ZST
852            child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
853
854            // SAFETY: Same as above
855            unsafe { hole.move_to(child) };
856            child = 2 * hole.pos() + 1;
857        }
858
859        if child == end - 1 {
860            // SAFETY: child == end - 1 < self.len(), so it's a valid index
861            //  and child == 2 * hole.pos() + 1 != hole.pos().
862            unsafe { hole.move_to(child) };
863        }
864        pos = hole.pos();
865        drop(hole);
866
867        // SAFETY: pos is the position in the hole and was already proven
868        //  to be a valid index.
869        unsafe { self.sift_up(start, pos) };
870    }
871
872    /// Rebuild assuming data[0..start] is still a proper heap.
873    fn rebuild_tail(&mut self, start: usize) {
874        if start == self.len() {
875            return;
876        }
877
878        let tail_len = self.len() - start;
879
880        #[inline(always)]
881        fn log2_fast(x: usize) -> usize {
882            (usize::BITS - x.leading_zeros() - 1) as usize
883        }
884
885        // `rebuild` takes O(self.len()) operations
886        // and about 2 * self.len() comparisons in the worst case
887        // while repeating `sift_up` takes O(tail_len * log(start)) operations
888        // and about 1 * tail_len * log_2(start) comparisons in the worst case,
889        // assuming start >= tail_len. For larger heaps, the crossover point
890        // no longer follows this reasoning and was determined empirically.
891        let better_to_rebuild = if start < tail_len {
892            true
893        } else if self.len() <= 2048 {
894            2 * self.len() < tail_len * log2_fast(start)
895        } else {
896            2 * self.len() < tail_len * 11
897        };
898
899        if better_to_rebuild {
900            self.rebuild();
901        } else {
902            for i in start..self.len() {
903                // SAFETY: The index `i` is always less than self.len().
904                unsafe { self.sift_up(0, i) };
905            }
906        }
907    }
908
909    fn rebuild(&mut self) {
910        let mut n = self.len() / 2;
911        while n > 0 {
912            n -= 1;
913            // SAFETY: n starts from self.len() / 2 and goes down to 0.
914            //  The only case when !(n < self.len()) is if
915            //  self.len() == 0, but it's ruled out by the loop condition.
916            unsafe { self.sift_down(n) };
917        }
918    }
919
920    /// Moves all the elements of `other` into `self`, leaving `other` empty.
921    ///
922    /// # Examples
923    ///
924    /// Basic usage:
925    ///
926    /// ```
927    /// use std::collections::BinaryHeap;
928    ///
929    /// let mut a = BinaryHeap::from([-10, 1, 2, 3, 3]);
930    /// let mut b = BinaryHeap::from([-20, 5, 43]);
931    ///
932    /// a.append(&mut b);
933    ///
934    /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
935    /// assert!(b.is_empty());
936    /// ```
937    #[stable(feature = "binary_heap_append", since = "1.11.0")]
938    pub fn append(&mut self, other: &mut Self) {
939        if self.len() < other.len() {
940            swap(self, other);
941        }
942
943        let start = self.data.len();
944
945        self.data.append(&mut other.data);
946
947        self.rebuild_tail(start);
948    }
949
950    /// Clears the binary heap, returning an iterator over the removed elements
951    /// in heap order. If the iterator is dropped before being fully consumed,
952    /// it drops the remaining elements in heap order.
953    ///
954    /// The returned iterator keeps a mutable borrow on the heap to optimize
955    /// its implementation.
956    ///
957    /// Note:
958    /// * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`.
959    ///   You should use the latter for most cases.
960    ///
961    /// # Examples
962    ///
963    /// Basic usage:
964    ///
965    /// ```
966    /// #![feature(binary_heap_drain_sorted)]
967    /// use std::collections::BinaryHeap;
968    ///
969    /// let mut heap = BinaryHeap::from([1, 2, 3, 4, 5]);
970    /// assert_eq!(heap.len(), 5);
971    ///
972    /// drop(heap.drain_sorted()); // removes all elements in heap order
973    /// assert_eq!(heap.len(), 0);
974    /// ```
975    #[inline]
976    #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
977    pub fn drain_sorted(&mut self) -> DrainSorted<'_, T, A> {
978        DrainSorted { inner: self }
979    }
980
981    /// Retains only the elements specified by the predicate.
982    ///
983    /// In other words, remove all elements `e` for which `f(&e)` returns
984    /// `false`. The elements are visited in unsorted (and unspecified) order.
985    ///
986    /// # Examples
987    ///
988    /// Basic usage:
989    ///
990    /// ```
991    /// use std::collections::BinaryHeap;
992    ///
993    /// let mut heap = BinaryHeap::from([-10, -5, 1, 2, 4, 13]);
994    ///
995    /// heap.retain(|x| x % 2 == 0); // only keep even numbers
996    ///
997    /// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
998    /// ```
999    #[stable(feature = "binary_heap_retain", since = "1.70.0")]
1000    pub fn retain<F>(&mut self, mut f: F)
1001    where
1002        F: FnMut(&T) -> bool,
1003    {
1004        // rebuild_start will be updated to the first touched element below, and the rebuild will
1005        // only be done for the tail.
1006        let mut guard = RebuildOnDrop { rebuild_from: self.len(), heap: self };
1007        let mut i = 0;
1008
1009        guard.heap.data.retain(|e| {
1010            let keep = f(e);
1011            if !keep && i < guard.rebuild_from {
1012                guard.rebuild_from = i;
1013            }
1014            i += 1;
1015            keep
1016        });
1017    }
1018}
1019
1020impl<T, A: Allocator> BinaryHeap<T, A> {
1021    /// Returns an iterator visiting all values in the underlying vector, in
1022    /// arbitrary order.
1023    ///
1024    /// # Examples
1025    ///
1026    /// Basic usage:
1027    ///
1028    /// ```
1029    /// use std::collections::BinaryHeap;
1030    /// let heap = BinaryHeap::from([1, 2, 3, 4]);
1031    ///
1032    /// // Print 1, 2, 3, 4 in arbitrary order
1033    /// for x in heap.iter() {
1034    ///     println!("{x}");
1035    /// }
1036    /// ```
1037    #[stable(feature = "rust1", since = "1.0.0")]
1038    #[cfg_attr(not(test), rustc_diagnostic_item = "binaryheap_iter")]
1039    pub fn iter(&self) -> Iter<'_, T> {
1040        Iter { iter: self.data.iter() }
1041    }
1042
1043    /// Returns an iterator which retrieves elements in heap order.
1044    ///
1045    /// This method consumes the original heap.
1046    ///
1047    /// # Examples
1048    ///
1049    /// Basic usage:
1050    ///
1051    /// ```
1052    /// #![feature(binary_heap_into_iter_sorted)]
1053    /// use std::collections::BinaryHeap;
1054    /// let heap = BinaryHeap::from([1, 2, 3, 4, 5]);
1055    ///
1056    /// assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), [5, 4]);
1057    /// ```
1058    #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1059    pub fn into_iter_sorted(self) -> IntoIterSorted<T, A> {
1060        IntoIterSorted { inner: self }
1061    }
1062
1063    /// Returns the greatest item in the binary heap, or `None` if it is empty.
1064    ///
1065    /// # Examples
1066    ///
1067    /// Basic usage:
1068    ///
1069    /// ```
1070    /// use std::collections::BinaryHeap;
1071    /// let mut heap = BinaryHeap::new();
1072    /// assert_eq!(heap.peek(), None);
1073    ///
1074    /// heap.push(1);
1075    /// heap.push(5);
1076    /// heap.push(2);
1077    /// assert_eq!(heap.peek(), Some(&5));
1078    ///
1079    /// ```
1080    ///
1081    /// # Time complexity
1082    ///
1083    /// Cost is *O*(1) in the worst case.
1084    #[must_use]
1085    #[stable(feature = "rust1", since = "1.0.0")]
1086    pub fn peek(&self) -> Option<&T> {
1087        self.data.get(0)
1088    }
1089
1090    /// Returns the number of elements the binary heap can hold without reallocating.
1091    ///
1092    /// # Examples
1093    ///
1094    /// Basic usage:
1095    ///
1096    /// ```
1097    /// use std::collections::BinaryHeap;
1098    /// let mut heap = BinaryHeap::with_capacity(100);
1099    /// assert!(heap.capacity() >= 100);
1100    /// heap.push(4);
1101    /// ```
1102    #[must_use]
1103    #[stable(feature = "rust1", since = "1.0.0")]
1104    pub fn capacity(&self) -> usize {
1105        self.data.capacity()
1106    }
1107
1108    /// Reserves the minimum capacity for at least `additional` elements more than
1109    /// the current length. Unlike [`reserve`], this will not
1110    /// deliberately over-allocate to speculatively avoid frequent allocations.
1111    /// After calling `reserve_exact`, capacity will be greater than or equal to
1112    /// `self.len() + additional`. Does nothing if the capacity is already
1113    /// sufficient.
1114    ///
1115    /// [`reserve`]: BinaryHeap::reserve
1116    ///
1117    /// # Panics
1118    ///
1119    /// Panics if the new capacity overflows [`usize`].
1120    ///
1121    /// # Examples
1122    ///
1123    /// Basic usage:
1124    ///
1125    /// ```
1126    /// use std::collections::BinaryHeap;
1127    /// let mut heap = BinaryHeap::new();
1128    /// heap.reserve_exact(100);
1129    /// assert!(heap.capacity() >= 100);
1130    /// heap.push(4);
1131    /// ```
1132    ///
1133    /// [`reserve`]: BinaryHeap::reserve
1134    #[stable(feature = "rust1", since = "1.0.0")]
1135    pub fn reserve_exact(&mut self, additional: usize) {
1136        self.data.reserve_exact(additional);
1137    }
1138
1139    /// Reserves capacity for at least `additional` elements more than the
1140    /// current length. The allocator may reserve more space to speculatively
1141    /// avoid frequent allocations. After calling `reserve`,
1142    /// capacity will be greater than or equal to `self.len() + additional`.
1143    /// Does nothing if capacity is already sufficient.
1144    ///
1145    /// # Panics
1146    ///
1147    /// Panics if the new capacity overflows [`usize`].
1148    ///
1149    /// # Examples
1150    ///
1151    /// Basic usage:
1152    ///
1153    /// ```
1154    /// use std::collections::BinaryHeap;
1155    /// let mut heap = BinaryHeap::new();
1156    /// heap.reserve(100);
1157    /// assert!(heap.capacity() >= 100);
1158    /// heap.push(4);
1159    /// ```
1160    #[stable(feature = "rust1", since = "1.0.0")]
1161    pub fn reserve(&mut self, additional: usize) {
1162        self.data.reserve(additional);
1163    }
1164
1165    /// Tries to reserve the minimum capacity for at least `additional` elements
1166    /// more than the current length. Unlike [`try_reserve`], this will not
1167    /// deliberately over-allocate to speculatively avoid frequent allocations.
1168    /// After calling `try_reserve_exact`, capacity will be greater than or
1169    /// equal to `self.len() + additional` if it returns `Ok(())`.
1170    /// Does nothing if the capacity is already sufficient.
1171    ///
1172    /// Note that the allocator may give the collection more space than it
1173    /// requests. Therefore, capacity can not be relied upon to be precisely
1174    /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1175    ///
1176    /// [`try_reserve`]: BinaryHeap::try_reserve
1177    ///
1178    /// # Errors
1179    ///
1180    /// If the capacity overflows, or the allocator reports a failure, then an error
1181    /// is returned.
1182    ///
1183    /// # Examples
1184    ///
1185    /// ```
1186    /// use std::collections::BinaryHeap;
1187    /// use std::collections::TryReserveError;
1188    ///
1189    /// fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
1190    ///     let mut heap = BinaryHeap::new();
1191    ///
1192    ///     // Pre-reserve the memory, exiting if we can't
1193    ///     heap.try_reserve_exact(data.len())?;
1194    ///
1195    ///     // Now we know this can't OOM in the middle of our complex work
1196    ///     heap.extend(data.iter());
1197    ///
1198    ///     Ok(heap.pop())
1199    /// }
1200    /// # find_max_slow(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
1201    /// ```
1202    #[stable(feature = "try_reserve_2", since = "1.63.0")]
1203    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1204        self.data.try_reserve_exact(additional)
1205    }
1206
1207    /// Tries to reserve capacity for at least `additional` elements more than the
1208    /// current length. The allocator may reserve more space to speculatively
1209    /// avoid frequent allocations. After calling `try_reserve`, capacity will be
1210    /// greater than or equal to `self.len() + additional` if it returns
1211    /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1212    /// preserves the contents even if an error occurs.
1213    ///
1214    /// # Errors
1215    ///
1216    /// If the capacity overflows, or the allocator reports a failure, then an error
1217    /// is returned.
1218    ///
1219    /// # Examples
1220    ///
1221    /// ```
1222    /// use std::collections::BinaryHeap;
1223    /// use std::collections::TryReserveError;
1224    ///
1225    /// fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
1226    ///     let mut heap = BinaryHeap::new();
1227    ///
1228    ///     // Pre-reserve the memory, exiting if we can't
1229    ///     heap.try_reserve(data.len())?;
1230    ///
1231    ///     // Now we know this can't OOM in the middle of our complex work
1232    ///     heap.extend(data.iter());
1233    ///
1234    ///     Ok(heap.pop())
1235    /// }
1236    /// # find_max_slow(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
1237    /// ```
1238    #[stable(feature = "try_reserve_2", since = "1.63.0")]
1239    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1240        self.data.try_reserve(additional)
1241    }
1242
1243    /// Discards as much additional capacity as possible.
1244    ///
1245    /// # Examples
1246    ///
1247    /// Basic usage:
1248    ///
1249    /// ```
1250    /// use std::collections::BinaryHeap;
1251    /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
1252    ///
1253    /// assert!(heap.capacity() >= 100);
1254    /// heap.shrink_to_fit();
1255    /// assert!(heap.capacity() == 0);
1256    /// ```
1257    #[stable(feature = "rust1", since = "1.0.0")]
1258    pub fn shrink_to_fit(&mut self) {
1259        self.data.shrink_to_fit();
1260    }
1261
1262    /// Discards capacity with a lower bound.
1263    ///
1264    /// The capacity will remain at least as large as both the length
1265    /// and the supplied value.
1266    ///
1267    /// If the current capacity is less than the lower limit, this is a no-op.
1268    ///
1269    /// # Examples
1270    ///
1271    /// ```
1272    /// use std::collections::BinaryHeap;
1273    /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
1274    ///
1275    /// assert!(heap.capacity() >= 100);
1276    /// heap.shrink_to(10);
1277    /// assert!(heap.capacity() >= 10);
1278    /// ```
1279    #[inline]
1280    #[stable(feature = "shrink_to", since = "1.56.0")]
1281    pub fn shrink_to(&mut self, min_capacity: usize) {
1282        self.data.shrink_to(min_capacity)
1283    }
1284
1285    /// Returns a slice of all values in the underlying vector, in arbitrary
1286    /// order.
1287    ///
1288    /// # Examples
1289    ///
1290    /// Basic usage:
1291    ///
1292    /// ```
1293    /// use std::collections::BinaryHeap;
1294    /// use std::io::{self, Write};
1295    ///
1296    /// let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
1297    ///
1298    /// io::sink().write(heap.as_slice()).unwrap();
1299    /// ```
1300    #[must_use]
1301    #[stable(feature = "binary_heap_as_slice", since = "1.80.0")]
1302    pub fn as_slice(&self) -> &[T] {
1303        self.data.as_slice()
1304    }
1305
1306    /// Consumes the `BinaryHeap` and returns the underlying vector
1307    /// in arbitrary order.
1308    ///
1309    /// # Examples
1310    ///
1311    /// Basic usage:
1312    ///
1313    /// ```
1314    /// use std::collections::BinaryHeap;
1315    /// let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
1316    /// let vec = heap.into_vec();
1317    ///
1318    /// // Will print in some order
1319    /// for x in vec {
1320    ///     println!("{x}");
1321    /// }
1322    /// ```
1323    #[must_use = "`self` will be dropped if the result is not used"]
1324    #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1325    pub fn into_vec(self) -> Vec<T, A> {
1326        self.into()
1327    }
1328
1329    /// Returns a reference to the underlying allocator.
1330    #[unstable(feature = "allocator_api", issue = "32838")]
1331    #[inline]
1332    pub fn allocator(&self) -> &A {
1333        self.data.allocator()
1334    }
1335
1336    /// Returns the length of the binary heap.
1337    ///
1338    /// # Examples
1339    ///
1340    /// Basic usage:
1341    ///
1342    /// ```
1343    /// use std::collections::BinaryHeap;
1344    /// let heap = BinaryHeap::from([1, 3]);
1345    ///
1346    /// assert_eq!(heap.len(), 2);
1347    /// ```
1348    #[must_use]
1349    #[stable(feature = "rust1", since = "1.0.0")]
1350    #[rustc_confusables("length", "size")]
1351    pub fn len(&self) -> usize {
1352        self.data.len()
1353    }
1354
1355    /// Checks if the binary heap is empty.
1356    ///
1357    /// # Examples
1358    ///
1359    /// Basic usage:
1360    ///
1361    /// ```
1362    /// use std::collections::BinaryHeap;
1363    /// let mut heap = BinaryHeap::new();
1364    ///
1365    /// assert!(heap.is_empty());
1366    ///
1367    /// heap.push(3);
1368    /// heap.push(5);
1369    /// heap.push(1);
1370    ///
1371    /// assert!(!heap.is_empty());
1372    /// ```
1373    #[must_use]
1374    #[stable(feature = "rust1", since = "1.0.0")]
1375    pub fn is_empty(&self) -> bool {
1376        self.len() == 0
1377    }
1378
1379    /// Clears the binary heap, returning an iterator over the removed elements
1380    /// in arbitrary order. If the iterator is dropped before being fully
1381    /// consumed, it drops the remaining elements in arbitrary order.
1382    ///
1383    /// The returned iterator keeps a mutable borrow on the heap to optimize
1384    /// its implementation.
1385    ///
1386    /// # Examples
1387    ///
1388    /// Basic usage:
1389    ///
1390    /// ```
1391    /// use std::collections::BinaryHeap;
1392    /// let mut heap = BinaryHeap::from([1, 3]);
1393    ///
1394    /// assert!(!heap.is_empty());
1395    ///
1396    /// for x in heap.drain() {
1397    ///     println!("{x}");
1398    /// }
1399    ///
1400    /// assert!(heap.is_empty());
1401    /// ```
1402    #[inline]
1403    #[stable(feature = "drain", since = "1.6.0")]
1404    pub fn drain(&mut self) -> Drain<'_, T, A> {
1405        Drain { iter: self.data.drain(..) }
1406    }
1407
1408    /// Drops all items from the binary heap.
1409    ///
1410    /// # Examples
1411    ///
1412    /// Basic usage:
1413    ///
1414    /// ```
1415    /// use std::collections::BinaryHeap;
1416    /// let mut heap = BinaryHeap::from([1, 3]);
1417    ///
1418    /// assert!(!heap.is_empty());
1419    ///
1420    /// heap.clear();
1421    ///
1422    /// assert!(heap.is_empty());
1423    /// ```
1424    #[stable(feature = "rust1", since = "1.0.0")]
1425    pub fn clear(&mut self) {
1426        self.drain();
1427    }
1428}
1429
1430/// Hole represents a hole in a slice i.e., an index without valid value
1431/// (because it was moved from or duplicated).
1432/// In drop, `Hole` will restore the slice by filling the hole
1433/// position with the value that was originally removed.
1434struct Hole<'a, T: 'a> {
1435    data: &'a mut [T],
1436    elt: ManuallyDrop<T>,
1437    pos: usize,
1438}
1439
1440impl<'a, T> Hole<'a, T> {
1441    /// Creates a new `Hole` at index `pos`.
1442    ///
1443    /// Unsafe because pos must be within the data slice.
1444    #[inline]
1445    unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
1446        debug_assert!(pos < data.len());
1447        // SAFE: pos should be inside the slice
1448        let elt = unsafe { ptr::read(data.get_unchecked(pos)) };
1449        Hole { data, elt: ManuallyDrop::new(elt), pos }
1450    }
1451
1452    #[inline]
1453    fn pos(&self) -> usize {
1454        self.pos
1455    }
1456
1457    /// Returns a reference to the element removed.
1458    #[inline]
1459    fn element(&self) -> &T {
1460        &self.elt
1461    }
1462
1463    /// Returns a reference to the element at `index`.
1464    ///
1465    /// Unsafe because index must be within the data slice and not equal to pos.
1466    #[inline]
1467    unsafe fn get(&self, index: usize) -> &T {
1468        debug_assert!(index != self.pos);
1469        debug_assert!(index < self.data.len());
1470        unsafe { self.data.get_unchecked(index) }
1471    }
1472
1473    /// Move hole to new location
1474    ///
1475    /// Unsafe because index must be within the data slice and not equal to pos.
1476    #[inline]
1477    unsafe fn move_to(&mut self, index: usize) {
1478        debug_assert!(index != self.pos);
1479        debug_assert!(index < self.data.len());
1480        unsafe {
1481            let ptr = self.data.as_mut_ptr();
1482            let index_ptr: *const _ = ptr.add(index);
1483            let hole_ptr = ptr.add(self.pos);
1484            ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1485        }
1486        self.pos = index;
1487    }
1488}
1489
1490impl<T> Drop for Hole<'_, T> {
1491    #[inline]
1492    fn drop(&mut self) {
1493        // fill the hole again
1494        unsafe {
1495            let pos = self.pos;
1496            ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
1497        }
1498    }
1499}
1500
1501/// An iterator over the elements of a `BinaryHeap`.
1502///
1503/// This `struct` is created by [`BinaryHeap::iter()`]. See its
1504/// documentation for more.
1505///
1506/// [`iter`]: BinaryHeap::iter
1507#[must_use = "iterators are lazy and do nothing unless consumed"]
1508#[stable(feature = "rust1", since = "1.0.0")]
1509pub struct Iter<'a, T: 'a> {
1510    iter: slice::Iter<'a, T>,
1511}
1512
1513#[stable(feature = "default_iters_sequel", since = "1.82.0")]
1514impl<T> Default for Iter<'_, T> {
1515    /// Creates an empty `binary_heap::Iter`.
1516    ///
1517    /// ```
1518    /// # use std::collections::binary_heap;
1519    /// let iter: binary_heap::Iter<'_, u8> = Default::default();
1520    /// assert_eq!(iter.len(), 0);
1521    /// ```
1522    fn default() -> Self {
1523        Iter { iter: Default::default() }
1524    }
1525}
1526
1527#[stable(feature = "collection_debug", since = "1.17.0")]
1528impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1529    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1530        f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
1531    }
1532}
1533
1534// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1535#[stable(feature = "rust1", since = "1.0.0")]
1536impl<T> Clone for Iter<'_, T> {
1537    fn clone(&self) -> Self {
1538        Iter { iter: self.iter.clone() }
1539    }
1540}
1541
1542#[stable(feature = "rust1", since = "1.0.0")]
1543impl<'a, T> Iterator for Iter<'a, T> {
1544    type Item = &'a T;
1545
1546    #[inline]
1547    fn next(&mut self) -> Option<&'a T> {
1548        self.iter.next()
1549    }
1550
1551    #[inline]
1552    fn size_hint(&self) -> (usize, Option<usize>) {
1553        self.iter.size_hint()
1554    }
1555
1556    #[inline]
1557    fn last(self) -> Option<&'a T> {
1558        self.iter.last()
1559    }
1560}
1561
1562#[stable(feature = "rust1", since = "1.0.0")]
1563impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1564    #[inline]
1565    fn next_back(&mut self) -> Option<&'a T> {
1566        self.iter.next_back()
1567    }
1568}
1569
1570#[stable(feature = "rust1", since = "1.0.0")]
1571impl<T> ExactSizeIterator for Iter<'_, T> {
1572    fn is_empty(&self) -> bool {
1573        self.iter.is_empty()
1574    }
1575}
1576
1577#[stable(feature = "fused", since = "1.26.0")]
1578impl<T> FusedIterator for Iter<'_, T> {}
1579
1580/// An owning iterator over the elements of a `BinaryHeap`.
1581///
1582/// This `struct` is created by [`BinaryHeap::into_iter()`]
1583/// (provided by the [`IntoIterator`] trait). See its documentation for more.
1584///
1585/// [`into_iter`]: BinaryHeap::into_iter
1586#[stable(feature = "rust1", since = "1.0.0")]
1587#[derive(Clone)]
1588pub struct IntoIter<
1589    T,
1590    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1591> {
1592    iter: vec::IntoIter<T, A>,
1593}
1594
1595impl<T, A: Allocator> IntoIter<T, A> {
1596    /// Returns a reference to the underlying allocator.
1597    #[unstable(feature = "allocator_api", issue = "32838")]
1598    pub fn allocator(&self) -> &A {
1599        self.iter.allocator()
1600    }
1601}
1602
1603#[stable(feature = "collection_debug", since = "1.17.0")]
1604impl<T: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<T, A> {
1605    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1606        f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
1607    }
1608}
1609
1610#[stable(feature = "rust1", since = "1.0.0")]
1611impl<T, A: Allocator> Iterator for IntoIter<T, A> {
1612    type Item = T;
1613
1614    #[inline]
1615    fn next(&mut self) -> Option<T> {
1616        self.iter.next()
1617    }
1618
1619    #[inline]
1620    fn size_hint(&self) -> (usize, Option<usize>) {
1621        self.iter.size_hint()
1622    }
1623}
1624
1625#[stable(feature = "rust1", since = "1.0.0")]
1626impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
1627    #[inline]
1628    fn next_back(&mut self) -> Option<T> {
1629        self.iter.next_back()
1630    }
1631}
1632
1633#[stable(feature = "rust1", since = "1.0.0")]
1634impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {
1635    fn is_empty(&self) -> bool {
1636        self.iter.is_empty()
1637    }
1638}
1639
1640#[stable(feature = "fused", since = "1.26.0")]
1641impl<T, A: Allocator> FusedIterator for IntoIter<T, A> {}
1642
1643#[doc(hidden)]
1644#[unstable(issue = "none", feature = "trusted_fused")]
1645unsafe impl<T, A: Allocator> TrustedFused for IntoIter<T, A> {}
1646
1647#[stable(feature = "default_iters", since = "1.70.0")]
1648impl<T> Default for IntoIter<T> {
1649    /// Creates an empty `binary_heap::IntoIter`.
1650    ///
1651    /// ```
1652    /// # use std::collections::binary_heap;
1653    /// let iter: binary_heap::IntoIter<u8> = Default::default();
1654    /// assert_eq!(iter.len(), 0);
1655    /// ```
1656    fn default() -> Self {
1657        IntoIter { iter: Default::default() }
1658    }
1659}
1660
1661// In addition to the SAFETY invariants of the following three unsafe traits
1662// also refer to the vec::in_place_collect module documentation to get an overview
1663#[unstable(issue = "none", feature = "inplace_iteration")]
1664#[doc(hidden)]
1665unsafe impl<T, A: Allocator> SourceIter for IntoIter<T, A> {
1666    type Source = IntoIter<T, A>;
1667
1668    #[inline]
1669    unsafe fn as_inner(&mut self) -> &mut Self::Source {
1670        self
1671    }
1672}
1673
1674#[unstable(issue = "none", feature = "inplace_iteration")]
1675#[doc(hidden)]
1676unsafe impl<I, A: Allocator> InPlaceIterable for IntoIter<I, A> {
1677    const EXPAND_BY: Option<NonZero<usize>> = NonZero::new(1);
1678    const MERGE_BY: Option<NonZero<usize>> = NonZero::new(1);
1679}
1680
1681#[cfg(not(test))]
1682unsafe impl<I> AsVecIntoIter for IntoIter<I> {
1683    type Item = I;
1684
1685    fn as_into_iter(&mut self) -> &mut vec::IntoIter<Self::Item> {
1686        &mut self.iter
1687    }
1688}
1689
1690#[must_use = "iterators are lazy and do nothing unless consumed"]
1691#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1692#[derive(Clone, Debug)]
1693pub struct IntoIterSorted<
1694    T,
1695    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1696> {
1697    inner: BinaryHeap<T, A>,
1698}
1699
1700impl<T, A: Allocator> IntoIterSorted<T, A> {
1701    /// Returns a reference to the underlying allocator.
1702    #[unstable(feature = "allocator_api", issue = "32838")]
1703    pub fn allocator(&self) -> &A {
1704        self.inner.allocator()
1705    }
1706}
1707
1708#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1709impl<T: Ord, A: Allocator> Iterator for IntoIterSorted<T, A> {
1710    type Item = T;
1711
1712    #[inline]
1713    fn next(&mut self) -> Option<T> {
1714        self.inner.pop()
1715    }
1716
1717    #[inline]
1718    fn size_hint(&self) -> (usize, Option<usize>) {
1719        let exact = self.inner.len();
1720        (exact, Some(exact))
1721    }
1722}
1723
1724#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1725impl<T: Ord, A: Allocator> ExactSizeIterator for IntoIterSorted<T, A> {}
1726
1727#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1728impl<T: Ord, A: Allocator> FusedIterator for IntoIterSorted<T, A> {}
1729
1730#[unstable(feature = "trusted_len", issue = "37572")]
1731unsafe impl<T: Ord, A: Allocator> TrustedLen for IntoIterSorted<T, A> {}
1732
1733/// A draining iterator over the elements of a `BinaryHeap`.
1734///
1735/// This `struct` is created by [`BinaryHeap::drain()`]. See its
1736/// documentation for more.
1737///
1738/// [`drain`]: BinaryHeap::drain
1739#[stable(feature = "drain", since = "1.6.0")]
1740#[derive(Debug)]
1741pub struct Drain<
1742    'a,
1743    T: 'a,
1744    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1745> {
1746    iter: vec::Drain<'a, T, A>,
1747}
1748
1749impl<T, A: Allocator> Drain<'_, T, A> {
1750    /// Returns a reference to the underlying allocator.
1751    #[unstable(feature = "allocator_api", issue = "32838")]
1752    pub fn allocator(&self) -> &A {
1753        self.iter.allocator()
1754    }
1755}
1756
1757#[stable(feature = "drain", since = "1.6.0")]
1758impl<T, A: Allocator> Iterator for Drain<'_, T, A> {
1759    type Item = T;
1760
1761    #[inline]
1762    fn next(&mut self) -> Option<T> {
1763        self.iter.next()
1764    }
1765
1766    #[inline]
1767    fn size_hint(&self) -> (usize, Option<usize>) {
1768        self.iter.size_hint()
1769    }
1770}
1771
1772#[stable(feature = "drain", since = "1.6.0")]
1773impl<T, A: Allocator> DoubleEndedIterator for Drain<'_, T, A> {
1774    #[inline]
1775    fn next_back(&mut self) -> Option<T> {
1776        self.iter.next_back()
1777    }
1778}
1779
1780#[stable(feature = "drain", since = "1.6.0")]
1781impl<T, A: Allocator> ExactSizeIterator for Drain<'_, T, A> {
1782    fn is_empty(&self) -> bool {
1783        self.iter.is_empty()
1784    }
1785}
1786
1787#[stable(feature = "fused", since = "1.26.0")]
1788impl<T, A: Allocator> FusedIterator for Drain<'_, T, A> {}
1789
1790/// A draining iterator over the elements of a `BinaryHeap`.
1791///
1792/// This `struct` is created by [`BinaryHeap::drain_sorted()`]. See its
1793/// documentation for more.
1794///
1795/// [`drain_sorted`]: BinaryHeap::drain_sorted
1796#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1797#[derive(Debug)]
1798pub struct DrainSorted<
1799    'a,
1800    T: Ord,
1801    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1802> {
1803    inner: &'a mut BinaryHeap<T, A>,
1804}
1805
1806impl<'a, T: Ord, A: Allocator> DrainSorted<'a, T, A> {
1807    /// Returns a reference to the underlying allocator.
1808    #[unstable(feature = "allocator_api", issue = "32838")]
1809    pub fn allocator(&self) -> &A {
1810        self.inner.allocator()
1811    }
1812}
1813
1814#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1815impl<'a, T: Ord, A: Allocator> Drop for DrainSorted<'a, T, A> {
1816    /// Removes heap elements in heap order.
1817    fn drop(&mut self) {
1818        struct DropGuard<'r, 'a, T: Ord, A: Allocator>(&'r mut DrainSorted<'a, T, A>);
1819
1820        impl<'r, 'a, T: Ord, A: Allocator> Drop for DropGuard<'r, 'a, T, A> {
1821            fn drop(&mut self) {
1822                while self.0.inner.pop().is_some() {}
1823            }
1824        }
1825
1826        while let Some(item) = self.inner.pop() {
1827            let guard = DropGuard(self);
1828            drop(item);
1829            mem::forget(guard);
1830        }
1831    }
1832}
1833
1834#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1835impl<T: Ord, A: Allocator> Iterator for DrainSorted<'_, T, A> {
1836    type Item = T;
1837
1838    #[inline]
1839    fn next(&mut self) -> Option<T> {
1840        self.inner.pop()
1841    }
1842
1843    #[inline]
1844    fn size_hint(&self) -> (usize, Option<usize>) {
1845        let exact = self.inner.len();
1846        (exact, Some(exact))
1847    }
1848}
1849
1850#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1851impl<T: Ord, A: Allocator> ExactSizeIterator for DrainSorted<'_, T, A> {}
1852
1853#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1854impl<T: Ord, A: Allocator> FusedIterator for DrainSorted<'_, T, A> {}
1855
1856#[unstable(feature = "trusted_len", issue = "37572")]
1857unsafe impl<T: Ord, A: Allocator> TrustedLen for DrainSorted<'_, T, A> {}
1858
1859#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1860impl<T: Ord, A: Allocator> From<Vec<T, A>> for BinaryHeap<T, A> {
1861    /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1862    ///
1863    /// This conversion happens in-place, and has *O*(*n*) time complexity.
1864    fn from(vec: Vec<T, A>) -> BinaryHeap<T, A> {
1865        let mut heap = BinaryHeap { data: vec };
1866        heap.rebuild();
1867        heap
1868    }
1869}
1870
1871#[stable(feature = "std_collections_from_array", since = "1.56.0")]
1872impl<T: Ord, const N: usize> From<[T; N]> for BinaryHeap<T> {
1873    /// ```
1874    /// use std::collections::BinaryHeap;
1875    ///
1876    /// let mut h1 = BinaryHeap::from([1, 4, 2, 3]);
1877    /// let mut h2: BinaryHeap<_> = [1, 4, 2, 3].into();
1878    /// while let Some((a, b)) = h1.pop().zip(h2.pop()) {
1879    ///     assert_eq!(a, b);
1880    /// }
1881    /// ```
1882    fn from(arr: [T; N]) -> Self {
1883        Self::from_iter(arr)
1884    }
1885}
1886
1887#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1888impl<T, A: Allocator> From<BinaryHeap<T, A>> for Vec<T, A> {
1889    /// Converts a `BinaryHeap<T>` into a `Vec<T>`.
1890    ///
1891    /// This conversion requires no data movement or allocation, and has
1892    /// constant time complexity.
1893    fn from(heap: BinaryHeap<T, A>) -> Vec<T, A> {
1894        heap.data
1895    }
1896}
1897
1898#[stable(feature = "rust1", since = "1.0.0")]
1899impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1900    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1901        BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1902    }
1903}
1904
1905#[stable(feature = "rust1", since = "1.0.0")]
1906impl<T, A: Allocator> IntoIterator for BinaryHeap<T, A> {
1907    type Item = T;
1908    type IntoIter = IntoIter<T, A>;
1909
1910    /// Creates a consuming iterator, that is, one that moves each value out of
1911    /// the binary heap in arbitrary order. The binary heap cannot be used
1912    /// after calling this.
1913    ///
1914    /// # Examples
1915    ///
1916    /// Basic usage:
1917    ///
1918    /// ```
1919    /// use std::collections::BinaryHeap;
1920    /// let heap = BinaryHeap::from([1, 2, 3, 4]);
1921    ///
1922    /// // Print 1, 2, 3, 4 in arbitrary order
1923    /// for x in heap.into_iter() {
1924    ///     // x has type i32, not &i32
1925    ///     println!("{x}");
1926    /// }
1927    /// ```
1928    fn into_iter(self) -> IntoIter<T, A> {
1929        IntoIter { iter: self.data.into_iter() }
1930    }
1931}
1932
1933#[stable(feature = "rust1", since = "1.0.0")]
1934impl<'a, T, A: Allocator> IntoIterator for &'a BinaryHeap<T, A> {
1935    type Item = &'a T;
1936    type IntoIter = Iter<'a, T>;
1937
1938    fn into_iter(self) -> Iter<'a, T> {
1939        self.iter()
1940    }
1941}
1942
1943#[stable(feature = "rust1", since = "1.0.0")]
1944impl<T: Ord, A: Allocator> Extend<T> for BinaryHeap<T, A> {
1945    #[inline]
1946    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1947        let guard = RebuildOnDrop { rebuild_from: self.len(), heap: self };
1948        guard.heap.data.extend(iter);
1949    }
1950
1951    #[inline]
1952    fn extend_one(&mut self, item: T) {
1953        self.push(item);
1954    }
1955
1956    #[inline]
1957    fn extend_reserve(&mut self, additional: usize) {
1958        self.reserve(additional);
1959    }
1960}
1961
1962#[stable(feature = "extend_ref", since = "1.2.0")]
1963impl<'a, T: 'a + Ord + Copy, A: Allocator> Extend<&'a T> for BinaryHeap<T, A> {
1964    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1965        self.extend(iter.into_iter().cloned());
1966    }
1967
1968    #[inline]
1969    fn extend_one(&mut self, &item: &'a T) {
1970        self.push(item);
1971    }
1972
1973    #[inline]
1974    fn extend_reserve(&mut self, additional: usize) {
1975        self.reserve(additional);
1976    }
1977}