]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/collections/binary_heap.rs
Stabilize File::options()
[rust.git] / library / alloc / src / collections / binary_heap.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 the 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
146 use core::fmt;
147 use core::iter::{FromIterator, FusedIterator, InPlaceIterable, SourceIter, TrustedLen};
148 use core::mem::{self, swap, ManuallyDrop};
149 use core::ops::{Deref, DerefMut};
150 use core::ptr;
151
152 use crate::slice;
153 use crate::vec::{self, AsIntoIter, Vec};
154
155 use super::SpecExtend;
156
157 /// A priority queue implemented with a binary heap.
158 ///
159 /// This will be a max-heap.
160 ///
161 /// It is a logic error for an item to be modified in such a way that the
162 /// item's ordering relative to any other item, as determined by the [`Ord`]
163 /// trait, changes while it is in the heap. This is normally only possible
164 /// through [`Cell`], [`RefCell`], global state, I/O, or unsafe code. The
165 /// behavior resulting from such a logic error is not specified (it
166 /// could include panics, incorrect results, aborts, memory leaks, or
167 /// non-termination) but will not be undefined behavior.
168 ///
169 /// # Examples
170 ///
171 /// ```
172 /// use std::collections::BinaryHeap;
173 ///
174 /// // Type inference lets us omit an explicit type signature (which
175 /// // would be `BinaryHeap<i32>` in this example).
176 /// let mut heap = BinaryHeap::new();
177 ///
178 /// // We can use peek to look at the next item in the heap. In this case,
179 /// // there's no items in there yet so we get None.
180 /// assert_eq!(heap.peek(), None);
181 ///
182 /// // Let's add some scores...
183 /// heap.push(1);
184 /// heap.push(5);
185 /// heap.push(2);
186 ///
187 /// // Now peek shows the most important item in the heap.
188 /// assert_eq!(heap.peek(), Some(&5));
189 ///
190 /// // We can check the length of a heap.
191 /// assert_eq!(heap.len(), 3);
192 ///
193 /// // We can iterate over the items in the heap, although they are returned in
194 /// // a random order.
195 /// for x in &heap {
196 ///     println!("{}", x);
197 /// }
198 ///
199 /// // If we instead pop these scores, they should come back in order.
200 /// assert_eq!(heap.pop(), Some(5));
201 /// assert_eq!(heap.pop(), Some(2));
202 /// assert_eq!(heap.pop(), Some(1));
203 /// assert_eq!(heap.pop(), None);
204 ///
205 /// // We can clear the heap of any remaining items.
206 /// heap.clear();
207 ///
208 /// // The heap should now be empty.
209 /// assert!(heap.is_empty())
210 /// ```
211 ///
212 /// A `BinaryHeap` with a known list of items can be initialized from an array:
213 ///
214 /// ```
215 /// use std::collections::BinaryHeap;
216 ///
217 /// let heap = BinaryHeap::from([1, 5, 2]);
218 /// ```
219 ///
220 /// ## Min-heap
221 ///
222 /// Either [`core::cmp::Reverse`] or a custom [`Ord`] implementation can be used to
223 /// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest
224 /// value instead of the greatest one.
225 ///
226 /// ```
227 /// use std::collections::BinaryHeap;
228 /// use std::cmp::Reverse;
229 ///
230 /// let mut heap = BinaryHeap::new();
231 ///
232 /// // Wrap values in `Reverse`
233 /// heap.push(Reverse(1));
234 /// heap.push(Reverse(5));
235 /// heap.push(Reverse(2));
236 ///
237 /// // If we pop these scores now, they should come back in the reverse order.
238 /// assert_eq!(heap.pop(), Some(Reverse(1)));
239 /// assert_eq!(heap.pop(), Some(Reverse(2)));
240 /// assert_eq!(heap.pop(), Some(Reverse(5)));
241 /// assert_eq!(heap.pop(), None);
242 /// ```
243 ///
244 /// # Time complexity
245 ///
246 /// | [push]  | [pop]         | [peek]/[peek\_mut] |
247 /// |---------|---------------|--------------------|
248 /// | *O*(1)~ | *O*(log(*n*)) | *O*(1)             |
249 ///
250 /// The value for `push` is an expected cost; the method documentation gives a
251 /// more detailed analysis.
252 ///
253 /// [`core::cmp::Reverse`]: core::cmp::Reverse
254 /// [`Ord`]: core::cmp::Ord
255 /// [`Cell`]: core::cell::Cell
256 /// [`RefCell`]: core::cell::RefCell
257 /// [push]: BinaryHeap::push
258 /// [pop]: BinaryHeap::pop
259 /// [peek]: BinaryHeap::peek
260 /// [peek\_mut]: BinaryHeap::peek_mut
261 #[stable(feature = "rust1", since = "1.0.0")]
262 #[cfg_attr(not(test), rustc_diagnostic_item = "BinaryHeap")]
263 pub struct BinaryHeap<T> {
264     data: Vec<T>,
265 }
266
267 /// Structure wrapping a mutable reference to the greatest item on a
268 /// `BinaryHeap`.
269 ///
270 /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
271 /// its documentation for more.
272 ///
273 /// [`peek_mut`]: BinaryHeap::peek_mut
274 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
275 pub struct PeekMut<'a, T: 'a + Ord> {
276     heap: &'a mut BinaryHeap<T>,
277     sift: bool,
278 }
279
280 #[stable(feature = "collection_debug", since = "1.17.0")]
281 impl<T: Ord + fmt::Debug> fmt::Debug for PeekMut<'_, T> {
282     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283         f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish()
284     }
285 }
286
287 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
288 impl<T: Ord> Drop for PeekMut<'_, T> {
289     fn drop(&mut self) {
290         if self.sift {
291             // SAFETY: PeekMut is only instantiated for non-empty heaps.
292             unsafe { self.heap.sift_down(0) };
293         }
294     }
295 }
296
297 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
298 impl<T: Ord> Deref for PeekMut<'_, T> {
299     type Target = T;
300     fn deref(&self) -> &T {
301         debug_assert!(!self.heap.is_empty());
302         // SAFE: PeekMut is only instantiated for non-empty heaps
303         unsafe { self.heap.data.get_unchecked(0) }
304     }
305 }
306
307 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
308 impl<T: Ord> DerefMut for PeekMut<'_, T> {
309     fn deref_mut(&mut self) -> &mut T {
310         debug_assert!(!self.heap.is_empty());
311         self.sift = true;
312         // SAFE: PeekMut is only instantiated for non-empty heaps
313         unsafe { self.heap.data.get_unchecked_mut(0) }
314     }
315 }
316
317 impl<'a, T: Ord> PeekMut<'a, T> {
318     /// Removes the peeked value from the heap and returns it.
319     #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
320     pub fn pop(mut this: PeekMut<'a, T>) -> T {
321         let value = this.heap.pop().unwrap();
322         this.sift = false;
323         value
324     }
325 }
326
327 #[stable(feature = "rust1", since = "1.0.0")]
328 impl<T: Clone> Clone for BinaryHeap<T> {
329     fn clone(&self) -> Self {
330         BinaryHeap { data: self.data.clone() }
331     }
332
333     fn clone_from(&mut self, source: &Self) {
334         self.data.clone_from(&source.data);
335     }
336 }
337
338 #[stable(feature = "rust1", since = "1.0.0")]
339 impl<T: Ord> Default for BinaryHeap<T> {
340     /// Creates an empty `BinaryHeap<T>`.
341     #[inline]
342     fn default() -> BinaryHeap<T> {
343         BinaryHeap::new()
344     }
345 }
346
347 #[stable(feature = "binaryheap_debug", since = "1.4.0")]
348 impl<T: fmt::Debug> fmt::Debug for BinaryHeap<T> {
349     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350         f.debug_list().entries(self.iter()).finish()
351     }
352 }
353
354 impl<T: Ord> BinaryHeap<T> {
355     /// Creates an empty `BinaryHeap` as a max-heap.
356     ///
357     /// # Examples
358     ///
359     /// Basic usage:
360     ///
361     /// ```
362     /// use std::collections::BinaryHeap;
363     /// let mut heap = BinaryHeap::new();
364     /// heap.push(4);
365     /// ```
366     #[stable(feature = "rust1", since = "1.0.0")]
367     #[must_use]
368     pub fn new() -> BinaryHeap<T> {
369         BinaryHeap { data: vec![] }
370     }
371
372     /// Creates an empty `BinaryHeap` with a specific capacity.
373     /// This preallocates enough memory for `capacity` elements,
374     /// so that the `BinaryHeap` does not have to be reallocated
375     /// until it contains at least that many values.
376     ///
377     /// # Examples
378     ///
379     /// Basic usage:
380     ///
381     /// ```
382     /// use std::collections::BinaryHeap;
383     /// let mut heap = BinaryHeap::with_capacity(10);
384     /// heap.push(4);
385     /// ```
386     #[stable(feature = "rust1", since = "1.0.0")]
387     #[must_use]
388     pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
389         BinaryHeap { data: Vec::with_capacity(capacity) }
390     }
391
392     /// Returns a mutable reference to the greatest item in the binary heap, or
393     /// `None` if it is empty.
394     ///
395     /// Note: If the `PeekMut` value is leaked, the heap may be in an
396     /// inconsistent state.
397     ///
398     /// # Examples
399     ///
400     /// Basic usage:
401     ///
402     /// ```
403     /// use std::collections::BinaryHeap;
404     /// let mut heap = BinaryHeap::new();
405     /// assert!(heap.peek_mut().is_none());
406     ///
407     /// heap.push(1);
408     /// heap.push(5);
409     /// heap.push(2);
410     /// {
411     ///     let mut val = heap.peek_mut().unwrap();
412     ///     *val = 0;
413     /// }
414     /// assert_eq!(heap.peek(), Some(&2));
415     /// ```
416     ///
417     /// # Time complexity
418     ///
419     /// If the item is modified then the worst case time complexity is *O*(log(*n*)),
420     /// otherwise it's *O*(1).
421     #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
422     pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T>> {
423         if self.is_empty() { None } else { Some(PeekMut { heap: self, sift: false }) }
424     }
425
426     /// Removes the greatest item from the binary heap and returns it, or `None` if it
427     /// is empty.
428     ///
429     /// # Examples
430     ///
431     /// Basic usage:
432     ///
433     /// ```
434     /// use std::collections::BinaryHeap;
435     /// let mut heap = BinaryHeap::from(vec![1, 3]);
436     ///
437     /// assert_eq!(heap.pop(), Some(3));
438     /// assert_eq!(heap.pop(), Some(1));
439     /// assert_eq!(heap.pop(), None);
440     /// ```
441     ///
442     /// # Time complexity
443     ///
444     /// The worst case cost of `pop` on a heap containing *n* elements is *O*(log(*n*)).
445     #[stable(feature = "rust1", since = "1.0.0")]
446     pub fn pop(&mut self) -> Option<T> {
447         self.data.pop().map(|mut item| {
448             if !self.is_empty() {
449                 swap(&mut item, &mut self.data[0]);
450                 // SAFETY: !self.is_empty() means that self.len() > 0
451                 unsafe { self.sift_down_to_bottom(0) };
452             }
453             item
454         })
455     }
456
457     /// Pushes an item onto the binary heap.
458     ///
459     /// # Examples
460     ///
461     /// Basic usage:
462     ///
463     /// ```
464     /// use std::collections::BinaryHeap;
465     /// let mut heap = BinaryHeap::new();
466     /// heap.push(3);
467     /// heap.push(5);
468     /// heap.push(1);
469     ///
470     /// assert_eq!(heap.len(), 3);
471     /// assert_eq!(heap.peek(), Some(&5));
472     /// ```
473     ///
474     /// # Time complexity
475     ///
476     /// The expected cost of `push`, averaged over every possible ordering of
477     /// the elements being pushed, and over a sufficiently large number of
478     /// pushes, is *O*(1). This is the most meaningful cost metric when pushing
479     /// elements that are *not* already in any sorted pattern.
480     ///
481     /// The time complexity degrades if elements are pushed in predominantly
482     /// ascending order. In the worst case, elements are pushed in ascending
483     /// sorted order and the amortized cost per push is *O*(log(*n*)) against a heap
484     /// containing *n* elements.
485     ///
486     /// The worst case cost of a *single* call to `push` is *O*(*n*). The worst case
487     /// occurs when capacity is exhausted and needs a resize. The resize cost
488     /// has been amortized in the previous figures.
489     #[stable(feature = "rust1", since = "1.0.0")]
490     pub fn push(&mut self, item: T) {
491         let old_len = self.len();
492         self.data.push(item);
493         // SAFETY: Since we pushed a new item it means that
494         //  old_len = self.len() - 1 < self.len()
495         unsafe { self.sift_up(0, old_len) };
496     }
497
498     /// Consumes the `BinaryHeap` and returns a vector in sorted
499     /// (ascending) order.
500     ///
501     /// # Examples
502     ///
503     /// Basic usage:
504     ///
505     /// ```
506     /// use std::collections::BinaryHeap;
507     ///
508     /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
509     /// heap.push(6);
510     /// heap.push(3);
511     ///
512     /// let vec = heap.into_sorted_vec();
513     /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
514     /// ```
515     #[must_use = "`self` will be dropped if the result is not used"]
516     #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
517     pub fn into_sorted_vec(mut self) -> Vec<T> {
518         let mut end = self.len();
519         while end > 1 {
520             end -= 1;
521             // SAFETY: `end` goes from `self.len() - 1` to 1 (both included),
522             //  so it's always a valid index to access.
523             //  It is safe to access index 0 (i.e. `ptr`), because
524             //  1 <= end < self.len(), which means self.len() >= 2.
525             unsafe {
526                 let ptr = self.data.as_mut_ptr();
527                 ptr::swap(ptr, ptr.add(end));
528             }
529             // SAFETY: `end` goes from `self.len() - 1` to 1 (both included) so:
530             //  0 < 1 <= end <= self.len() - 1 < self.len()
531             //  Which means 0 < end and end < self.len().
532             unsafe { self.sift_down_range(0, end) };
533         }
534         self.into_vec()
535     }
536
537     // The implementations of sift_up and sift_down use unsafe blocks in
538     // order to move an element out of the vector (leaving behind a
539     // hole), shift along the others and move the removed element back into the
540     // vector at the final location of the hole.
541     // The `Hole` type is used to represent this, and make sure
542     // the hole is filled back at the end of its scope, even on panic.
543     // Using a hole reduces the constant factor compared to using swaps,
544     // which involves twice as many moves.
545
546     /// # Safety
547     ///
548     /// The caller must guarantee that `pos < self.len()`.
549     unsafe fn sift_up(&mut self, start: usize, pos: usize) -> usize {
550         // Take out the value at `pos` and create a hole.
551         // SAFETY: The caller guarantees that pos < self.len()
552         let mut hole = unsafe { Hole::new(&mut self.data, pos) };
553
554         while hole.pos() > start {
555             let parent = (hole.pos() - 1) / 2;
556
557             // SAFETY: hole.pos() > start >= 0, which means hole.pos() > 0
558             //  and so hole.pos() - 1 can't underflow.
559             //  This guarantees that parent < hole.pos() so
560             //  it's a valid index and also != hole.pos().
561             if hole.element() <= unsafe { hole.get(parent) } {
562                 break;
563             }
564
565             // SAFETY: Same as above
566             unsafe { hole.move_to(parent) };
567         }
568
569         hole.pos()
570     }
571
572     /// Take an element at `pos` and move it down the heap,
573     /// while its children are larger.
574     ///
575     /// # Safety
576     ///
577     /// The caller must guarantee that `pos < end <= self.len()`.
578     unsafe fn sift_down_range(&mut self, pos: usize, end: usize) {
579         // SAFETY: The caller guarantees that pos < end <= self.len().
580         let mut hole = unsafe { Hole::new(&mut self.data, pos) };
581         let mut child = 2 * hole.pos() + 1;
582
583         // Loop invariant: child == 2 * hole.pos() + 1.
584         while child <= end.saturating_sub(2) {
585             // compare with the greater of the two children
586             // SAFETY: child < end - 1 < self.len() and
587             //  child + 1 < end <= self.len(), so they're valid indexes.
588             //  child == 2 * hole.pos() + 1 != hole.pos() and
589             //  child + 1 == 2 * hole.pos() + 2 != hole.pos().
590             // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
591             //  if T is a ZST
592             child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
593
594             // if we are already in order, stop.
595             // SAFETY: child is now either the old child or the old child+1
596             //  We already proven that both are < self.len() and != hole.pos()
597             if hole.element() >= unsafe { hole.get(child) } {
598                 return;
599             }
600
601             // SAFETY: same as above.
602             unsafe { hole.move_to(child) };
603             child = 2 * hole.pos() + 1;
604         }
605
606         // SAFETY: && short circuit, which means that in the
607         //  second condition it's already true that child == end - 1 < self.len().
608         if child == end - 1 && hole.element() < unsafe { hole.get(child) } {
609             // SAFETY: child is already proven to be a valid index and
610             //  child == 2 * hole.pos() + 1 != hole.pos().
611             unsafe { hole.move_to(child) };
612         }
613     }
614
615     /// # Safety
616     ///
617     /// The caller must guarantee that `pos < self.len()`.
618     unsafe fn sift_down(&mut self, pos: usize) {
619         let len = self.len();
620         // SAFETY: pos < len is guaranteed by the caller and
621         //  obviously len = self.len() <= self.len().
622         unsafe { self.sift_down_range(pos, len) };
623     }
624
625     /// Take an element at `pos` and move it all the way down the heap,
626     /// then sift it up to its position.
627     ///
628     /// Note: This is faster when the element is known to be large / should
629     /// be closer to the bottom.
630     ///
631     /// # Safety
632     ///
633     /// The caller must guarantee that `pos < self.len()`.
634     unsafe fn sift_down_to_bottom(&mut self, mut pos: usize) {
635         let end = self.len();
636         let start = pos;
637
638         // SAFETY: The caller guarantees that pos < self.len().
639         let mut hole = unsafe { Hole::new(&mut self.data, pos) };
640         let mut child = 2 * hole.pos() + 1;
641
642         // Loop invariant: child == 2 * hole.pos() + 1.
643         while child <= end.saturating_sub(2) {
644             // SAFETY: child < end - 1 < self.len() and
645             //  child + 1 < end <= self.len(), so they're valid indexes.
646             //  child == 2 * hole.pos() + 1 != hole.pos() and
647             //  child + 1 == 2 * hole.pos() + 2 != hole.pos().
648             // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
649             //  if T is a ZST
650             child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
651
652             // SAFETY: Same as above
653             unsafe { hole.move_to(child) };
654             child = 2 * hole.pos() + 1;
655         }
656
657         if child == end - 1 {
658             // SAFETY: child == end - 1 < self.len(), so it's a valid index
659             //  and child == 2 * hole.pos() + 1 != hole.pos().
660             unsafe { hole.move_to(child) };
661         }
662         pos = hole.pos();
663         drop(hole);
664
665         // SAFETY: pos is the position in the hole and was already proven
666         //  to be a valid index.
667         unsafe { self.sift_up(start, pos) };
668     }
669
670     /// Rebuild assuming data[0..start] is still a proper heap.
671     fn rebuild_tail(&mut self, start: usize) {
672         if start == self.len() {
673             return;
674         }
675
676         let tail_len = self.len() - start;
677
678         #[inline(always)]
679         fn log2_fast(x: usize) -> usize {
680             (usize::BITS - x.leading_zeros() - 1) as usize
681         }
682
683         // `rebuild` takes O(self.len()) operations
684         // and about 2 * self.len() comparisons in the worst case
685         // while repeating `sift_up` takes O(tail_len * log(start)) operations
686         // and about 1 * tail_len * log_2(start) comparisons in the worst case,
687         // assuming start >= tail_len. For larger heaps, the crossover point
688         // no longer follows this reasoning and was determined empirically.
689         let better_to_rebuild = if start < tail_len {
690             true
691         } else if self.len() <= 2048 {
692             2 * self.len() < tail_len * log2_fast(start)
693         } else {
694             2 * self.len() < tail_len * 11
695         };
696
697         if better_to_rebuild {
698             self.rebuild();
699         } else {
700             for i in start..self.len() {
701                 // SAFETY: The index `i` is always less than self.len().
702                 unsafe { self.sift_up(0, i) };
703             }
704         }
705     }
706
707     fn rebuild(&mut self) {
708         let mut n = self.len() / 2;
709         while n > 0 {
710             n -= 1;
711             // SAFETY: n starts from self.len() / 2 and goes down to 0.
712             //  The only case when !(n < self.len()) is if
713             //  self.len() == 0, but it's ruled out by the loop condition.
714             unsafe { self.sift_down(n) };
715         }
716     }
717
718     /// Moves all the elements of `other` into `self`, leaving `other` empty.
719     ///
720     /// # Examples
721     ///
722     /// Basic usage:
723     ///
724     /// ```
725     /// use std::collections::BinaryHeap;
726     ///
727     /// let v = vec![-10, 1, 2, 3, 3];
728     /// let mut a = BinaryHeap::from(v);
729     ///
730     /// let v = vec![-20, 5, 43];
731     /// let mut b = BinaryHeap::from(v);
732     ///
733     /// a.append(&mut b);
734     ///
735     /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
736     /// assert!(b.is_empty());
737     /// ```
738     #[stable(feature = "binary_heap_append", since = "1.11.0")]
739     pub fn append(&mut self, other: &mut Self) {
740         if self.len() < other.len() {
741             swap(self, other);
742         }
743
744         let start = self.data.len();
745
746         self.data.append(&mut other.data);
747
748         self.rebuild_tail(start);
749     }
750
751     /// Returns an iterator which retrieves elements in heap order.
752     /// The retrieved elements are removed from the original heap.
753     /// The remaining elements will be removed on drop in heap order.
754     ///
755     /// Note:
756     /// * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`.
757     ///   You should use the latter for most cases.
758     ///
759     /// # Examples
760     ///
761     /// Basic usage:
762     ///
763     /// ```
764     /// #![feature(binary_heap_drain_sorted)]
765     /// use std::collections::BinaryHeap;
766     ///
767     /// let mut heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]);
768     /// assert_eq!(heap.len(), 5);
769     ///
770     /// drop(heap.drain_sorted()); // removes all elements in heap order
771     /// assert_eq!(heap.len(), 0);
772     /// ```
773     #[inline]
774     #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
775     pub fn drain_sorted(&mut self) -> DrainSorted<'_, T> {
776         DrainSorted { inner: self }
777     }
778
779     /// Retains only the elements specified by the predicate.
780     ///
781     /// In other words, remove all elements `e` such that `f(&e)` returns
782     /// `false`. The elements are visited in unsorted (and unspecified) order.
783     ///
784     /// # Examples
785     ///
786     /// Basic usage:
787     ///
788     /// ```
789     /// #![feature(binary_heap_retain)]
790     /// use std::collections::BinaryHeap;
791     ///
792     /// let mut heap = BinaryHeap::from(vec![-10, -5, 1, 2, 4, 13]);
793     ///
794     /// heap.retain(|x| x % 2 == 0); // only keep even numbers
795     ///
796     /// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
797     /// ```
798     #[unstable(feature = "binary_heap_retain", issue = "71503")]
799     pub fn retain<F>(&mut self, mut f: F)
800     where
801         F: FnMut(&T) -> bool,
802     {
803         let mut first_removed = self.len();
804         let mut i = 0;
805         self.data.retain(|e| {
806             let keep = f(e);
807             if !keep && i < first_removed {
808                 first_removed = i;
809             }
810             i += 1;
811             keep
812         });
813         // data[0..first_removed] is untouched, so we only need to rebuild the tail:
814         self.rebuild_tail(first_removed);
815     }
816 }
817
818 impl<T> BinaryHeap<T> {
819     /// Returns an iterator visiting all values in the underlying vector, in
820     /// arbitrary order.
821     ///
822     /// # Examples
823     ///
824     /// Basic usage:
825     ///
826     /// ```
827     /// use std::collections::BinaryHeap;
828     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
829     ///
830     /// // Print 1, 2, 3, 4 in arbitrary order
831     /// for x in heap.iter() {
832     ///     println!("{}", x);
833     /// }
834     /// ```
835     #[stable(feature = "rust1", since = "1.0.0")]
836     pub fn iter(&self) -> Iter<'_, T> {
837         Iter { iter: self.data.iter() }
838     }
839
840     /// Returns an iterator which retrieves elements in heap order.
841     /// This method consumes the original heap.
842     ///
843     /// # Examples
844     ///
845     /// Basic usage:
846     ///
847     /// ```
848     /// #![feature(binary_heap_into_iter_sorted)]
849     /// use std::collections::BinaryHeap;
850     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]);
851     ///
852     /// assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), vec![5, 4]);
853     /// ```
854     #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
855     pub fn into_iter_sorted(self) -> IntoIterSorted<T> {
856         IntoIterSorted { inner: self }
857     }
858
859     /// Returns the greatest item in the binary heap, or `None` if it is empty.
860     ///
861     /// # Examples
862     ///
863     /// Basic usage:
864     ///
865     /// ```
866     /// use std::collections::BinaryHeap;
867     /// let mut heap = BinaryHeap::new();
868     /// assert_eq!(heap.peek(), None);
869     ///
870     /// heap.push(1);
871     /// heap.push(5);
872     /// heap.push(2);
873     /// assert_eq!(heap.peek(), Some(&5));
874     ///
875     /// ```
876     ///
877     /// # Time complexity
878     ///
879     /// Cost is *O*(1) in the worst case.
880     #[must_use]
881     #[stable(feature = "rust1", since = "1.0.0")]
882     pub fn peek(&self) -> Option<&T> {
883         self.data.get(0)
884     }
885
886     /// Returns the number of elements the binary heap can hold without reallocating.
887     ///
888     /// # Examples
889     ///
890     /// Basic usage:
891     ///
892     /// ```
893     /// use std::collections::BinaryHeap;
894     /// let mut heap = BinaryHeap::with_capacity(100);
895     /// assert!(heap.capacity() >= 100);
896     /// heap.push(4);
897     /// ```
898     #[must_use]
899     #[stable(feature = "rust1", since = "1.0.0")]
900     pub fn capacity(&self) -> usize {
901         self.data.capacity()
902     }
903
904     /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
905     /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
906     ///
907     /// Note that the allocator may give the collection more space than it requests. Therefore
908     /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
909     /// insertions are expected.
910     ///
911     /// # Panics
912     ///
913     /// Panics if the new capacity overflows `usize`.
914     ///
915     /// # Examples
916     ///
917     /// Basic usage:
918     ///
919     /// ```
920     /// use std::collections::BinaryHeap;
921     /// let mut heap = BinaryHeap::new();
922     /// heap.reserve_exact(100);
923     /// assert!(heap.capacity() >= 100);
924     /// heap.push(4);
925     /// ```
926     ///
927     /// [`reserve`]: BinaryHeap::reserve
928     #[stable(feature = "rust1", since = "1.0.0")]
929     pub fn reserve_exact(&mut self, additional: usize) {
930         self.data.reserve_exact(additional);
931     }
932
933     /// Reserves capacity for at least `additional` more elements to be inserted in the
934     /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
935     ///
936     /// # Panics
937     ///
938     /// Panics if the new capacity overflows `usize`.
939     ///
940     /// # Examples
941     ///
942     /// Basic usage:
943     ///
944     /// ```
945     /// use std::collections::BinaryHeap;
946     /// let mut heap = BinaryHeap::new();
947     /// heap.reserve(100);
948     /// assert!(heap.capacity() >= 100);
949     /// heap.push(4);
950     /// ```
951     #[stable(feature = "rust1", since = "1.0.0")]
952     pub fn reserve(&mut self, additional: usize) {
953         self.data.reserve(additional);
954     }
955
956     /// Discards as much additional capacity as possible.
957     ///
958     /// # Examples
959     ///
960     /// Basic usage:
961     ///
962     /// ```
963     /// use std::collections::BinaryHeap;
964     /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
965     ///
966     /// assert!(heap.capacity() >= 100);
967     /// heap.shrink_to_fit();
968     /// assert!(heap.capacity() == 0);
969     /// ```
970     #[stable(feature = "rust1", since = "1.0.0")]
971     pub fn shrink_to_fit(&mut self) {
972         self.data.shrink_to_fit();
973     }
974
975     /// Discards capacity with a lower bound.
976     ///
977     /// The capacity will remain at least as large as both the length
978     /// and the supplied value.
979     ///
980     /// If the current capacity is less than the lower limit, this is a no-op.
981     ///
982     /// # Examples
983     ///
984     /// ```
985     /// use std::collections::BinaryHeap;
986     /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
987     ///
988     /// assert!(heap.capacity() >= 100);
989     /// heap.shrink_to(10);
990     /// assert!(heap.capacity() >= 10);
991     /// ```
992     #[inline]
993     #[stable(feature = "shrink_to", since = "1.56.0")]
994     pub fn shrink_to(&mut self, min_capacity: usize) {
995         self.data.shrink_to(min_capacity)
996     }
997
998     /// Returns a slice of all values in the underlying vector, in arbitrary
999     /// order.
1000     ///
1001     /// # Examples
1002     ///
1003     /// Basic usage:
1004     ///
1005     /// ```
1006     /// #![feature(binary_heap_as_slice)]
1007     /// use std::collections::BinaryHeap;
1008     /// use std::io::{self, Write};
1009     ///
1010     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
1011     ///
1012     /// io::sink().write(heap.as_slice()).unwrap();
1013     /// ```
1014     #[must_use]
1015     #[unstable(feature = "binary_heap_as_slice", issue = "83659")]
1016     pub fn as_slice(&self) -> &[T] {
1017         self.data.as_slice()
1018     }
1019
1020     /// Consumes the `BinaryHeap` and returns the underlying vector
1021     /// in arbitrary order.
1022     ///
1023     /// # Examples
1024     ///
1025     /// Basic usage:
1026     ///
1027     /// ```
1028     /// use std::collections::BinaryHeap;
1029     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
1030     /// let vec = heap.into_vec();
1031     ///
1032     /// // Will print in some order
1033     /// for x in vec {
1034     ///     println!("{}", x);
1035     /// }
1036     /// ```
1037     #[must_use = "`self` will be dropped if the result is not used"]
1038     #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1039     pub fn into_vec(self) -> Vec<T> {
1040         self.into()
1041     }
1042
1043     /// Returns the length of the binary heap.
1044     ///
1045     /// # Examples
1046     ///
1047     /// Basic usage:
1048     ///
1049     /// ```
1050     /// use std::collections::BinaryHeap;
1051     /// let heap = BinaryHeap::from(vec![1, 3]);
1052     ///
1053     /// assert_eq!(heap.len(), 2);
1054     /// ```
1055     #[must_use]
1056     #[stable(feature = "rust1", since = "1.0.0")]
1057     pub fn len(&self) -> usize {
1058         self.data.len()
1059     }
1060
1061     /// Checks if the binary heap is empty.
1062     ///
1063     /// # Examples
1064     ///
1065     /// Basic usage:
1066     ///
1067     /// ```
1068     /// use std::collections::BinaryHeap;
1069     /// let mut heap = BinaryHeap::new();
1070     ///
1071     /// assert!(heap.is_empty());
1072     ///
1073     /// heap.push(3);
1074     /// heap.push(5);
1075     /// heap.push(1);
1076     ///
1077     /// assert!(!heap.is_empty());
1078     /// ```
1079     #[must_use]
1080     #[stable(feature = "rust1", since = "1.0.0")]
1081     pub fn is_empty(&self) -> bool {
1082         self.len() == 0
1083     }
1084
1085     /// Clears the binary heap, returning an iterator over the removed elements.
1086     ///
1087     /// The elements are removed in arbitrary order.
1088     ///
1089     /// # Examples
1090     ///
1091     /// Basic usage:
1092     ///
1093     /// ```
1094     /// use std::collections::BinaryHeap;
1095     /// let mut heap = BinaryHeap::from(vec![1, 3]);
1096     ///
1097     /// assert!(!heap.is_empty());
1098     ///
1099     /// for x in heap.drain() {
1100     ///     println!("{}", x);
1101     /// }
1102     ///
1103     /// assert!(heap.is_empty());
1104     /// ```
1105     #[inline]
1106     #[stable(feature = "drain", since = "1.6.0")]
1107     pub fn drain(&mut self) -> Drain<'_, T> {
1108         Drain { iter: self.data.drain(..) }
1109     }
1110
1111     /// Drops all items from the binary heap.
1112     ///
1113     /// # Examples
1114     ///
1115     /// Basic usage:
1116     ///
1117     /// ```
1118     /// use std::collections::BinaryHeap;
1119     /// let mut heap = BinaryHeap::from(vec![1, 3]);
1120     ///
1121     /// assert!(!heap.is_empty());
1122     ///
1123     /// heap.clear();
1124     ///
1125     /// assert!(heap.is_empty());
1126     /// ```
1127     #[stable(feature = "rust1", since = "1.0.0")]
1128     pub fn clear(&mut self) {
1129         self.drain();
1130     }
1131 }
1132
1133 /// Hole represents a hole in a slice i.e., an index without valid value
1134 /// (because it was moved from or duplicated).
1135 /// In drop, `Hole` will restore the slice by filling the hole
1136 /// position with the value that was originally removed.
1137 struct Hole<'a, T: 'a> {
1138     data: &'a mut [T],
1139     elt: ManuallyDrop<T>,
1140     pos: usize,
1141 }
1142
1143 impl<'a, T> Hole<'a, T> {
1144     /// Create a new `Hole` at index `pos`.
1145     ///
1146     /// Unsafe because pos must be within the data slice.
1147     #[inline]
1148     unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
1149         debug_assert!(pos < data.len());
1150         // SAFE: pos should be inside the slice
1151         let elt = unsafe { ptr::read(data.get_unchecked(pos)) };
1152         Hole { data, elt: ManuallyDrop::new(elt), pos }
1153     }
1154
1155     #[inline]
1156     fn pos(&self) -> usize {
1157         self.pos
1158     }
1159
1160     /// Returns a reference to the element removed.
1161     #[inline]
1162     fn element(&self) -> &T {
1163         &self.elt
1164     }
1165
1166     /// Returns a reference to the element at `index`.
1167     ///
1168     /// Unsafe because index must be within the data slice and not equal to pos.
1169     #[inline]
1170     unsafe fn get(&self, index: usize) -> &T {
1171         debug_assert!(index != self.pos);
1172         debug_assert!(index < self.data.len());
1173         unsafe { self.data.get_unchecked(index) }
1174     }
1175
1176     /// Move hole to new location
1177     ///
1178     /// Unsafe because index must be within the data slice and not equal to pos.
1179     #[inline]
1180     unsafe fn move_to(&mut self, index: usize) {
1181         debug_assert!(index != self.pos);
1182         debug_assert!(index < self.data.len());
1183         unsafe {
1184             let ptr = self.data.as_mut_ptr();
1185             let index_ptr: *const _ = ptr.add(index);
1186             let hole_ptr = ptr.add(self.pos);
1187             ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1188         }
1189         self.pos = index;
1190     }
1191 }
1192
1193 impl<T> Drop for Hole<'_, T> {
1194     #[inline]
1195     fn drop(&mut self) {
1196         // fill the hole again
1197         unsafe {
1198             let pos = self.pos;
1199             ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
1200         }
1201     }
1202 }
1203
1204 /// An iterator over the elements of a `BinaryHeap`.
1205 ///
1206 /// This `struct` is created by [`BinaryHeap::iter()`]. See its
1207 /// documentation for more.
1208 ///
1209 /// [`iter`]: BinaryHeap::iter
1210 #[must_use = "iterators are lazy and do nothing unless consumed"]
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 pub struct Iter<'a, T: 'a> {
1213     iter: slice::Iter<'a, T>,
1214 }
1215
1216 #[stable(feature = "collection_debug", since = "1.17.0")]
1217 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1218     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1219         f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
1220     }
1221 }
1222
1223 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 impl<T> Clone for Iter<'_, T> {
1226     fn clone(&self) -> Self {
1227         Iter { iter: self.iter.clone() }
1228     }
1229 }
1230
1231 #[stable(feature = "rust1", since = "1.0.0")]
1232 impl<'a, T> Iterator for Iter<'a, T> {
1233     type Item = &'a T;
1234
1235     #[inline]
1236     fn next(&mut self) -> Option<&'a T> {
1237         self.iter.next()
1238     }
1239
1240     #[inline]
1241     fn size_hint(&self) -> (usize, Option<usize>) {
1242         self.iter.size_hint()
1243     }
1244
1245     #[inline]
1246     fn last(self) -> Option<&'a T> {
1247         self.iter.last()
1248     }
1249 }
1250
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1253     #[inline]
1254     fn next_back(&mut self) -> Option<&'a T> {
1255         self.iter.next_back()
1256     }
1257 }
1258
1259 #[stable(feature = "rust1", since = "1.0.0")]
1260 impl<T> ExactSizeIterator for Iter<'_, T> {
1261     fn is_empty(&self) -> bool {
1262         self.iter.is_empty()
1263     }
1264 }
1265
1266 #[stable(feature = "fused", since = "1.26.0")]
1267 impl<T> FusedIterator for Iter<'_, T> {}
1268
1269 /// An owning iterator over the elements of a `BinaryHeap`.
1270 ///
1271 /// This `struct` is created by [`BinaryHeap::into_iter()`]
1272 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
1273 ///
1274 /// [`into_iter`]: BinaryHeap::into_iter
1275 /// [`IntoIterator`]: core::iter::IntoIterator
1276 #[stable(feature = "rust1", since = "1.0.0")]
1277 #[derive(Clone)]
1278 pub struct IntoIter<T> {
1279     iter: vec::IntoIter<T>,
1280 }
1281
1282 #[stable(feature = "collection_debug", since = "1.17.0")]
1283 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1284     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1285         f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
1286     }
1287 }
1288
1289 #[stable(feature = "rust1", since = "1.0.0")]
1290 impl<T> Iterator for IntoIter<T> {
1291     type Item = T;
1292
1293     #[inline]
1294     fn next(&mut self) -> Option<T> {
1295         self.iter.next()
1296     }
1297
1298     #[inline]
1299     fn size_hint(&self) -> (usize, Option<usize>) {
1300         self.iter.size_hint()
1301     }
1302 }
1303
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 impl<T> DoubleEndedIterator for IntoIter<T> {
1306     #[inline]
1307     fn next_back(&mut self) -> Option<T> {
1308         self.iter.next_back()
1309     }
1310 }
1311
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 impl<T> ExactSizeIterator for IntoIter<T> {
1314     fn is_empty(&self) -> bool {
1315         self.iter.is_empty()
1316     }
1317 }
1318
1319 #[stable(feature = "fused", since = "1.26.0")]
1320 impl<T> FusedIterator for IntoIter<T> {}
1321
1322 #[unstable(issue = "none", feature = "inplace_iteration")]
1323 #[doc(hidden)]
1324 unsafe impl<T> SourceIter for IntoIter<T> {
1325     type Source = IntoIter<T>;
1326
1327     #[inline]
1328     unsafe fn as_inner(&mut self) -> &mut Self::Source {
1329         self
1330     }
1331 }
1332
1333 #[unstable(issue = "none", feature = "inplace_iteration")]
1334 #[doc(hidden)]
1335 unsafe impl<I> InPlaceIterable for IntoIter<I> {}
1336
1337 impl<I> AsIntoIter for IntoIter<I> {
1338     type Item = I;
1339
1340     fn as_into_iter(&mut self) -> &mut vec::IntoIter<Self::Item> {
1341         &mut self.iter
1342     }
1343 }
1344
1345 #[must_use = "iterators are lazy and do nothing unless consumed"]
1346 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1347 #[derive(Clone, Debug)]
1348 pub struct IntoIterSorted<T> {
1349     inner: BinaryHeap<T>,
1350 }
1351
1352 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1353 impl<T: Ord> Iterator for IntoIterSorted<T> {
1354     type Item = T;
1355
1356     #[inline]
1357     fn next(&mut self) -> Option<T> {
1358         self.inner.pop()
1359     }
1360
1361     #[inline]
1362     fn size_hint(&self) -> (usize, Option<usize>) {
1363         let exact = self.inner.len();
1364         (exact, Some(exact))
1365     }
1366 }
1367
1368 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1369 impl<T: Ord> ExactSizeIterator for IntoIterSorted<T> {}
1370
1371 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1372 impl<T: Ord> FusedIterator for IntoIterSorted<T> {}
1373
1374 #[unstable(feature = "trusted_len", issue = "37572")]
1375 unsafe impl<T: Ord> TrustedLen for IntoIterSorted<T> {}
1376
1377 /// A draining iterator over the elements of a `BinaryHeap`.
1378 ///
1379 /// This `struct` is created by [`BinaryHeap::drain()`]. See its
1380 /// documentation for more.
1381 ///
1382 /// [`drain`]: BinaryHeap::drain
1383 #[stable(feature = "drain", since = "1.6.0")]
1384 #[derive(Debug)]
1385 pub struct Drain<'a, T: 'a> {
1386     iter: vec::Drain<'a, T>,
1387 }
1388
1389 #[stable(feature = "drain", since = "1.6.0")]
1390 impl<T> Iterator for Drain<'_, T> {
1391     type Item = T;
1392
1393     #[inline]
1394     fn next(&mut self) -> Option<T> {
1395         self.iter.next()
1396     }
1397
1398     #[inline]
1399     fn size_hint(&self) -> (usize, Option<usize>) {
1400         self.iter.size_hint()
1401     }
1402 }
1403
1404 #[stable(feature = "drain", since = "1.6.0")]
1405 impl<T> DoubleEndedIterator for Drain<'_, T> {
1406     #[inline]
1407     fn next_back(&mut self) -> Option<T> {
1408         self.iter.next_back()
1409     }
1410 }
1411
1412 #[stable(feature = "drain", since = "1.6.0")]
1413 impl<T> ExactSizeIterator for Drain<'_, T> {
1414     fn is_empty(&self) -> bool {
1415         self.iter.is_empty()
1416     }
1417 }
1418
1419 #[stable(feature = "fused", since = "1.26.0")]
1420 impl<T> FusedIterator for Drain<'_, T> {}
1421
1422 /// A draining iterator over the elements of a `BinaryHeap`.
1423 ///
1424 /// This `struct` is created by [`BinaryHeap::drain_sorted()`]. See its
1425 /// documentation for more.
1426 ///
1427 /// [`drain_sorted`]: BinaryHeap::drain_sorted
1428 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1429 #[derive(Debug)]
1430 pub struct DrainSorted<'a, T: Ord> {
1431     inner: &'a mut BinaryHeap<T>,
1432 }
1433
1434 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1435 impl<'a, T: Ord> Drop for DrainSorted<'a, T> {
1436     /// Removes heap elements in heap order.
1437     fn drop(&mut self) {
1438         struct DropGuard<'r, 'a, T: Ord>(&'r mut DrainSorted<'a, T>);
1439
1440         impl<'r, 'a, T: Ord> Drop for DropGuard<'r, 'a, T> {
1441             fn drop(&mut self) {
1442                 while self.0.inner.pop().is_some() {}
1443             }
1444         }
1445
1446         while let Some(item) = self.inner.pop() {
1447             let guard = DropGuard(self);
1448             drop(item);
1449             mem::forget(guard);
1450         }
1451     }
1452 }
1453
1454 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1455 impl<T: Ord> Iterator for DrainSorted<'_, T> {
1456     type Item = T;
1457
1458     #[inline]
1459     fn next(&mut self) -> Option<T> {
1460         self.inner.pop()
1461     }
1462
1463     #[inline]
1464     fn size_hint(&self) -> (usize, Option<usize>) {
1465         let exact = self.inner.len();
1466         (exact, Some(exact))
1467     }
1468 }
1469
1470 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1471 impl<T: Ord> ExactSizeIterator for DrainSorted<'_, T> {}
1472
1473 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1474 impl<T: Ord> FusedIterator for DrainSorted<'_, T> {}
1475
1476 #[unstable(feature = "trusted_len", issue = "37572")]
1477 unsafe impl<T: Ord> TrustedLen for DrainSorted<'_, T> {}
1478
1479 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1480 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1481     /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1482     ///
1483     /// This conversion happens in-place, and has *O*(*n*) time complexity.
1484     fn from(vec: Vec<T>) -> BinaryHeap<T> {
1485         let mut heap = BinaryHeap { data: vec };
1486         heap.rebuild();
1487         heap
1488     }
1489 }
1490
1491 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1492 impl<T: Ord, const N: usize> From<[T; N]> for BinaryHeap<T> {
1493     /// ```
1494     /// use std::collections::BinaryHeap;
1495     ///
1496     /// let mut h1 = BinaryHeap::from([1, 4, 2, 3]);
1497     /// let mut h2: BinaryHeap<_> = [1, 4, 2, 3].into();
1498     /// while let Some((a, b)) = h1.pop().zip(h2.pop()) {
1499     ///     assert_eq!(a, b);
1500     /// }
1501     /// ```
1502     fn from(arr: [T; N]) -> Self {
1503         core::array::IntoIter::new(arr).collect()
1504     }
1505 }
1506
1507 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1508 impl<T> From<BinaryHeap<T>> for Vec<T> {
1509     /// Converts a `BinaryHeap<T>` into a `Vec<T>`.
1510     ///
1511     /// This conversion requires no data movement or allocation, and has
1512     /// constant time complexity.
1513     fn from(heap: BinaryHeap<T>) -> Vec<T> {
1514         heap.data
1515     }
1516 }
1517
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1520     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1521         BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1522     }
1523 }
1524
1525 #[stable(feature = "rust1", since = "1.0.0")]
1526 impl<T> IntoIterator for BinaryHeap<T> {
1527     type Item = T;
1528     type IntoIter = IntoIter<T>;
1529
1530     /// Creates a consuming iterator, that is, one that moves each value out of
1531     /// the binary heap in arbitrary order. The binary heap cannot be used
1532     /// after calling this.
1533     ///
1534     /// # Examples
1535     ///
1536     /// Basic usage:
1537     ///
1538     /// ```
1539     /// use std::collections::BinaryHeap;
1540     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1541     ///
1542     /// // Print 1, 2, 3, 4 in arbitrary order
1543     /// for x in heap.into_iter() {
1544     ///     // x has type i32, not &i32
1545     ///     println!("{}", x);
1546     /// }
1547     /// ```
1548     fn into_iter(self) -> IntoIter<T> {
1549         IntoIter { iter: self.data.into_iter() }
1550     }
1551 }
1552
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 impl<'a, T> IntoIterator for &'a BinaryHeap<T> {
1555     type Item = &'a T;
1556     type IntoIter = Iter<'a, T>;
1557
1558     fn into_iter(self) -> Iter<'a, T> {
1559         self.iter()
1560     }
1561 }
1562
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1565     #[inline]
1566     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1567         <Self as SpecExtend<I>>::spec_extend(self, iter);
1568     }
1569
1570     #[inline]
1571     fn extend_one(&mut self, item: T) {
1572         self.push(item);
1573     }
1574
1575     #[inline]
1576     fn extend_reserve(&mut self, additional: usize) {
1577         self.reserve(additional);
1578     }
1579 }
1580
1581 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1582     default fn spec_extend(&mut self, iter: I) {
1583         self.extend_desugared(iter.into_iter());
1584     }
1585 }
1586
1587 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1588     fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1589         self.append(other);
1590     }
1591 }
1592
1593 impl<T: Ord> BinaryHeap<T> {
1594     fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1595         let iterator = iter.into_iter();
1596         let (lower, _) = iterator.size_hint();
1597
1598         self.reserve(lower);
1599
1600         iterator.for_each(move |elem| self.push(elem));
1601     }
1602 }
1603
1604 #[stable(feature = "extend_ref", since = "1.2.0")]
1605 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1606     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1607         self.extend(iter.into_iter().cloned());
1608     }
1609
1610     #[inline]
1611     fn extend_one(&mut self, &item: &'a T) {
1612         self.push(item);
1613     }
1614
1615     #[inline]
1616     fn extend_reserve(&mut self, additional: usize) {
1617         self.reserve(additional);
1618     }
1619 }