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