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    /// For performance, `self` and `other` may be swapped before appending.
983    ///
984    /// # Examples
985    ///
986    /// Basic usage:
987    ///
988    /// ```
989    /// use std::collections::BinaryHeap;
990    ///
991    /// let mut a = BinaryHeap::from([-10, 1, 2, 3, 3]);
992    /// let mut b = BinaryHeap::from([-20, 5, 43]);
993    ///
994    /// a.append(&mut b);
995    ///
996    /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
997    /// assert!(b.is_empty());
998    /// ```
999    #[stable(feature = "binary_heap_append", since = "1.11.0")]
1000    pub fn append(&mut self, other: &mut Self) {
1001        if self.len() < other.len() {
1002            swap(self, other);
1003        }
1004
1005        let start = self.data.len();
1006
1007        self.data.append(&mut other.data);
1008
1009        self.rebuild_tail(start);
1010    }
1011
1012    /// Clears the binary heap, returning an iterator over the removed elements
1013    /// in heap order. If the iterator is dropped before being fully consumed,
1014    /// it drops the remaining elements in heap order.
1015    ///
1016    /// The returned iterator keeps a mutable borrow on the heap to optimize
1017    /// its implementation.
1018    ///
1019    /// Note:
1020    /// * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`.
1021    ///   You should use the latter for most cases.
1022    ///
1023    /// # Examples
1024    ///
1025    /// Basic usage:
1026    ///
1027    /// ```
1028    /// #![feature(binary_heap_drain_sorted)]
1029    /// use std::collections::BinaryHeap;
1030    ///
1031    /// let mut heap = BinaryHeap::from([1, 2, 3, 4, 5]);
1032    /// assert_eq!(heap.len(), 5);
1033    ///
1034    /// drop(heap.drain_sorted()); // removes all elements in heap order
1035    /// assert_eq!(heap.len(), 0);
1036    /// ```
1037    #[inline]
1038    #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1039    pub fn drain_sorted(&mut self) -> DrainSorted<'_, T, A> {
1040        DrainSorted { inner: self }
1041    }
1042
1043    /// Retains only the elements specified by the predicate.
1044    ///
1045    /// In other words, remove all elements `e` for which `f(&e)` returns
1046    /// `false`. The elements are visited in unsorted (and unspecified) order.
1047    ///
1048    /// # Examples
1049    ///
1050    /// Basic usage:
1051    ///
1052    /// ```
1053    /// use std::collections::BinaryHeap;
1054    ///
1055    /// let mut heap = BinaryHeap::from([-10, -5, 1, 2, 4, 13]);
1056    ///
1057    /// heap.retain(|x| x % 2 == 0); // only keep even numbers
1058    ///
1059    /// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
1060    /// ```
1061    #[stable(feature = "binary_heap_retain", since = "1.70.0")]
1062    pub fn retain<F>(&mut self, mut f: F)
1063    where
1064        F: FnMut(&T) -> bool,
1065    {
1066        // rebuild_start will be updated to the first touched element below, and the rebuild will
1067        // only be done for the tail.
1068        let mut guard = RebuildOnDrop { rebuild_from: self.len(), heap: self };
1069        let mut i = 0;
1070
1071        guard.heap.data.retain(|e| {
1072            let keep = f(e);
1073            if !keep && i < guard.rebuild_from {
1074                guard.rebuild_from = i;
1075            }
1076            i += 1;
1077            keep
1078        });
1079    }
1080}
1081
1082impl<T, A: Allocator> BinaryHeap<T, A> {
1083    /// Returns an iterator visiting all values in the underlying vector, in
1084    /// arbitrary order.
1085    ///
1086    /// # Examples
1087    ///
1088    /// Basic usage:
1089    ///
1090    /// ```
1091    /// use std::collections::BinaryHeap;
1092    /// let heap = BinaryHeap::from([1, 2, 3, 4]);
1093    ///
1094    /// // Print 1, 2, 3, 4 in arbitrary order
1095    /// for x in heap.iter() {
1096    ///     println!("{x}");
1097    /// }
1098    /// ```
1099    #[stable(feature = "rust1", since = "1.0.0")]
1100    #[cfg_attr(not(test), rustc_diagnostic_item = "binaryheap_iter")]
1101    pub fn iter(&self) -> Iter<'_, T> {
1102        Iter { iter: self.data.iter() }
1103    }
1104
1105    /// Returns an iterator which retrieves elements in heap order.
1106    ///
1107    /// This method consumes the original heap.
1108    ///
1109    /// # Examples
1110    ///
1111    /// Basic usage:
1112    ///
1113    /// ```
1114    /// #![feature(binary_heap_into_iter_sorted)]
1115    /// use std::collections::BinaryHeap;
1116    /// let heap = BinaryHeap::from([1, 2, 3, 4, 5]);
1117    ///
1118    /// assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), [5, 4]);
1119    /// ```
1120    #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1121    pub fn into_iter_sorted(self) -> IntoIterSorted<T, A> {
1122        IntoIterSorted { inner: self }
1123    }
1124
1125    /// Returns the greatest item in the binary heap, or `None` if it is empty.
1126    ///
1127    /// # Examples
1128    ///
1129    /// Basic usage:
1130    ///
1131    /// ```
1132    /// use std::collections::BinaryHeap;
1133    /// let mut heap = BinaryHeap::new();
1134    /// assert_eq!(heap.peek(), None);
1135    ///
1136    /// heap.push(1);
1137    /// heap.push(5);
1138    /// heap.push(2);
1139    /// assert_eq!(heap.peek(), Some(&5));
1140    ///
1141    /// ```
1142    ///
1143    /// # Time complexity
1144    ///
1145    /// Cost is *O*(1) in the worst case.
1146    #[must_use]
1147    #[stable(feature = "rust1", since = "1.0.0")]
1148    pub fn peek(&self) -> Option<&T> {
1149        self.data.get(0)
1150    }
1151
1152    /// Returns the number of elements the binary heap can hold without reallocating.
1153    ///
1154    /// # Examples
1155    ///
1156    /// Basic usage:
1157    ///
1158    /// ```
1159    /// use std::collections::BinaryHeap;
1160    /// let mut heap = BinaryHeap::with_capacity(100);
1161    /// assert!(heap.capacity() >= 100);
1162    /// heap.push(4);
1163    /// ```
1164    #[must_use]
1165    #[stable(feature = "rust1", since = "1.0.0")]
1166    pub fn capacity(&self) -> usize {
1167        self.data.capacity()
1168    }
1169
1170    /// Reserves the minimum capacity for at least `additional` elements more than
1171    /// the current length. Unlike [`reserve`], this will not
1172    /// deliberately over-allocate to speculatively avoid frequent allocations.
1173    /// After calling `reserve_exact`, capacity will be greater than or equal to
1174    /// `self.len() + additional`. Does nothing if the capacity is already
1175    /// sufficient.
1176    ///
1177    /// [`reserve`]: BinaryHeap::reserve
1178    ///
1179    /// # Panics
1180    ///
1181    /// Panics if the new capacity overflows [`usize`].
1182    ///
1183    /// # Examples
1184    ///
1185    /// Basic usage:
1186    ///
1187    /// ```
1188    /// use std::collections::BinaryHeap;
1189    /// let mut heap = BinaryHeap::new();
1190    /// heap.reserve_exact(100);
1191    /// assert!(heap.capacity() >= 100);
1192    /// heap.push(4);
1193    /// ```
1194    ///
1195    /// [`reserve`]: BinaryHeap::reserve
1196    #[stable(feature = "rust1", since = "1.0.0")]
1197    pub fn reserve_exact(&mut self, additional: usize) {
1198        self.data.reserve_exact(additional);
1199    }
1200
1201    /// Reserves capacity for at least `additional` elements more than the
1202    /// current length. The allocator may reserve more space to speculatively
1203    /// avoid frequent allocations. After calling `reserve`,
1204    /// capacity will be greater than or equal to `self.len() + additional`.
1205    /// Does nothing if capacity is already sufficient.
1206    ///
1207    /// # Panics
1208    ///
1209    /// Panics if the new capacity overflows [`usize`].
1210    ///
1211    /// # Examples
1212    ///
1213    /// Basic usage:
1214    ///
1215    /// ```
1216    /// use std::collections::BinaryHeap;
1217    /// let mut heap = BinaryHeap::new();
1218    /// heap.reserve(100);
1219    /// assert!(heap.capacity() >= 100);
1220    /// heap.push(4);
1221    /// ```
1222    #[stable(feature = "rust1", since = "1.0.0")]
1223    pub fn reserve(&mut self, additional: usize) {
1224        self.data.reserve(additional);
1225    }
1226
1227    /// Tries to reserve the minimum capacity for at least `additional` elements
1228    /// more than the current length. Unlike [`try_reserve`], this will not
1229    /// deliberately over-allocate to speculatively avoid frequent allocations.
1230    /// After calling `try_reserve_exact`, capacity will be greater than or
1231    /// equal to `self.len() + additional` if it returns `Ok(())`.
1232    /// Does nothing if the capacity is already sufficient.
1233    ///
1234    /// Note that the allocator may give the collection more space than it
1235    /// requests. Therefore, capacity can not be relied upon to be precisely
1236    /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1237    ///
1238    /// [`try_reserve`]: BinaryHeap::try_reserve
1239    ///
1240    /// # Errors
1241    ///
1242    /// If the capacity overflows, or the allocator reports a failure, then an error
1243    /// is returned.
1244    ///
1245    /// # Examples
1246    ///
1247    /// ```
1248    /// use std::collections::BinaryHeap;
1249    /// use std::collections::TryReserveError;
1250    ///
1251    /// fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
1252    ///     let mut heap = BinaryHeap::new();
1253    ///
1254    ///     // Pre-reserve the memory, exiting if we can't
1255    ///     heap.try_reserve_exact(data.len())?;
1256    ///
1257    ///     // Now we know this can't OOM in the middle of our complex work
1258    ///     heap.extend(data.iter());
1259    ///
1260    ///     Ok(heap.pop())
1261    /// }
1262    /// # find_max_slow(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1263    /// ```
1264    #[stable(feature = "try_reserve_2", since = "1.63.0")]
1265    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1266        self.data.try_reserve_exact(additional)
1267    }
1268
1269    /// Tries to reserve capacity for at least `additional` elements more than the
1270    /// current length. The allocator may reserve more space to speculatively
1271    /// avoid frequent allocations. After calling `try_reserve`, capacity will be
1272    /// greater than or equal to `self.len() + additional` if it returns
1273    /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1274    /// preserves the contents even if an error occurs.
1275    ///
1276    /// # Errors
1277    ///
1278    /// If the capacity overflows, or the allocator reports a failure, then an error
1279    /// is returned.
1280    ///
1281    /// # Examples
1282    ///
1283    /// ```
1284    /// use std::collections::BinaryHeap;
1285    /// use std::collections::TryReserveError;
1286    ///
1287    /// fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
1288    ///     let mut heap = BinaryHeap::new();
1289    ///
1290    ///     // Pre-reserve the memory, exiting if we can't
1291    ///     heap.try_reserve(data.len())?;
1292    ///
1293    ///     // Now we know this can't OOM in the middle of our complex work
1294    ///     heap.extend(data.iter());
1295    ///
1296    ///     Ok(heap.pop())
1297    /// }
1298    /// # find_max_slow(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1299    /// ```
1300    #[stable(feature = "try_reserve_2", since = "1.63.0")]
1301    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1302        self.data.try_reserve(additional)
1303    }
1304
1305    /// Discards as much additional capacity as possible.
1306    ///
1307    /// # Examples
1308    ///
1309    /// Basic usage:
1310    ///
1311    /// ```
1312    /// use std::collections::BinaryHeap;
1313    /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
1314    ///
1315    /// assert!(heap.capacity() >= 100);
1316    /// heap.shrink_to_fit();
1317    /// assert!(heap.capacity() == 0);
1318    /// ```
1319    #[stable(feature = "rust1", since = "1.0.0")]
1320    pub fn shrink_to_fit(&mut self) {
1321        self.data.shrink_to_fit();
1322    }
1323
1324    /// Discards capacity with a lower bound.
1325    ///
1326    /// The capacity will remain at least as large as both the length
1327    /// and the supplied value.
1328    ///
1329    /// If the current capacity is less than the lower limit, this is a no-op.
1330    ///
1331    /// # Examples
1332    ///
1333    /// ```
1334    /// use std::collections::BinaryHeap;
1335    /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
1336    ///
1337    /// assert!(heap.capacity() >= 100);
1338    /// heap.shrink_to(10);
1339    /// assert!(heap.capacity() >= 10);
1340    /// ```
1341    #[inline]
1342    #[stable(feature = "shrink_to", since = "1.56.0")]
1343    pub fn shrink_to(&mut self, min_capacity: usize) {
1344        self.data.shrink_to(min_capacity)
1345    }
1346
1347    /// Returns a slice of all values in the underlying vector, in arbitrary
1348    /// order.
1349    ///
1350    /// # Examples
1351    ///
1352    /// Basic usage:
1353    ///
1354    /// ```
1355    /// use std::collections::BinaryHeap;
1356    /// use std::io::{self, Write};
1357    ///
1358    /// let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
1359    ///
1360    /// io::sink().write(heap.as_slice()).unwrap();
1361    /// ```
1362    #[must_use]
1363    #[stable(feature = "binary_heap_as_slice", since = "1.80.0")]
1364    pub fn as_slice(&self) -> &[T] {
1365        self.data.as_slice()
1366    }
1367
1368    /// Returns a mutable slice of all values in the underlying vector.
1369    ///
1370    /// # Safety
1371    ///
1372    /// The caller must ensure that the slice remains a max-heap, i.e. for all indices
1373    /// `0 < i < slice.len()`, `slice[(i - 1) / 2] >= slice[i]`, before the borrow ends
1374    /// and the binary heap is used.
1375    ///
1376    /// # Examples
1377    ///
1378    /// Basic usage:
1379    ///
1380    /// ```
1381    /// #![feature(binary_heap_as_mut_slice)]
1382    ///
1383    /// use std::collections::BinaryHeap;
1384    ///
1385    /// let mut heap = BinaryHeap::<u32>::from([1, 2, 3, 4, 5, 6, 7]);
1386    ///
1387    /// unsafe {
1388    ///     for value in heap.as_mut_slice() {
1389    ///         *value = (*value).saturating_mul(2);
1390    ///     }
1391    /// }
1392    /// ```
1393    #[must_use]
1394    #[unstable(feature = "binary_heap_as_mut_slice", issue = "154009")]
1395    pub unsafe fn as_mut_slice(&mut self) -> &mut [T] {
1396        self.data.as_mut_slice()
1397    }
1398
1399    /// Consumes the `BinaryHeap` and returns the underlying vector
1400    /// in arbitrary order.
1401    ///
1402    /// # Examples
1403    ///
1404    /// Basic usage:
1405    ///
1406    /// ```
1407    /// use std::collections::BinaryHeap;
1408    /// let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
1409    /// let vec = heap.into_vec();
1410    ///
1411    /// // Will print in some order
1412    /// for x in vec {
1413    ///     println!("{x}");
1414    /// }
1415    /// ```
1416    #[must_use = "`self` will be dropped if the result is not used"]
1417    #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1418    pub fn into_vec(self) -> Vec<T, A> {
1419        self.into()
1420    }
1421
1422    /// Returns a reference to the underlying allocator.
1423    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1424    #[inline]
1425    pub fn allocator(&self) -> &A {
1426        self.data.allocator()
1427    }
1428
1429    /// Returns the length of the binary heap.
1430    ///
1431    /// # Examples
1432    ///
1433    /// Basic usage:
1434    ///
1435    /// ```
1436    /// use std::collections::BinaryHeap;
1437    /// let heap = BinaryHeap::from([1, 3]);
1438    ///
1439    /// assert_eq!(heap.len(), 2);
1440    /// ```
1441    #[must_use]
1442    #[stable(feature = "rust1", since = "1.0.0")]
1443    #[rustc_confusables("length", "size")]
1444    #[rustc_const_stable(feature = "const_binary_heap_len", since = "1.101.0")]
1445    pub const fn len(&self) -> usize {
1446        self.data.len()
1447    }
1448
1449    /// Checks if the binary heap is empty.
1450    ///
1451    /// # Examples
1452    ///
1453    /// Basic usage:
1454    ///
1455    /// ```
1456    /// use std::collections::BinaryHeap;
1457    /// let mut heap = BinaryHeap::new();
1458    ///
1459    /// assert!(heap.is_empty());
1460    ///
1461    /// heap.push(3);
1462    /// heap.push(5);
1463    /// heap.push(1);
1464    ///
1465    /// assert!(!heap.is_empty());
1466    /// ```
1467    #[must_use]
1468    #[stable(feature = "rust1", since = "1.0.0")]
1469    #[rustc_const_stable(feature = "const_binary_heap_len", since = "1.101.0")]
1470    pub const fn is_empty(&self) -> bool {
1471        self.len() == 0
1472    }
1473
1474    /// Clears the binary heap, returning an iterator over the removed elements
1475    /// in arbitrary order. If the iterator is dropped before being fully
1476    /// consumed, it drops the remaining elements in arbitrary order.
1477    ///
1478    /// The returned iterator keeps a mutable borrow on the heap to optimize
1479    /// its implementation.
1480    ///
1481    /// # Examples
1482    ///
1483    /// Basic usage:
1484    ///
1485    /// ```
1486    /// use std::collections::BinaryHeap;
1487    /// let mut heap = BinaryHeap::from([1, 3]);
1488    ///
1489    /// assert!(!heap.is_empty());
1490    ///
1491    /// for x in heap.drain() {
1492    ///     println!("{x}");
1493    /// }
1494    ///
1495    /// assert!(heap.is_empty());
1496    /// ```
1497    #[inline]
1498    #[stable(feature = "drain", since = "1.6.0")]
1499    pub fn drain(&mut self) -> Drain<'_, T, A>
1500    where
1501        A: AllocatorNightly, // needed for the `Vec::drain` call
1502    {
1503        Drain { iter: self.data.drain(..) }
1504    }
1505
1506    /// Drops all items from the binary heap.
1507    ///
1508    /// # Examples
1509    ///
1510    /// Basic usage:
1511    ///
1512    /// ```
1513    /// use std::collections::BinaryHeap;
1514    /// let mut heap = BinaryHeap::from([1, 3]);
1515    ///
1516    /// assert!(!heap.is_empty());
1517    ///
1518    /// heap.clear();
1519    ///
1520    /// assert!(heap.is_empty());
1521    /// ```
1522    #[stable(feature = "rust1", since = "1.0.0")]
1523    pub fn clear(&mut self)
1524    where
1525        A: AllocatorNightly,
1526    {
1527        self.drain();
1528    }
1529}
1530
1531/// Hole represents a hole in a slice i.e., an index without valid value
1532/// (because it was moved from or duplicated).
1533/// In drop, `Hole` will restore the slice by filling the hole
1534/// position with the value that was originally removed.
1535struct Hole<'a, T: 'a> {
1536    data: &'a mut [T],
1537    elt: ManuallyDrop<T>,
1538    pos: usize,
1539}
1540
1541impl<'a, T> Hole<'a, T> {
1542    /// Creates a new `Hole` at index `pos`.
1543    ///
1544    /// # Safety
1545    ///
1546    /// `pos` must be within the data slice.
1547    #[inline]
1548    unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
1549        debug_assert!(pos < data.len());
1550        // SAFETY: Caller ensures pos is inside the slice.
1551        let elt = unsafe { ptr::read(data.get_unchecked(pos)) };
1552        Hole { data, elt: ManuallyDrop::new(elt), pos }
1553    }
1554
1555    #[inline]
1556    fn pos(&self) -> usize {
1557        self.pos
1558    }
1559
1560    /// Returns a reference to the element removed.
1561    #[inline]
1562    fn element(&self) -> &T {
1563        &self.elt
1564    }
1565
1566    /// Returns a reference to the element at `index`.
1567    ///
1568    /// # Safety
1569    ///
1570    /// `index` must be within the data slice and not equal to the current position.
1571    #[inline]
1572    unsafe fn get(&self, index: usize) -> &T {
1573        debug_assert!(index != self.pos);
1574        debug_assert!(index < self.data.len());
1575        // SAFETY: Upheld by caller.
1576        unsafe { self.data.get_unchecked(index) }
1577    }
1578
1579    /// Move hole to new location
1580    ///
1581    /// # Safety
1582    ///
1583    /// `index` must be within the data slice and not equal to the current position.
1584    #[inline]
1585    unsafe fn move_to(&mut self, index: usize) {
1586        debug_assert!(index != self.pos);
1587        debug_assert!(index < self.data.len());
1588        let ptr = self.data.as_mut_ptr();
1589        // ignore-tidy-undocumented-unsafe
1590        unsafe {
1591            let index_ptr: *const _ = ptr.add(index);
1592            let hole_ptr = ptr.add(self.pos);
1593            ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1594        }
1595        self.pos = index;
1596    }
1597}
1598
1599impl<T> Drop for Hole<'_, T> {
1600    #[inline]
1601    fn drop(&mut self) {
1602        // fill the hole again
1603        let pos = self.pos;
1604        // ignore-tidy-undocumented-unsafe
1605        unsafe {
1606            ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
1607        }
1608    }
1609}
1610
1611/// An iterator over the elements of a `BinaryHeap`.
1612///
1613/// This `struct` is created by [`BinaryHeap::iter()`]. See its
1614/// documentation for more.
1615///
1616/// [`iter`]: BinaryHeap::iter
1617#[must_use = "iterators are lazy and do nothing unless consumed"]
1618#[stable(feature = "rust1", since = "1.0.0")]
1619pub struct Iter<'a, T: 'a> {
1620    iter: slice::Iter<'a, T>,
1621}
1622
1623#[stable(feature = "default_iters_sequel", since = "1.82.0")]
1624impl<T> Default for Iter<'_, T> {
1625    /// Creates an empty `binary_heap::Iter`.
1626    ///
1627    /// ```
1628    /// # use std::collections::binary_heap;
1629    /// let iter: binary_heap::Iter<'_, u8> = Default::default();
1630    /// assert_eq!(iter.len(), 0);
1631    /// ```
1632    fn default() -> Self {
1633        Iter { iter: Default::default() }
1634    }
1635}
1636
1637#[stable(feature = "collection_debug", since = "1.17.0")]
1638impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1639    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1640        f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
1641    }
1642}
1643
1644// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1645#[stable(feature = "rust1", since = "1.0.0")]
1646impl<T> Clone for Iter<'_, T> {
1647    fn clone(&self) -> Self {
1648        Iter { iter: self.iter.clone() }
1649    }
1650}
1651
1652#[stable(feature = "rust1", since = "1.0.0")]
1653impl<'a, T> Iterator for Iter<'a, T> {
1654    type Item = &'a T;
1655
1656    #[inline]
1657    fn next(&mut self) -> Option<&'a T> {
1658        self.iter.next()
1659    }
1660
1661    #[inline]
1662    fn size_hint(&self) -> (usize, Option<usize>) {
1663        self.iter.size_hint()
1664    }
1665
1666    #[inline]
1667    fn last(self) -> Option<&'a T> {
1668        self.iter.last()
1669    }
1670}
1671
1672#[stable(feature = "rust1", since = "1.0.0")]
1673impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1674    #[inline]
1675    fn next_back(&mut self) -> Option<&'a T> {
1676        self.iter.next_back()
1677    }
1678}
1679
1680#[stable(feature = "rust1", since = "1.0.0")]
1681impl<T> ExactSizeIterator for Iter<'_, T> {
1682    fn is_empty(&self) -> bool {
1683        self.iter.is_empty()
1684    }
1685}
1686
1687#[stable(feature = "fused", since = "1.26.0")]
1688impl<T> FusedIterator for Iter<'_, T> {}
1689
1690/// An owning iterator over the elements of a `BinaryHeap`.
1691///
1692/// This `struct` is created by [`BinaryHeap::into_iter()`]
1693/// (provided by the [`IntoIterator`] trait). See its documentation for more.
1694///
1695/// [`into_iter`]: BinaryHeap::into_iter
1696#[stable(feature = "rust1", since = "1.0.0")]
1697#[derive(Clone)]
1698pub struct IntoIter<
1699    T,
1700    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1701> {
1702    iter: vec::IntoIter<T, A>,
1703}
1704
1705impl<T, A: Allocator> IntoIter<T, A> {
1706    /// Returns a reference to the underlying allocator.
1707    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1708    pub fn allocator(&self) -> &A {
1709        self.iter.allocator()
1710    }
1711}
1712
1713#[stable(feature = "collection_debug", since = "1.17.0")]
1714impl<T: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<T, A> {
1715    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1716        f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
1717    }
1718}
1719
1720#[stable(feature = "rust1", since = "1.0.0")]
1721impl<T, A: Allocator> Iterator for IntoIter<T, A> {
1722    type Item = T;
1723
1724    #[inline]
1725    fn next(&mut self) -> Option<T> {
1726        self.iter.next()
1727    }
1728
1729    #[inline]
1730    fn size_hint(&self) -> (usize, Option<usize>) {
1731        self.iter.size_hint()
1732    }
1733}
1734
1735#[stable(feature = "rust1", since = "1.0.0")]
1736impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
1737    #[inline]
1738    fn next_back(&mut self) -> Option<T> {
1739        self.iter.next_back()
1740    }
1741}
1742
1743#[stable(feature = "rust1", since = "1.0.0")]
1744impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {
1745    fn is_empty(&self) -> bool {
1746        self.iter.is_empty()
1747    }
1748}
1749
1750#[stable(feature = "fused", since = "1.26.0")]
1751impl<T, A: Allocator> FusedIterator for IntoIter<T, A> {}
1752
1753#[doc(hidden)]
1754#[unstable(issue = "none", feature = "trusted_fused")]
1755unsafe impl<T, A: Allocator> TrustedFused for IntoIter<T, A> {}
1756
1757#[stable(feature = "default_iters", since = "1.70.0")]
1758impl<T> Default for IntoIter<T> {
1759    /// Creates an empty `binary_heap::IntoIter`.
1760    ///
1761    /// ```
1762    /// # use std::collections::binary_heap;
1763    /// let iter: binary_heap::IntoIter<u8> = Default::default();
1764    /// assert_eq!(iter.len(), 0);
1765    /// ```
1766    fn default() -> Self {
1767        IntoIter { iter: Default::default() }
1768    }
1769}
1770
1771// In addition to the SAFETY invariants of the following three unsafe traits
1772// also refer to the vec::in_place_collect module documentation to get an overview
1773#[unstable(issue = "none", feature = "inplace_iteration")]
1774#[doc(hidden)]
1775unsafe impl<T, A: Allocator> SourceIter for IntoIter<T, A> {
1776    type Source = IntoIter<T, A>;
1777
1778    #[inline]
1779    unsafe fn as_inner(&mut self) -> &mut Self::Source {
1780        self
1781    }
1782}
1783
1784#[unstable(issue = "none", feature = "inplace_iteration")]
1785#[doc(hidden)]
1786unsafe impl<I, A: Allocator> InPlaceIterable for IntoIter<I, A> {
1787    const EXPAND_BY: Option<NonZero<usize>> = NonZero::new(1);
1788    const MERGE_BY: Option<NonZero<usize>> = NonZero::new(1);
1789}
1790
1791#[cfg(not(test))]
1792unsafe impl<I> AsVecIntoIter for IntoIter<I> {
1793    type Item = I;
1794
1795    fn as_into_iter(&mut self) -> &mut vec::IntoIter<Self::Item> {
1796        &mut self.iter
1797    }
1798}
1799
1800#[must_use = "iterators are lazy and do nothing unless consumed"]
1801#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1802#[derive(Clone, Debug)]
1803pub struct IntoIterSorted<
1804    T,
1805    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1806> {
1807    inner: BinaryHeap<T, A>,
1808}
1809
1810impl<T, A: Allocator> IntoIterSorted<T, A> {
1811    /// Returns a reference to the underlying allocator.
1812    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1813    pub fn allocator(&self) -> &A {
1814        self.inner.allocator()
1815    }
1816}
1817
1818#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1819impl<T: Ord, A: Allocator> Iterator for IntoIterSorted<T, A> {
1820    type Item = T;
1821
1822    #[inline]
1823    fn next(&mut self) -> Option<T> {
1824        self.inner.pop()
1825    }
1826
1827    #[inline]
1828    fn size_hint(&self) -> (usize, Option<usize>) {
1829        let exact = self.inner.len();
1830        (exact, Some(exact))
1831    }
1832}
1833
1834#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1835impl<T: Ord, A: Allocator> ExactSizeIterator for IntoIterSorted<T, A> {}
1836
1837#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1838impl<T: Ord, A: Allocator> FusedIterator for IntoIterSorted<T, A> {}
1839
1840#[unstable(feature = "trusted_len", issue = "37572")]
1841unsafe impl<T: Ord, A: Allocator> TrustedLen for IntoIterSorted<T, A> {}
1842
1843/// A draining iterator over the elements of a `BinaryHeap`.
1844///
1845/// This `struct` is created by [`BinaryHeap::drain()`]. See its
1846/// documentation for more.
1847///
1848/// [`drain`]: BinaryHeap::drain
1849#[stable(feature = "drain", since = "1.6.0")]
1850#[derive(Debug)]
1851pub struct Drain<
1852    'a,
1853    T: 'a,
1854    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1855> {
1856    iter: vec::Drain<'a, T, A>,
1857}
1858
1859impl<T, A: Allocator> Drain<'_, T, A> {
1860    /// Returns a reference to the underlying allocator.
1861    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1862    pub fn allocator(&self) -> &A {
1863        self.iter.allocator()
1864    }
1865}
1866
1867#[stable(feature = "drain", since = "1.6.0")]
1868impl<T, A: Allocator> Iterator for Drain<'_, T, A> {
1869    type Item = T;
1870
1871    #[inline]
1872    fn next(&mut self) -> Option<T> {
1873        self.iter.next()
1874    }
1875
1876    #[inline]
1877    fn size_hint(&self) -> (usize, Option<usize>) {
1878        self.iter.size_hint()
1879    }
1880}
1881
1882#[stable(feature = "drain", since = "1.6.0")]
1883impl<T, A: Allocator> DoubleEndedIterator for Drain<'_, T, A> {
1884    #[inline]
1885    fn next_back(&mut self) -> Option<T> {
1886        self.iter.next_back()
1887    }
1888}
1889
1890#[stable(feature = "drain", since = "1.6.0")]
1891impl<T, A: Allocator> ExactSizeIterator for Drain<'_, T, A> {
1892    fn is_empty(&self) -> bool {
1893        self.iter.is_empty()
1894    }
1895}
1896
1897#[stable(feature = "fused", since = "1.26.0")]
1898impl<T, A: Allocator> FusedIterator for Drain<'_, T, A> {}
1899
1900/// A draining iterator over the elements of a `BinaryHeap`.
1901///
1902/// This `struct` is created by [`BinaryHeap::drain_sorted()`]. See its
1903/// documentation for more.
1904///
1905/// [`drain_sorted`]: BinaryHeap::drain_sorted
1906#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1907#[derive(Debug)]
1908pub struct DrainSorted<
1909    'a,
1910    T: Ord,
1911    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1912> {
1913    inner: &'a mut BinaryHeap<T, A>,
1914}
1915
1916impl<'a, T: Ord, A: Allocator> DrainSorted<'a, T, A> {
1917    /// Returns a reference to the underlying allocator.
1918    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1919    pub fn allocator(&self) -> &A {
1920        self.inner.allocator()
1921    }
1922}
1923
1924#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1925impl<'a, T: Ord, A: Allocator> Drop for DrainSorted<'a, T, A> {
1926    /// Removes heap elements in heap order.
1927    fn drop(&mut self) {
1928        struct DropGuard<'r, 'a, T: Ord, A: Allocator>(&'r mut DrainSorted<'a, T, A>);
1929
1930        impl<'r, 'a, T: Ord, A: Allocator> Drop for DropGuard<'r, 'a, T, A> {
1931            fn drop(&mut self) {
1932                while self.0.inner.pop().is_some() {}
1933            }
1934        }
1935
1936        while let Some(item) = self.inner.pop() {
1937            let guard = DropGuard(self);
1938            drop(item);
1939            mem::forget(guard);
1940        }
1941    }
1942}
1943
1944#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1945impl<T: Ord, A: Allocator> Iterator for DrainSorted<'_, T, A> {
1946    type Item = T;
1947
1948    #[inline]
1949    fn next(&mut self) -> Option<T> {
1950        self.inner.pop()
1951    }
1952
1953    #[inline]
1954    fn size_hint(&self) -> (usize, Option<usize>) {
1955        let exact = self.inner.len();
1956        (exact, Some(exact))
1957    }
1958}
1959
1960#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1961impl<T: Ord, A: Allocator> ExactSizeIterator for DrainSorted<'_, T, A> {}
1962
1963#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1964impl<T: Ord, A: Allocator> FusedIterator for DrainSorted<'_, T, A> {}
1965
1966#[unstable(feature = "trusted_len", issue = "37572")]
1967unsafe impl<T: Ord, A: Allocator> TrustedLen for DrainSorted<'_, T, A> {}
1968
1969#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1970impl<T: Ord, A: AllocatorNightly> From<Vec<T, A>> for BinaryHeap<T, A> {
1971    /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1972    ///
1973    /// This conversion happens in-place, and has *O*(*n*) time complexity.
1974    fn from(vec: Vec<T, A>) -> BinaryHeap<T, A> {
1975        let mut heap = BinaryHeap { data: vec };
1976        heap.rebuild();
1977        heap
1978    }
1979}
1980
1981#[stable(feature = "std_collections_from_array", since = "1.56.0")]
1982impl<T: Ord, const N: usize> From<[T; N]> for BinaryHeap<T> {
1983    /// ```
1984    /// use std::collections::BinaryHeap;
1985    ///
1986    /// let mut h1 = BinaryHeap::from([1, 4, 2, 3]);
1987    /// let mut h2: BinaryHeap<_> = [1, 4, 2, 3].into();
1988    /// while let Some((a, b)) = h1.pop().zip(h2.pop()) {
1989    ///     assert_eq!(a, b);
1990    /// }
1991    /// ```
1992    fn from(arr: [T; N]) -> Self {
1993        Self::from_iter(arr)
1994    }
1995}
1996
1997#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1998impl<T, A: Allocator> From<BinaryHeap<T, A>> for Vec<T, A> {
1999    /// Converts a `BinaryHeap<T>` into a `Vec<T>`.
2000    ///
2001    /// This conversion requires no data movement or allocation, and has
2002    /// constant time complexity.
2003    fn from(heap: BinaryHeap<T, A>) -> Vec<T, A> {
2004        heap.data
2005    }
2006}
2007
2008#[stable(feature = "rust1", since = "1.0.0")]
2009impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
2010    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
2011        BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
2012    }
2013}
2014
2015#[stable(feature = "rust1", since = "1.0.0")]
2016impl<T, A: Allocator> IntoIterator for BinaryHeap<T, A> {
2017    type Item = T;
2018    type IntoIter = IntoIter<T, A>;
2019
2020    /// Creates a consuming iterator, that is, one that moves each value out of
2021    /// the binary heap in arbitrary order. The binary heap cannot be used
2022    /// after calling this.
2023    ///
2024    /// # Examples
2025    ///
2026    /// Basic usage:
2027    ///
2028    /// ```
2029    /// use std::collections::BinaryHeap;
2030    /// let heap = BinaryHeap::from([1, 2, 3, 4]);
2031    ///
2032    /// // Print 1, 2, 3, 4 in arbitrary order
2033    /// for x in heap.into_iter() {
2034    ///     // x has type i32, not &i32
2035    ///     println!("{x}");
2036    /// }
2037    /// ```
2038    fn into_iter(self) -> IntoIter<T, A> {
2039        IntoIter { iter: self.data.into_iter() }
2040    }
2041}
2042
2043#[stable(feature = "rust1", since = "1.0.0")]
2044impl<'a, T, A: Allocator> IntoIterator for &'a BinaryHeap<T, A> {
2045    type Item = &'a T;
2046    type IntoIter = Iter<'a, T>;
2047
2048    fn into_iter(self) -> Iter<'a, T> {
2049        self.iter()
2050    }
2051}
2052
2053#[stable(feature = "rust1", since = "1.0.0")]
2054impl<T: Ord, A: Allocator> Extend<T> for BinaryHeap<T, A> {
2055    #[inline]
2056    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2057        let guard = RebuildOnDrop { rebuild_from: self.len(), heap: self };
2058        guard.heap.data.extend(iter);
2059    }
2060
2061    #[inline]
2062    fn extend_one(&mut self, item: T) {
2063        self.push(item);
2064    }
2065
2066    #[inline]
2067    fn extend_reserve(&mut self, additional: usize) {
2068        self.reserve(additional);
2069    }
2070}
2071
2072#[stable(feature = "extend_ref", since = "1.2.0")]
2073impl<'a, T: 'a + Ord + Copy, A: Allocator> Extend<&'a T> for BinaryHeap<T, A> {
2074    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2075        self.extend(iter.into_iter().cloned());
2076    }
2077
2078    #[inline]
2079    fn extend_one(&mut self, &item: &'a T) {
2080        self.push(item);
2081    }
2082
2083    #[inline]
2084    fn extend_reserve(&mut self, additional: usize) {
2085        self.reserve(additional);
2086    }
2087}