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