Skip to main content

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::{AllocatorNightly, 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_ext", issue = "163177", implied_by = "allocator_api")] 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_ext", issue = "163177", implied_by = "allocator_api")] 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        // SAFETY: 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            // SAFETY: len > 1 so len != 0.
350            self.original_len = Some(unsafe { NonZero::new_unchecked(len) });
351            // SAFETY: len > 1 so all this does for now is leak elements,
352            // which is safe.
353            unsafe { self.heap.data.set_len(1) };
354        }
355
356        // SAFETY: PeekMut is only instantiated for non-empty heaps
357        unsafe { self.heap.data.get_unchecked_mut(0) }
358    }
359}
360
361impl<'a, T: Ord, A: Allocator> PeekMut<'a, T, A> {
362    /// Sifts the current element to its new position.
363    ///
364    /// Afterwards refers to the new element. Returns if the element changed.
365    ///
366    /// ## Examples
367    ///
368    /// The condition can be used to upper bound all elements in the heap. When only few elements
369    /// are affected, the heap's sort ensures this is faster than a reconstruction from the raw
370    /// element list and requires no additional allocation.
371    ///
372    /// ```
373    /// #![feature(binary_heap_peek_mut_refresh)]
374    /// use std::collections::BinaryHeap;
375    ///
376    /// let mut heap: BinaryHeap<u32> = (0..128).collect();
377    /// let mut peek = heap.peek_mut().unwrap();
378    ///
379    /// loop {
380    ///     *peek = 99;
381    ///
382    ///     if !peek.refresh() {
383    ///         break;
384    ///     }
385    /// }
386    ///
387    /// // Post condition, this is now an upper bound.
388    /// assert!(*peek < 100);
389    /// ```
390    ///
391    /// When the element remains the maximum after modification, the peek remains unchanged:
392    ///
393    /// ```
394    /// #![feature(binary_heap_peek_mut_refresh)]
395    /// use std::collections::BinaryHeap;
396    ///
397    /// let mut heap: BinaryHeap<u32> = [1, 2, 3].into();
398    /// let mut peek = heap.peek_mut().unwrap();
399    ///
400    /// assert_eq!(*peek, 3);
401    /// *peek = 42;
402    ///
403    /// // When we refresh, the peek is updated to the new maximum.
404    /// assert!(!peek.refresh(), "42 is even larger than 3");
405    /// assert_eq!(*peek, 42);
406    /// ```
407    #[unstable(feature = "binary_heap_peek_mut_refresh", issue = "138355")]
408    #[must_use = "is equivalent to dropping and getting a new PeekMut except for return information"]
409    pub fn refresh(&mut self) -> bool {
410        // The length of the underlying heap is unchanged by sifting down. The value stored for leak
411        // amplification thus remains accurate. We erase the leak amplification firstly because the
412        // operation is then equivalent to constructing a new PeekMut and secondly this avoids any
413        // future complication where original_len being non-empty would be interpreted as the heap
414        // having been leak amplified instead of checking the heap itself.
415        if let Some(original_len) = self.original_len.take() {
416            // SAFETY: This is how many elements were in the Vec at the time of
417            // the BinaryHeap::peek_mut call.
418            unsafe { self.heap.data.set_len(original_len.get()) };
419
420            // The length of the heap did not change by sifting, upholding our own invariants.
421
422            // SAFETY: PeekMut is only instantiated for non-empty heaps.
423            (unsafe { self.heap.sift_down(0) }) != 0
424        } else {
425            // The element was not modified.
426            false
427        }
428    }
429
430    /// Removes the peeked value from the heap and returns it.
431    #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
432    pub fn pop(mut this: PeekMut<'a, T, A>) -> T {
433        if let Some(original_len) = this.original_len.take() {
434            // SAFETY: This is how many elements were in the Vec at the time of
435            // the BinaryHeap::peek_mut call.
436            unsafe { this.heap.data.set_len(original_len.get()) };
437
438            // Unlike in Drop, here we don't also need to do a sift_down even if
439            // the caller could've mutated the element. It is removed from the
440            // heap on the next line and pop() is not sensitive to its value.
441        }
442
443        // SAFETY: Have a `PeekMut` element proves that the associated binary heap being non-empty,
444        // so the `pop` operation will not fail.
445        unsafe { this.heap.pop().unwrap_unchecked() }
446    }
447}
448
449#[stable(feature = "rust1", since = "1.0.0")]
450impl<T: Clone, A: Allocator + Clone> Clone for BinaryHeap<T, A> {
451    fn clone(&self) -> Self {
452        BinaryHeap { data: self.data.clone() }
453    }
454
455    /// Overwrites the contents of `self` with a clone of the contents of `source`.
456    ///
457    /// This method is preferred over simply assigning `source.clone()` to `self`,
458    /// as it avoids reallocation if possible.
459    ///
460    /// See [`Vec::clone_from()`] for more details.
461    fn clone_from(&mut self, source: &Self) {
462        self.data.clone_from(&source.data);
463    }
464}
465
466#[stable(feature = "rust1", since = "1.0.0")]
467impl<T> Default for BinaryHeap<T> {
468    /// Creates an empty `BinaryHeap<T>`.
469    #[inline]
470    fn default() -> BinaryHeap<T> {
471        BinaryHeap::new()
472    }
473}
474
475#[stable(feature = "binaryheap_debug", since = "1.4.0")]
476impl<T: fmt::Debug, A: Allocator> fmt::Debug for BinaryHeap<T, A> {
477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478        f.debug_list().entries(self.iter()).finish()
479    }
480}
481
482struct RebuildOnDrop<
483    'a,
484    T: Ord,
485    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
486> {
487    heap: &'a mut BinaryHeap<T, A>,
488    rebuild_from: usize,
489}
490
491impl<T: Ord, A: Allocator> Drop for RebuildOnDrop<'_, T, A> {
492    fn drop(&mut self) {
493        self.heap.rebuild_tail(self.rebuild_from);
494    }
495}
496
497impl<T> BinaryHeap<T> {
498    /// Creates an empty `BinaryHeap` as a max-heap.
499    ///
500    /// # Examples
501    ///
502    /// Basic usage:
503    ///
504    /// ```
505    /// use std::collections::BinaryHeap;
506    /// let mut heap = BinaryHeap::new();
507    /// heap.push(4);
508    /// ```
509    #[stable(feature = "rust1", since = "1.0.0")]
510    #[rustc_const_stable(feature = "const_binary_heap_constructor", since = "1.80.0")]
511    #[must_use]
512    pub const fn new() -> BinaryHeap<T> {
513        BinaryHeap { data: vec![] }
514    }
515
516    /// Creates an empty `BinaryHeap` with at least the specified capacity.
517    ///
518    /// The binary heap will be able to hold at least `capacity` elements without
519    /// reallocating. This method is allowed to allocate for more elements than
520    /// `capacity`. If `capacity` is zero, the binary heap will not allocate.
521    ///
522    /// # Examples
523    ///
524    /// Basic usage:
525    ///
526    /// ```
527    /// use std::collections::BinaryHeap;
528    /// let mut heap = BinaryHeap::with_capacity(10);
529    /// heap.push(4);
530    /// ```
531    #[stable(feature = "rust1", since = "1.0.0")]
532    #[must_use]
533    pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
534        BinaryHeap { data: Vec::with_capacity(capacity) }
535    }
536}
537
538impl<T, A: Allocator> BinaryHeap<T, A> {
539    /// Creates an empty `BinaryHeap` as a max-heap, using `A` as allocator.
540    ///
541    /// # Examples
542    ///
543    /// Basic usage:
544    ///
545    /// ```
546    /// #![feature(allocator_ext)]
547    ///
548    /// use std::alloc::System;
549    /// use std::collections::BinaryHeap;
550    ///
551    /// let heap : BinaryHeap<i32, System> = BinaryHeap::new_in(System);
552    /// ```
553    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
554    #[rustc_const_unstable(feature = "allocator_ext", issue = "163177")]
555    #[must_use]
556    pub const fn new_in(alloc: A) -> BinaryHeap<T, A> {
557        BinaryHeap { data: Vec::new_in(alloc) }
558    }
559
560    /// Creates an empty `BinaryHeap` with at least the specified capacity, using `A` as allocator.
561    ///
562    /// The binary heap will be able to hold at least `capacity` elements without
563    /// reallocating. This method is allowed to allocate for more elements than
564    /// `capacity`. If `capacity` is zero, the binary heap will not allocate.
565    ///
566    /// # Examples
567    ///
568    /// Basic usage:
569    ///
570    /// ```
571    /// #![feature(allocator_ext)]
572    ///
573    /// use std::alloc::System;
574    /// use std::collections::BinaryHeap;
575    ///
576    /// let heap: BinaryHeap<i32, System> = BinaryHeap::with_capacity_in(10, System);
577    /// ```
578    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
579    #[must_use]
580    pub fn with_capacity_in(capacity: usize, alloc: A) -> BinaryHeap<T, A> {
581        BinaryHeap { data: Vec::with_capacity_in(capacity, alloc) }
582    }
583
584    /// Creates a `BinaryHeap` using the supplied `vec`. This does not rebuild the heap,
585    /// so `vec` must already be a max-heap.
586    ///
587    /// # Safety
588    ///
589    /// The supplied `vec` must be a max-heap, i.e. for all indices `0 < i < vec.len()`,
590    /// `vec[(i - 1) / 2] >= vec[i]`.
591    ///
592    /// # Examples
593    ///
594    /// Basic usage:
595    ///
596    /// ```
597    /// #![feature(binary_heap_from_raw_vec)]
598    ///
599    /// use std::collections::BinaryHeap;
600    /// let heap = BinaryHeap::from([1, 2, 3]);
601    /// let vec = heap.into_vec();
602    ///
603    /// // Safety: vec is the output of heap.from_vec(), so is a max-heap.
604    /// let mut new_heap = unsafe {
605    ///     BinaryHeap::from_raw_vec(vec)
606    /// };
607    /// assert_eq!(new_heap.pop(), Some(3));
608    /// assert_eq!(new_heap.pop(), Some(2));
609    /// assert_eq!(new_heap.pop(), Some(1));
610    /// assert_eq!(new_heap.pop(), None);
611    /// ```
612    #[unstable(feature = "binary_heap_from_raw_vec", issue = "152500")]
613    #[must_use]
614    pub unsafe fn from_raw_vec(vec: Vec<T, A>) -> BinaryHeap<T, A> {
615        BinaryHeap { data: vec }
616    }
617}
618
619impl<T: Ord, A: Allocator> BinaryHeap<T, A> {
620    /// Returns a mutable reference to the greatest item in the binary heap, or
621    /// `None` if it is empty.
622    ///
623    /// Note: If the `PeekMut` value is leaked, some heap elements might get
624    /// leaked along with it, but the remaining elements will remain a valid
625    /// heap.
626    ///
627    /// # Examples
628    ///
629    /// Basic usage:
630    ///
631    /// ```
632    /// use std::collections::BinaryHeap;
633    /// let mut heap = BinaryHeap::new();
634    /// assert!(heap.peek_mut().is_none());
635    ///
636    /// heap.push(1);
637    /// heap.push(5);
638    /// heap.push(2);
639    /// if let Some(mut val) = heap.peek_mut() {
640    ///     *val = 0;
641    /// }
642    /// assert_eq!(heap.peek(), Some(&2));
643    /// ```
644    ///
645    /// # Time complexity
646    ///
647    /// If the item is modified then the worst case time complexity is *O*(log(*n*)),
648    /// otherwise it's *O*(1).
649    #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
650    pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, A>> {
651        if self.is_empty() { None } else { Some(PeekMut { heap: self, original_len: None }) }
652    }
653
654    /// Removes the greatest item from the binary heap and returns it, or `None` if it
655    /// is empty.
656    ///
657    /// # Examples
658    ///
659    /// Basic usage:
660    ///
661    /// ```
662    /// use std::collections::BinaryHeap;
663    /// let mut heap = BinaryHeap::from([1, 3]);
664    ///
665    /// assert_eq!(heap.pop(), Some(3));
666    /// assert_eq!(heap.pop(), Some(1));
667    /// assert_eq!(heap.pop(), None);
668    /// ```
669    ///
670    /// # Time complexity
671    ///
672    /// The worst case cost of `pop` on a heap containing *n* elements is *O*(log(*n*)).
673    #[stable(feature = "rust1", since = "1.0.0")]
674    pub fn pop(&mut self) -> Option<T> {
675        self.data.pop().map(|mut item| {
676            if !self.is_empty() {
677                swap(&mut item, &mut self.data[0]);
678                // SAFETY: !self.is_empty() means that self.len() > 0
679                unsafe { self.sift_down_to_bottom(0) };
680            }
681            item
682        })
683    }
684
685    /// Removes and returns the greatest item from the binary heap if the predicate
686    /// returns `true`, or [`None`] if the predicate returns false or the heap
687    /// is empty (the predicate will not be called in that case).
688    ///
689    /// # Examples
690    ///
691    /// ```
692    /// #![feature(binary_heap_pop_if)]
693    /// use std::collections::BinaryHeap;
694    /// let mut heap = BinaryHeap::from([1, 2]);
695    /// let pred = |x: &i32| *x % 2 == 0;
696    ///
697    /// assert_eq!(heap.pop_if(pred), Some(2));
698    /// assert_eq!(heap.as_slice(), [1]);
699    /// assert_eq!(heap.pop_if(pred), None);
700    /// assert_eq!(heap.as_slice(), [1]);
701    /// ```
702    ///
703    /// # Time complexity
704    ///
705    /// The worst case cost of `pop_if` on a heap containing *n* elements is *O*(log(*n*)).
706    #[unstable(feature = "binary_heap_pop_if", issue = "151828")]
707    pub fn pop_if(&mut self, predicate: impl FnOnce(&T) -> bool) -> Option<T> {
708        let first = self.peek()?;
709        if predicate(first) { self.pop() } else { None }
710    }
711
712    /// Pushes an item onto the binary heap.
713    ///
714    /// # Examples
715    ///
716    /// Basic usage:
717    ///
718    /// ```
719    /// use std::collections::BinaryHeap;
720    /// let mut heap = BinaryHeap::new();
721    /// heap.push(3);
722    /// heap.push(5);
723    /// heap.push(1);
724    ///
725    /// assert_eq!(heap.len(), 3);
726    /// assert_eq!(heap.peek(), Some(&5));
727    /// ```
728    ///
729    /// # Time complexity
730    ///
731    /// The expected cost of `push`, averaged over every possible ordering of
732    /// the elements being pushed, and over a sufficiently large number of
733    /// pushes, is *O*(1). This is the most meaningful cost metric when pushing
734    /// elements that are *not* already in any sorted pattern.
735    ///
736    /// The time complexity degrades if elements are pushed in predominantly
737    /// ascending order. In the worst case, elements are pushed in ascending
738    /// sorted order and the amortized cost per push is *O*(log(*n*)) against a heap
739    /// containing *n* elements.
740    ///
741    /// The worst case cost of a *single* call to `push` is *O*(*n*). The worst case
742    /// occurs when capacity is exhausted and needs a resize. The resize cost
743    /// has been amortized in the previous figures.
744    #[stable(feature = "rust1", since = "1.0.0")]
745    #[rustc_confusables("append", "put")]
746    pub fn push(&mut self, item: T) {
747        let old_len = self.len();
748        self.data.push(item);
749        // SAFETY: Since we pushed a new item it means that
750        //  old_len = self.len() - 1 < self.len()
751        unsafe { self.sift_up(0, old_len) };
752    }
753
754    /// Consumes the `BinaryHeap` and returns a vector in sorted
755    /// (ascending) order.
756    ///
757    /// # Examples
758    ///
759    /// Basic usage:
760    ///
761    /// ```
762    /// use std::collections::BinaryHeap;
763    ///
764    /// let mut heap = BinaryHeap::from([1, 2, 4, 5, 7]);
765    /// heap.push(6);
766    /// heap.push(3);
767    ///
768    /// let vec = heap.into_sorted_vec();
769    /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
770    /// ```
771    #[must_use = "`self` will be dropped if the result is not used"]
772    #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
773    pub fn into_sorted_vec(mut self) -> Vec<T, A> {
774        let mut end = self.len();
775        while end > 1 {
776            end -= 1;
777            // SAFETY: `end` goes from `self.len() - 1` to 1 (both included),
778            //  so it's always a valid index to access.
779            //  It is safe to access index 0 (i.e. `ptr`), because
780            //  1 <= end < self.len(), which means self.len() >= 2.
781            unsafe {
782                let ptr = self.data.as_mut_ptr();
783                ptr::swap(ptr, ptr.add(end));
784            }
785            // SAFETY: `end` goes from `self.len() - 1` to 1 (both included) so:
786            //  0 < 1 <= end <= self.len() - 1 < self.len()
787            //  Which means 0 < end and end < self.len().
788            unsafe { self.sift_down_range(0, end) };
789        }
790        self.into_vec()
791    }
792
793    // The implementations of sift_up and sift_down use unsafe blocks in
794    // order to move an element out of the vector (leaving behind a
795    // hole), shift along the others and move the removed element back into the
796    // vector at the final location of the hole.
797    // The `Hole` type is used to represent this, and make sure
798    // the hole is filled back at the end of its scope, even on panic.
799    // Using a hole reduces the constant factor compared to using swaps,
800    // which involves twice as many moves.
801
802    /// # Safety
803    ///
804    /// The caller must guarantee that `pos < self.len()`.
805    ///
806    /// Returns the new position of the element.
807    unsafe fn sift_up(&mut self, start: usize, pos: usize) -> usize {
808        // Take out the value at `pos` and create a hole.
809        // SAFETY: The caller guarantees that pos < self.len()
810        let mut hole = unsafe { Hole::new(&mut self.data, pos) };
811
812        while hole.pos() > start {
813            let parent = (hole.pos() - 1) / 2;
814
815            // SAFETY: hole.pos() > start >= 0, which means hole.pos() > 0
816            //  and so hole.pos() - 1 can't underflow.
817            //  This guarantees that parent < hole.pos() so
818            //  it's a valid index and also != hole.pos().
819            if hole.element() <= unsafe { hole.get(parent) } {
820                break;
821            }
822
823            // SAFETY: Same as above
824            unsafe { hole.move_to(parent) };
825        }
826
827        hole.pos()
828    }
829
830    /// Take an element at `pos` and move it down the heap,
831    /// while its children are larger.
832    ///
833    /// Returns the new position of the element.
834    ///
835    /// # Safety
836    ///
837    /// The caller must guarantee that `pos < end <= self.len()`.
838    unsafe fn sift_down_range(&mut self, pos: usize, end: usize) -> usize {
839        // SAFETY: The caller guarantees that pos < end <= self.len().
840        let mut hole = unsafe { Hole::new(&mut self.data, pos) };
841        let mut child = 2 * hole.pos() + 1;
842
843        // Loop invariant: child == 2 * hole.pos() + 1.
844        while child <= end.saturating_sub(2) {
845            // compare with the greater of the two children
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            // if we are already in order, stop.
855            // SAFETY: child is now either the old child or the old child+1
856            //  We already proven that both are < self.len() and != hole.pos()
857            if hole.element() >= unsafe { hole.get(child) } {
858                return hole.pos();
859            }
860
861            // SAFETY: same as above.
862            unsafe { hole.move_to(child) };
863            child = 2 * hole.pos() + 1;
864        }
865
866        // SAFETY: && short circuit, which means that in the
867        //  second condition it's already true that child == end - 1 < self.len().
868        if child == end - 1 && hole.element() < unsafe { hole.get(child) } {
869            // SAFETY: child is already proven to be a valid index and
870            //  child == 2 * hole.pos() + 1 != hole.pos().
871            unsafe { hole.move_to(child) };
872        }
873
874        hole.pos()
875    }
876
877    /// # Safety
878    ///
879    /// The caller must guarantee that `pos < self.len()`.
880    unsafe fn sift_down(&mut self, pos: usize) -> usize {
881        let len = self.len();
882        // SAFETY: pos < len is guaranteed by the caller and
883        //  obviously len = self.len() <= self.len().
884        unsafe { self.sift_down_range(pos, len) }
885    }
886
887    /// Take an element at `pos` and move it all the way down the heap,
888    /// then sift it up to its position.
889    ///
890    /// Note: This is faster when the element is known to be large / should
891    /// be closer to the bottom.
892    ///
893    /// # Safety
894    ///
895    /// The caller must guarantee that `pos < self.len()`.
896    unsafe fn sift_down_to_bottom(&mut self, mut pos: usize) {
897        let end = self.len();
898        let start = pos;
899
900        // SAFETY: The caller guarantees that pos < self.len().
901        let mut hole = unsafe { Hole::new(&mut self.data, pos) };
902        let mut child = 2 * hole.pos() + 1;
903
904        // Loop invariant: child == 2 * hole.pos() + 1.
905        while child <= end.saturating_sub(2) {
906            // SAFETY: child < end - 1 < self.len() and
907            //  child + 1 < end <= self.len(), so they're valid indexes.
908            //  child == 2 * hole.pos() + 1 != hole.pos() and
909            //  child + 1 == 2 * hole.pos() + 2 != hole.pos().
910            // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
911            //  if T is a ZST
912            child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
913
914            // SAFETY: Same as above
915            unsafe { hole.move_to(child) };
916            child = 2 * hole.pos() + 1;
917        }
918
919        if child == end - 1 {
920            // SAFETY: child == end - 1 < self.len(), so it's a valid index
921            //  and child == 2 * hole.pos() + 1 != hole.pos().
922            unsafe { hole.move_to(child) };
923        }
924        pos = hole.pos();
925        drop(hole);
926
927        // SAFETY: pos is the position in the hole and was already proven
928        //  to be a valid index.
929        unsafe { self.sift_up(start, pos) };
930    }
931
932    /// Rebuild assuming data[0..start] is still a proper heap.
933    fn rebuild_tail(&mut self, start: usize) {
934        if start == self.len() {
935            return;
936        }
937
938        let tail_len = self.len() - start;
939
940        #[inline(always)]
941        fn log2_fast(x: usize) -> usize {
942            (usize::BITS - x.leading_zeros() - 1) as usize
943        }
944
945        // `rebuild` takes O(self.len()) operations
946        // and about 2 * self.len() comparisons in the worst case
947        // while repeating `sift_up` takes O(tail_len * log(start)) operations
948        // and about 1 * tail_len * log_2(start) comparisons in the worst case,
949        // assuming start >= tail_len. For larger heaps, the crossover point
950        // no longer follows this reasoning and was determined empirically.
951        let better_to_rebuild = if start < tail_len {
952            true
953        } else if self.len() <= 2048 {
954            2 * self.len() < tail_len * log2_fast(start)
955        } else {
956            2 * self.len() < tail_len * 11
957        };
958
959        if better_to_rebuild {
960            self.rebuild();
961        } else {
962            for i in start..self.len() {
963                // SAFETY: The index `i` is always less than self.len().
964                unsafe { self.sift_up(0, i) };
965            }
966        }
967    }
968
969    fn rebuild(&mut self) {
970        let mut n = self.len() / 2;
971        while n > 0 {
972            n -= 1;
973            // SAFETY: n starts from self.len() / 2 and goes down to 0.
974            //  The only case when !(n < self.len()) is if
975            //  self.len() == 0, but it's ruled out by the loop condition.
976            unsafe { self.sift_down(n) };
977        }
978    }
979
980    /// Moves all the elements of `other` into `self`, leaving `other` empty.
981    ///
982    /// # Examples
983    ///
984    /// Basic usage:
985    ///
986    /// ```
987    /// use std::collections::BinaryHeap;
988    ///
989    /// let mut a = BinaryHeap::from([-10, 1, 2, 3, 3]);
990    /// let mut b = BinaryHeap::from([-20, 5, 43]);
991    ///
992    /// a.append(&mut b);
993    ///
994    /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
995    /// assert!(b.is_empty());
996    /// ```
997    #[stable(feature = "binary_heap_append", since = "1.11.0")]
998    pub fn append(&mut self, other: &mut Self) {
999        if self.len() < other.len() {
1000            swap(self, other);
1001        }
1002
1003        let start = self.data.len();
1004
1005        self.data.append(&mut other.data);
1006
1007        self.rebuild_tail(start);
1008    }
1009
1010    /// Clears the binary heap, returning an iterator over the removed elements
1011    /// in heap order. If the iterator is dropped before being fully consumed,
1012    /// it drops the remaining elements in heap order.
1013    ///
1014    /// The returned iterator keeps a mutable borrow on the heap to optimize
1015    /// its implementation.
1016    ///
1017    /// Note:
1018    /// * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`.
1019    ///   You should use the latter for most cases.
1020    ///
1021    /// # Examples
1022    ///
1023    /// Basic usage:
1024    ///
1025    /// ```
1026    /// #![feature(binary_heap_drain_sorted)]
1027    /// use std::collections::BinaryHeap;
1028    ///
1029    /// let mut heap = BinaryHeap::from([1, 2, 3, 4, 5]);
1030    /// assert_eq!(heap.len(), 5);
1031    ///
1032    /// drop(heap.drain_sorted()); // removes all elements in heap order
1033    /// assert_eq!(heap.len(), 0);
1034    /// ```
1035    #[inline]
1036    #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1037    pub fn drain_sorted(&mut self) -> DrainSorted<'_, T, A> {
1038        DrainSorted { inner: self }
1039    }
1040
1041    /// Retains only the elements specified by the predicate.
1042    ///
1043    /// In other words, remove all elements `e` for which `f(&e)` returns
1044    /// `false`. The elements are visited in unsorted (and unspecified) order.
1045    ///
1046    /// # Examples
1047    ///
1048    /// Basic usage:
1049    ///
1050    /// ```
1051    /// use std::collections::BinaryHeap;
1052    ///
1053    /// let mut heap = BinaryHeap::from([-10, -5, 1, 2, 4, 13]);
1054    ///
1055    /// heap.retain(|x| x % 2 == 0); // only keep even numbers
1056    ///
1057    /// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
1058    /// ```
1059    #[stable(feature = "binary_heap_retain", since = "1.70.0")]
1060    pub fn retain<F>(&mut self, mut f: F)
1061    where
1062        F: FnMut(&T) -> bool,
1063    {
1064        // rebuild_start will be updated to the first touched element below, and the rebuild will
1065        // only be done for the tail.
1066        let mut guard = RebuildOnDrop { rebuild_from: self.len(), heap: self };
1067        let mut i = 0;
1068
1069        guard.heap.data.retain(|e| {
1070            let keep = f(e);
1071            if !keep && i < guard.rebuild_from {
1072                guard.rebuild_from = i;
1073            }
1074            i += 1;
1075            keep
1076        });
1077    }
1078}
1079
1080impl<T, A: Allocator> BinaryHeap<T, A> {
1081    /// Returns an iterator visiting all values in the underlying vector, in
1082    /// arbitrary order.
1083    ///
1084    /// # Examples
1085    ///
1086    /// Basic usage:
1087    ///
1088    /// ```
1089    /// use std::collections::BinaryHeap;
1090    /// let heap = BinaryHeap::from([1, 2, 3, 4]);
1091    ///
1092    /// // Print 1, 2, 3, 4 in arbitrary order
1093    /// for x in heap.iter() {
1094    ///     println!("{x}");
1095    /// }
1096    /// ```
1097    #[stable(feature = "rust1", since = "1.0.0")]
1098    #[cfg_attr(not(test), rustc_diagnostic_item = "binaryheap_iter")]
1099    pub fn iter(&self) -> Iter<'_, T> {
1100        Iter { iter: self.data.iter() }
1101    }
1102
1103    /// Returns an iterator which retrieves elements in heap order.
1104    ///
1105    /// This method consumes the original heap.
1106    ///
1107    /// # Examples
1108    ///
1109    /// Basic usage:
1110    ///
1111    /// ```
1112    /// #![feature(binary_heap_into_iter_sorted)]
1113    /// use std::collections::BinaryHeap;
1114    /// let heap = BinaryHeap::from([1, 2, 3, 4, 5]);
1115    ///
1116    /// assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), [5, 4]);
1117    /// ```
1118    #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1119    pub fn into_iter_sorted(self) -> IntoIterSorted<T, A> {
1120        IntoIterSorted { inner: self }
1121    }
1122
1123    /// Returns the greatest item in the binary heap, or `None` if it is empty.
1124    ///
1125    /// # Examples
1126    ///
1127    /// Basic usage:
1128    ///
1129    /// ```
1130    /// use std::collections::BinaryHeap;
1131    /// let mut heap = BinaryHeap::new();
1132    /// assert_eq!(heap.peek(), None);
1133    ///
1134    /// heap.push(1);
1135    /// heap.push(5);
1136    /// heap.push(2);
1137    /// assert_eq!(heap.peek(), Some(&5));
1138    ///
1139    /// ```
1140    ///
1141    /// # Time complexity
1142    ///
1143    /// Cost is *O*(1) in the worst case.
1144    #[must_use]
1145    #[stable(feature = "rust1", since = "1.0.0")]
1146    pub fn peek(&self) -> Option<&T> {
1147        self.data.get(0)
1148    }
1149
1150    /// Returns the number of elements the binary heap can hold without reallocating.
1151    ///
1152    /// # Examples
1153    ///
1154    /// Basic usage:
1155    ///
1156    /// ```
1157    /// use std::collections::BinaryHeap;
1158    /// let mut heap = BinaryHeap::with_capacity(100);
1159    /// assert!(heap.capacity() >= 100);
1160    /// heap.push(4);
1161    /// ```
1162    #[must_use]
1163    #[stable(feature = "rust1", since = "1.0.0")]
1164    pub fn capacity(&self) -> usize {
1165        self.data.capacity()
1166    }
1167
1168    /// Reserves the minimum capacity for at least `additional` elements more than
1169    /// the current length. Unlike [`reserve`], this will not
1170    /// deliberately over-allocate to speculatively avoid frequent allocations.
1171    /// After calling `reserve_exact`, capacity will be greater than or equal to
1172    /// `self.len() + additional`. Does nothing if the capacity is already
1173    /// sufficient.
1174    ///
1175    /// [`reserve`]: BinaryHeap::reserve
1176    ///
1177    /// # Panics
1178    ///
1179    /// Panics if the new capacity overflows [`usize`].
1180    ///
1181    /// # Examples
1182    ///
1183    /// Basic usage:
1184    ///
1185    /// ```
1186    /// use std::collections::BinaryHeap;
1187    /// let mut heap = BinaryHeap::new();
1188    /// heap.reserve_exact(100);
1189    /// assert!(heap.capacity() >= 100);
1190    /// heap.push(4);
1191    /// ```
1192    ///
1193    /// [`reserve`]: BinaryHeap::reserve
1194    #[stable(feature = "rust1", since = "1.0.0")]
1195    pub fn reserve_exact(&mut self, additional: usize) {
1196        self.data.reserve_exact(additional);
1197    }
1198
1199    /// Reserves capacity for at least `additional` elements more than the
1200    /// current length. The allocator may reserve more space to speculatively
1201    /// avoid frequent allocations. After calling `reserve`,
1202    /// capacity will be greater than or equal to `self.len() + additional`.
1203    /// Does nothing if capacity is already sufficient.
1204    ///
1205    /// # Panics
1206    ///
1207    /// Panics if the new capacity overflows [`usize`].
1208    ///
1209    /// # Examples
1210    ///
1211    /// Basic usage:
1212    ///
1213    /// ```
1214    /// use std::collections::BinaryHeap;
1215    /// let mut heap = BinaryHeap::new();
1216    /// heap.reserve(100);
1217    /// assert!(heap.capacity() >= 100);
1218    /// heap.push(4);
1219    /// ```
1220    #[stable(feature = "rust1", since = "1.0.0")]
1221    pub fn reserve(&mut self, additional: usize) {
1222        self.data.reserve(additional);
1223    }
1224
1225    /// Tries to reserve the minimum capacity for at least `additional` elements
1226    /// more than the current length. Unlike [`try_reserve`], this will not
1227    /// deliberately over-allocate to speculatively avoid frequent allocations.
1228    /// After calling `try_reserve_exact`, capacity will be greater than or
1229    /// equal to `self.len() + additional` if it returns `Ok(())`.
1230    /// Does nothing if the capacity is already sufficient.
1231    ///
1232    /// Note that the allocator may give the collection more space than it
1233    /// requests. Therefore, capacity can not be relied upon to be precisely
1234    /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1235    ///
1236    /// [`try_reserve`]: BinaryHeap::try_reserve
1237    ///
1238    /// # Errors
1239    ///
1240    /// If the capacity overflows, or the allocator reports a failure, then an error
1241    /// is returned.
1242    ///
1243    /// # Examples
1244    ///
1245    /// ```
1246    /// use std::collections::BinaryHeap;
1247    /// use std::collections::TryReserveError;
1248    ///
1249    /// fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
1250    ///     let mut heap = BinaryHeap::new();
1251    ///
1252    ///     // Pre-reserve the memory, exiting if we can't
1253    ///     heap.try_reserve_exact(data.len())?;
1254    ///
1255    ///     // Now we know this can't OOM in the middle of our complex work
1256    ///     heap.extend(data.iter());
1257    ///
1258    ///     Ok(heap.pop())
1259    /// }
1260    /// # find_max_slow(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1261    /// ```
1262    #[stable(feature = "try_reserve_2", since = "1.63.0")]
1263    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1264        self.data.try_reserve_exact(additional)
1265    }
1266
1267    /// Tries to reserve capacity for at least `additional` elements more than the
1268    /// current length. The allocator may reserve more space to speculatively
1269    /// avoid frequent allocations. After calling `try_reserve`, capacity will be
1270    /// greater than or equal to `self.len() + additional` if it returns
1271    /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1272    /// preserves the contents even if an error occurs.
1273    ///
1274    /// # Errors
1275    ///
1276    /// If the capacity overflows, or the allocator reports a failure, then an error
1277    /// is returned.
1278    ///
1279    /// # Examples
1280    ///
1281    /// ```
1282    /// use std::collections::BinaryHeap;
1283    /// use std::collections::TryReserveError;
1284    ///
1285    /// fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
1286    ///     let mut heap = BinaryHeap::new();
1287    ///
1288    ///     // Pre-reserve the memory, exiting if we can't
1289    ///     heap.try_reserve(data.len())?;
1290    ///
1291    ///     // Now we know this can't OOM in the middle of our complex work
1292    ///     heap.extend(data.iter());
1293    ///
1294    ///     Ok(heap.pop())
1295    /// }
1296    /// # find_max_slow(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1297    /// ```
1298    #[stable(feature = "try_reserve_2", since = "1.63.0")]
1299    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1300        self.data.try_reserve(additional)
1301    }
1302
1303    /// Discards as much additional capacity as possible.
1304    ///
1305    /// # Examples
1306    ///
1307    /// Basic usage:
1308    ///
1309    /// ```
1310    /// use std::collections::BinaryHeap;
1311    /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
1312    ///
1313    /// assert!(heap.capacity() >= 100);
1314    /// heap.shrink_to_fit();
1315    /// assert!(heap.capacity() == 0);
1316    /// ```
1317    #[stable(feature = "rust1", since = "1.0.0")]
1318    pub fn shrink_to_fit(&mut self) {
1319        self.data.shrink_to_fit();
1320    }
1321
1322    /// Discards capacity with a lower bound.
1323    ///
1324    /// The capacity will remain at least as large as both the length
1325    /// and the supplied value.
1326    ///
1327    /// If the current capacity is less than the lower limit, this is a no-op.
1328    ///
1329    /// # Examples
1330    ///
1331    /// ```
1332    /// use std::collections::BinaryHeap;
1333    /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
1334    ///
1335    /// assert!(heap.capacity() >= 100);
1336    /// heap.shrink_to(10);
1337    /// assert!(heap.capacity() >= 10);
1338    /// ```
1339    #[inline]
1340    #[stable(feature = "shrink_to", since = "1.56.0")]
1341    pub fn shrink_to(&mut self, min_capacity: usize) {
1342        self.data.shrink_to(min_capacity)
1343    }
1344
1345    /// Returns a slice of all values in the underlying vector, in arbitrary
1346    /// order.
1347    ///
1348    /// # Examples
1349    ///
1350    /// Basic usage:
1351    ///
1352    /// ```
1353    /// use std::collections::BinaryHeap;
1354    /// use std::io::{self, Write};
1355    ///
1356    /// let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
1357    ///
1358    /// io::sink().write(heap.as_slice()).unwrap();
1359    /// ```
1360    #[must_use]
1361    #[stable(feature = "binary_heap_as_slice", since = "1.80.0")]
1362    pub fn as_slice(&self) -> &[T] {
1363        self.data.as_slice()
1364    }
1365
1366    /// Returns a mutable slice of all values in the underlying vector.
1367    ///
1368    /// # Safety
1369    ///
1370    /// The caller must ensure that the slice remains a max-heap, i.e. for all indices
1371    /// `0 < i < slice.len()`, `slice[(i - 1) / 2] >= slice[i]`, before the borrow ends
1372    /// and the binary heap is used.
1373    ///
1374    /// # Examples
1375    ///
1376    /// Basic usage:
1377    ///
1378    /// ```
1379    /// #![feature(binary_heap_as_mut_slice)]
1380    ///
1381    /// use std::collections::BinaryHeap;
1382    ///
1383    /// let mut heap = BinaryHeap::<u32>::from([1, 2, 3, 4, 5, 6, 7]);
1384    ///
1385    /// unsafe {
1386    ///     for value in heap.as_mut_slice() {
1387    ///         *value = (*value).saturating_mul(2);
1388    ///     }
1389    /// }
1390    /// ```
1391    #[must_use]
1392    #[unstable(feature = "binary_heap_as_mut_slice", issue = "154009")]
1393    pub unsafe fn as_mut_slice(&mut self) -> &mut [T] {
1394        self.data.as_mut_slice()
1395    }
1396
1397    /// Consumes the `BinaryHeap` and returns the underlying vector
1398    /// in arbitrary order.
1399    ///
1400    /// # Examples
1401    ///
1402    /// Basic usage:
1403    ///
1404    /// ```
1405    /// use std::collections::BinaryHeap;
1406    /// let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
1407    /// let vec = heap.into_vec();
1408    ///
1409    /// // Will print in some order
1410    /// for x in vec {
1411    ///     println!("{x}");
1412    /// }
1413    /// ```
1414    #[must_use = "`self` will be dropped if the result is not used"]
1415    #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1416    pub fn into_vec(self) -> Vec<T, A> {
1417        self.into()
1418    }
1419
1420    /// Returns a reference to the underlying allocator.
1421    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1422    #[inline]
1423    pub fn allocator(&self) -> &A {
1424        self.data.allocator()
1425    }
1426
1427    /// Returns the length of the binary heap.
1428    ///
1429    /// # Examples
1430    ///
1431    /// Basic usage:
1432    ///
1433    /// ```
1434    /// use std::collections::BinaryHeap;
1435    /// let heap = BinaryHeap::from([1, 3]);
1436    ///
1437    /// assert_eq!(heap.len(), 2);
1438    /// ```
1439    #[must_use]
1440    #[stable(feature = "rust1", since = "1.0.0")]
1441    #[rustc_confusables("length", "size")]
1442    #[rustc_const_stable(feature = "const_binary_heap_len", since = "CURRENT_RUSTC_VERSION")]
1443    pub const fn len(&self) -> usize {
1444        self.data.len()
1445    }
1446
1447    /// Checks if the binary heap is empty.
1448    ///
1449    /// # Examples
1450    ///
1451    /// Basic usage:
1452    ///
1453    /// ```
1454    /// use std::collections::BinaryHeap;
1455    /// let mut heap = BinaryHeap::new();
1456    ///
1457    /// assert!(heap.is_empty());
1458    ///
1459    /// heap.push(3);
1460    /// heap.push(5);
1461    /// heap.push(1);
1462    ///
1463    /// assert!(!heap.is_empty());
1464    /// ```
1465    #[must_use]
1466    #[stable(feature = "rust1", since = "1.0.0")]
1467    #[rustc_const_stable(feature = "const_binary_heap_len", since = "CURRENT_RUSTC_VERSION")]
1468    pub const fn is_empty(&self) -> bool {
1469        self.len() == 0
1470    }
1471
1472    /// Clears the binary heap, returning an iterator over the removed elements
1473    /// in arbitrary order. If the iterator is dropped before being fully
1474    /// consumed, it drops the remaining elements in arbitrary order.
1475    ///
1476    /// The returned iterator keeps a mutable borrow on the heap to optimize
1477    /// its implementation.
1478    ///
1479    /// # Examples
1480    ///
1481    /// Basic usage:
1482    ///
1483    /// ```
1484    /// use std::collections::BinaryHeap;
1485    /// let mut heap = BinaryHeap::from([1, 3]);
1486    ///
1487    /// assert!(!heap.is_empty());
1488    ///
1489    /// for x in heap.drain() {
1490    ///     println!("{x}");
1491    /// }
1492    ///
1493    /// assert!(heap.is_empty());
1494    /// ```
1495    #[inline]
1496    #[stable(feature = "drain", since = "1.6.0")]
1497    pub fn drain(&mut self) -> Drain<'_, T, A>
1498    where
1499        A: AllocatorNightly, // needed for the `Vec::drain` call
1500    {
1501        Drain { iter: self.data.drain(..) }
1502    }
1503
1504    /// Drops all items from the binary heap.
1505    ///
1506    /// # Examples
1507    ///
1508    /// Basic usage:
1509    ///
1510    /// ```
1511    /// use std::collections::BinaryHeap;
1512    /// let mut heap = BinaryHeap::from([1, 3]);
1513    ///
1514    /// assert!(!heap.is_empty());
1515    ///
1516    /// heap.clear();
1517    ///
1518    /// assert!(heap.is_empty());
1519    /// ```
1520    #[stable(feature = "rust1", since = "1.0.0")]
1521    pub fn clear(&mut self)
1522    where
1523        A: AllocatorNightly,
1524    {
1525        self.drain();
1526    }
1527}
1528
1529/// Hole represents a hole in a slice i.e., an index without valid value
1530/// (because it was moved from or duplicated).
1531/// In drop, `Hole` will restore the slice by filling the hole
1532/// position with the value that was originally removed.
1533struct Hole<'a, T: 'a> {
1534    data: &'a mut [T],
1535    elt: ManuallyDrop<T>,
1536    pos: usize,
1537}
1538
1539impl<'a, T> Hole<'a, T> {
1540    /// Creates a new `Hole` at index `pos`.
1541    ///
1542    /// # Safety
1543    ///
1544    /// `pos` must be within the data slice.
1545    #[inline]
1546    unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
1547        debug_assert!(pos < data.len());
1548        // SAFETY: Caller ensures pos is inside the slice.
1549        let elt = unsafe { ptr::read(data.get_unchecked(pos)) };
1550        Hole { data, elt: ManuallyDrop::new(elt), pos }
1551    }
1552
1553    #[inline]
1554    fn pos(&self) -> usize {
1555        self.pos
1556    }
1557
1558    /// Returns a reference to the element removed.
1559    #[inline]
1560    fn element(&self) -> &T {
1561        &self.elt
1562    }
1563
1564    /// Returns a reference to the element at `index`.
1565    ///
1566    /// # Safety
1567    ///
1568    /// `index` must be within the data slice and not equal to the current position.
1569    #[inline]
1570    unsafe fn get(&self, index: usize) -> &T {
1571        debug_assert!(index != self.pos);
1572        debug_assert!(index < self.data.len());
1573        // SAFETY: Upheld by caller.
1574        unsafe { self.data.get_unchecked(index) }
1575    }
1576
1577    /// Move hole to new location
1578    ///
1579    /// # Safety
1580    ///
1581    /// `index` must be within the data slice and not equal to the current position.
1582    #[inline]
1583    unsafe fn move_to(&mut self, index: usize) {
1584        debug_assert!(index != self.pos);
1585        debug_assert!(index < self.data.len());
1586        let ptr = self.data.as_mut_ptr();
1587        // ignore-tidy-undocumented-unsafe
1588        unsafe {
1589            let index_ptr: *const _ = ptr.add(index);
1590            let hole_ptr = ptr.add(self.pos);
1591            ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1592        }
1593        self.pos = index;
1594    }
1595}
1596
1597impl<T> Drop for Hole<'_, T> {
1598    #[inline]
1599    fn drop(&mut self) {
1600        // fill the hole again
1601        let pos = self.pos;
1602        // ignore-tidy-undocumented-unsafe
1603        unsafe {
1604            ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
1605        }
1606    }
1607}
1608
1609/// An iterator over the elements of a `BinaryHeap`.
1610///
1611/// This `struct` is created by [`BinaryHeap::iter()`]. See its
1612/// documentation for more.
1613///
1614/// [`iter`]: BinaryHeap::iter
1615#[must_use = "iterators are lazy and do nothing unless consumed"]
1616#[stable(feature = "rust1", since = "1.0.0")]
1617pub struct Iter<'a, T: 'a> {
1618    iter: slice::Iter<'a, T>,
1619}
1620
1621#[stable(feature = "default_iters_sequel", since = "1.82.0")]
1622impl<T> Default for Iter<'_, T> {
1623    /// Creates an empty `binary_heap::Iter`.
1624    ///
1625    /// ```
1626    /// # use std::collections::binary_heap;
1627    /// let iter: binary_heap::Iter<'_, u8> = Default::default();
1628    /// assert_eq!(iter.len(), 0);
1629    /// ```
1630    fn default() -> Self {
1631        Iter { iter: Default::default() }
1632    }
1633}
1634
1635#[stable(feature = "collection_debug", since = "1.17.0")]
1636impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1637    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1638        f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
1639    }
1640}
1641
1642// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1643#[stable(feature = "rust1", since = "1.0.0")]
1644impl<T> Clone for Iter<'_, T> {
1645    fn clone(&self) -> Self {
1646        Iter { iter: self.iter.clone() }
1647    }
1648}
1649
1650#[stable(feature = "rust1", since = "1.0.0")]
1651impl<'a, T> Iterator for Iter<'a, T> {
1652    type Item = &'a T;
1653
1654    #[inline]
1655    fn next(&mut self) -> Option<&'a T> {
1656        self.iter.next()
1657    }
1658
1659    #[inline]
1660    fn size_hint(&self) -> (usize, Option<usize>) {
1661        self.iter.size_hint()
1662    }
1663
1664    #[inline]
1665    fn last(self) -> Option<&'a T> {
1666        self.iter.last()
1667    }
1668}
1669
1670#[stable(feature = "rust1", since = "1.0.0")]
1671impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1672    #[inline]
1673    fn next_back(&mut self) -> Option<&'a T> {
1674        self.iter.next_back()
1675    }
1676}
1677
1678#[stable(feature = "rust1", since = "1.0.0")]
1679impl<T> ExactSizeIterator for Iter<'_, T> {
1680    fn is_empty(&self) -> bool {
1681        self.iter.is_empty()
1682    }
1683}
1684
1685#[stable(feature = "fused", since = "1.26.0")]
1686impl<T> FusedIterator for Iter<'_, T> {}
1687
1688/// An owning iterator over the elements of a `BinaryHeap`.
1689///
1690/// This `struct` is created by [`BinaryHeap::into_iter()`]
1691/// (provided by the [`IntoIterator`] trait). See its documentation for more.
1692///
1693/// [`into_iter`]: BinaryHeap::into_iter
1694#[stable(feature = "rust1", since = "1.0.0")]
1695#[derive(Clone)]
1696pub struct IntoIter<
1697    T,
1698    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1699> {
1700    iter: vec::IntoIter<T, A>,
1701}
1702
1703impl<T, A: Allocator> IntoIter<T, A> {
1704    /// Returns a reference to the underlying allocator.
1705    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1706    pub fn allocator(&self) -> &A {
1707        self.iter.allocator()
1708    }
1709}
1710
1711#[stable(feature = "collection_debug", since = "1.17.0")]
1712impl<T: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<T, A> {
1713    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1714        f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
1715    }
1716}
1717
1718#[stable(feature = "rust1", since = "1.0.0")]
1719impl<T, A: Allocator> Iterator for IntoIter<T, A> {
1720    type Item = T;
1721
1722    #[inline]
1723    fn next(&mut self) -> Option<T> {
1724        self.iter.next()
1725    }
1726
1727    #[inline]
1728    fn size_hint(&self) -> (usize, Option<usize>) {
1729        self.iter.size_hint()
1730    }
1731}
1732
1733#[stable(feature = "rust1", since = "1.0.0")]
1734impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
1735    #[inline]
1736    fn next_back(&mut self) -> Option<T> {
1737        self.iter.next_back()
1738    }
1739}
1740
1741#[stable(feature = "rust1", since = "1.0.0")]
1742impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {
1743    fn is_empty(&self) -> bool {
1744        self.iter.is_empty()
1745    }
1746}
1747
1748#[stable(feature = "fused", since = "1.26.0")]
1749impl<T, A: Allocator> FusedIterator for IntoIter<T, A> {}
1750
1751#[doc(hidden)]
1752#[unstable(issue = "none", feature = "trusted_fused")]
1753unsafe impl<T, A: Allocator> TrustedFused for IntoIter<T, A> {}
1754
1755#[stable(feature = "default_iters", since = "1.70.0")]
1756impl<T> Default for IntoIter<T> {
1757    /// Creates an empty `binary_heap::IntoIter`.
1758    ///
1759    /// ```
1760    /// # use std::collections::binary_heap;
1761    /// let iter: binary_heap::IntoIter<u8> = Default::default();
1762    /// assert_eq!(iter.len(), 0);
1763    /// ```
1764    fn default() -> Self {
1765        IntoIter { iter: Default::default() }
1766    }
1767}
1768
1769// In addition to the SAFETY invariants of the following three unsafe traits
1770// also refer to the vec::in_place_collect module documentation to get an overview
1771#[unstable(issue = "none", feature = "inplace_iteration")]
1772#[doc(hidden)]
1773unsafe impl<T, A: Allocator> SourceIter for IntoIter<T, A> {
1774    type Source = IntoIter<T, A>;
1775
1776    #[inline]
1777    unsafe fn as_inner(&mut self) -> &mut Self::Source {
1778        self
1779    }
1780}
1781
1782#[unstable(issue = "none", feature = "inplace_iteration")]
1783#[doc(hidden)]
1784unsafe impl<I, A: Allocator> InPlaceIterable for IntoIter<I, A> {
1785    const EXPAND_BY: Option<NonZero<usize>> = NonZero::new(1);
1786    const MERGE_BY: Option<NonZero<usize>> = NonZero::new(1);
1787}
1788
1789#[cfg(not(test))]
1790unsafe impl<I> AsVecIntoIter for IntoIter<I> {
1791    type Item = I;
1792
1793    fn as_into_iter(&mut self) -> &mut vec::IntoIter<Self::Item> {
1794        &mut self.iter
1795    }
1796}
1797
1798#[must_use = "iterators are lazy and do nothing unless consumed"]
1799#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1800#[derive(Clone, Debug)]
1801pub struct IntoIterSorted<
1802    T,
1803    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1804> {
1805    inner: BinaryHeap<T, A>,
1806}
1807
1808impl<T, A: Allocator> IntoIterSorted<T, A> {
1809    /// Returns a reference to the underlying allocator.
1810    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1811    pub fn allocator(&self) -> &A {
1812        self.inner.allocator()
1813    }
1814}
1815
1816#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1817impl<T: Ord, A: Allocator> Iterator for IntoIterSorted<T, A> {
1818    type Item = T;
1819
1820    #[inline]
1821    fn next(&mut self) -> Option<T> {
1822        self.inner.pop()
1823    }
1824
1825    #[inline]
1826    fn size_hint(&self) -> (usize, Option<usize>) {
1827        let exact = self.inner.len();
1828        (exact, Some(exact))
1829    }
1830}
1831
1832#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1833impl<T: Ord, A: Allocator> ExactSizeIterator for IntoIterSorted<T, A> {}
1834
1835#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1836impl<T: Ord, A: Allocator> FusedIterator for IntoIterSorted<T, A> {}
1837
1838#[unstable(feature = "trusted_len", issue = "37572")]
1839unsafe impl<T: Ord, A: Allocator> TrustedLen for IntoIterSorted<T, A> {}
1840
1841/// A draining iterator over the elements of a `BinaryHeap`.
1842///
1843/// This `struct` is created by [`BinaryHeap::drain()`]. See its
1844/// documentation for more.
1845///
1846/// [`drain`]: BinaryHeap::drain
1847#[stable(feature = "drain", since = "1.6.0")]
1848#[derive(Debug)]
1849pub struct Drain<
1850    'a,
1851    T: 'a,
1852    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1853> {
1854    iter: vec::Drain<'a, T, A>,
1855}
1856
1857impl<T, A: Allocator> Drain<'_, T, A> {
1858    /// Returns a reference to the underlying allocator.
1859    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1860    pub fn allocator(&self) -> &A {
1861        self.iter.allocator()
1862    }
1863}
1864
1865#[stable(feature = "drain", since = "1.6.0")]
1866impl<T, A: Allocator> Iterator for Drain<'_, T, A> {
1867    type Item = T;
1868
1869    #[inline]
1870    fn next(&mut self) -> Option<T> {
1871        self.iter.next()
1872    }
1873
1874    #[inline]
1875    fn size_hint(&self) -> (usize, Option<usize>) {
1876        self.iter.size_hint()
1877    }
1878}
1879
1880#[stable(feature = "drain", since = "1.6.0")]
1881impl<T, A: Allocator> DoubleEndedIterator for Drain<'_, T, A> {
1882    #[inline]
1883    fn next_back(&mut self) -> Option<T> {
1884        self.iter.next_back()
1885    }
1886}
1887
1888#[stable(feature = "drain", since = "1.6.0")]
1889impl<T, A: Allocator> ExactSizeIterator for Drain<'_, T, A> {
1890    fn is_empty(&self) -> bool {
1891        self.iter.is_empty()
1892    }
1893}
1894
1895#[stable(feature = "fused", since = "1.26.0")]
1896impl<T, A: Allocator> FusedIterator for Drain<'_, T, A> {}
1897
1898/// A draining iterator over the elements of a `BinaryHeap`.
1899///
1900/// This `struct` is created by [`BinaryHeap::drain_sorted()`]. See its
1901/// documentation for more.
1902///
1903/// [`drain_sorted`]: BinaryHeap::drain_sorted
1904#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1905#[derive(Debug)]
1906pub struct DrainSorted<
1907    'a,
1908    T: Ord,
1909    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1910> {
1911    inner: &'a mut BinaryHeap<T, A>,
1912}
1913
1914impl<'a, T: Ord, A: Allocator> DrainSorted<'a, T, A> {
1915    /// Returns a reference to the underlying allocator.
1916    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1917    pub fn allocator(&self) -> &A {
1918        self.inner.allocator()
1919    }
1920}
1921
1922#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1923impl<'a, T: Ord, A: Allocator> Drop for DrainSorted<'a, T, A> {
1924    /// Removes heap elements in heap order.
1925    fn drop(&mut self) {
1926        struct DropGuard<'r, 'a, T: Ord, A: Allocator>(&'r mut DrainSorted<'a, T, A>);
1927
1928        impl<'r, 'a, T: Ord, A: Allocator> Drop for DropGuard<'r, 'a, T, A> {
1929            fn drop(&mut self) {
1930                while self.0.inner.pop().is_some() {}
1931            }
1932        }
1933
1934        while let Some(item) = self.inner.pop() {
1935            let guard = DropGuard(self);
1936            drop(item);
1937            mem::forget(guard);
1938        }
1939    }
1940}
1941
1942#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1943impl<T: Ord, A: Allocator> Iterator for DrainSorted<'_, T, A> {
1944    type Item = T;
1945
1946    #[inline]
1947    fn next(&mut self) -> Option<T> {
1948        self.inner.pop()
1949    }
1950
1951    #[inline]
1952    fn size_hint(&self) -> (usize, Option<usize>) {
1953        let exact = self.inner.len();
1954        (exact, Some(exact))
1955    }
1956}
1957
1958#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1959impl<T: Ord, A: Allocator> ExactSizeIterator for DrainSorted<'_, T, A> {}
1960
1961#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1962impl<T: Ord, A: Allocator> FusedIterator for DrainSorted<'_, T, A> {}
1963
1964#[unstable(feature = "trusted_len", issue = "37572")]
1965unsafe impl<T: Ord, A: Allocator> TrustedLen for DrainSorted<'_, T, A> {}
1966
1967#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1968impl<T: Ord, A: AllocatorNightly> From<Vec<T, A>> for BinaryHeap<T, A> {
1969    /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1970    ///
1971    /// This conversion happens in-place, and has *O*(*n*) time complexity.
1972    fn from(vec: Vec<T, A>) -> BinaryHeap<T, A> {
1973        let mut heap = BinaryHeap { data: vec };
1974        heap.rebuild();
1975        heap
1976    }
1977}
1978
1979#[stable(feature = "std_collections_from_array", since = "1.56.0")]
1980impl<T: Ord, const N: usize> From<[T; N]> for BinaryHeap<T> {
1981    /// ```
1982    /// use std::collections::BinaryHeap;
1983    ///
1984    /// let mut h1 = BinaryHeap::from([1, 4, 2, 3]);
1985    /// let mut h2: BinaryHeap<_> = [1, 4, 2, 3].into();
1986    /// while let Some((a, b)) = h1.pop().zip(h2.pop()) {
1987    ///     assert_eq!(a, b);
1988    /// }
1989    /// ```
1990    fn from(arr: [T; N]) -> Self {
1991        Self::from_iter(arr)
1992    }
1993}
1994
1995#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1996impl<T, A: Allocator> From<BinaryHeap<T, A>> for Vec<T, A> {
1997    /// Converts a `BinaryHeap<T>` into a `Vec<T>`.
1998    ///
1999    /// This conversion requires no data movement or allocation, and has
2000    /// constant time complexity.
2001    fn from(heap: BinaryHeap<T, A>) -> Vec<T, A> {
2002        heap.data
2003    }
2004}
2005
2006#[stable(feature = "rust1", since = "1.0.0")]
2007impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
2008    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
2009        BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
2010    }
2011}
2012
2013#[stable(feature = "rust1", since = "1.0.0")]
2014impl<T, A: Allocator> IntoIterator for BinaryHeap<T, A> {
2015    type Item = T;
2016    type IntoIter = IntoIter<T, A>;
2017
2018    /// Creates a consuming iterator, that is, one that moves each value out of
2019    /// the binary heap in arbitrary order. The binary heap cannot be used
2020    /// after calling this.
2021    ///
2022    /// # Examples
2023    ///
2024    /// Basic usage:
2025    ///
2026    /// ```
2027    /// use std::collections::BinaryHeap;
2028    /// let heap = BinaryHeap::from([1, 2, 3, 4]);
2029    ///
2030    /// // Print 1, 2, 3, 4 in arbitrary order
2031    /// for x in heap.into_iter() {
2032    ///     // x has type i32, not &i32
2033    ///     println!("{x}");
2034    /// }
2035    /// ```
2036    fn into_iter(self) -> IntoIter<T, A> {
2037        IntoIter { iter: self.data.into_iter() }
2038    }
2039}
2040
2041#[stable(feature = "rust1", since = "1.0.0")]
2042impl<'a, T, A: Allocator> IntoIterator for &'a BinaryHeap<T, A> {
2043    type Item = &'a T;
2044    type IntoIter = Iter<'a, T>;
2045
2046    fn into_iter(self) -> Iter<'a, T> {
2047        self.iter()
2048    }
2049}
2050
2051#[stable(feature = "rust1", since = "1.0.0")]
2052impl<T: Ord, A: Allocator> Extend<T> for BinaryHeap<T, A> {
2053    #[inline]
2054    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2055        let guard = RebuildOnDrop { rebuild_from: self.len(), heap: self };
2056        guard.heap.data.extend(iter);
2057    }
2058
2059    #[inline]
2060    fn extend_one(&mut self, item: T) {
2061        self.push(item);
2062    }
2063
2064    #[inline]
2065    fn extend_reserve(&mut self, additional: usize) {
2066        self.reserve(additional);
2067    }
2068}
2069
2070#[stable(feature = "extend_ref", since = "1.2.0")]
2071impl<'a, T: 'a + Ord + Copy, A: Allocator> Extend<&'a T> for BinaryHeap<T, A> {
2072    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2073        self.extend(iter.into_iter().cloned());
2074    }
2075
2076    #[inline]
2077    fn extend_one(&mut self, &item: &'a T) {
2078        self.push(item);
2079    }
2080
2081    #[inline]
2082    fn extend_reserve(&mut self, additional: usize) {
2083        self.reserve(additional);
2084    }
2085}