]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/collections/binary_heap.rs
Add diagnostic items
[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 - 1 {
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 - 1 {
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     /// Consumes the `BinaryHeap` and returns the underlying vector
962     /// in arbitrary order.
963     ///
964     /// # Examples
965     ///
966     /// Basic usage:
967     ///
968     /// ```
969     /// use std::collections::BinaryHeap;
970     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
971     /// let vec = heap.into_vec();
972     ///
973     /// // Will print in some order
974     /// for x in vec {
975     ///     println!("{}", x);
976     /// }
977     /// ```
978     #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
979     pub fn into_vec(self) -> Vec<T> {
980         self.into()
981     }
982
983     /// Returns the length of the binary heap.
984     ///
985     /// # Examples
986     ///
987     /// Basic usage:
988     ///
989     /// ```
990     /// use std::collections::BinaryHeap;
991     /// let heap = BinaryHeap::from(vec![1, 3]);
992     ///
993     /// assert_eq!(heap.len(), 2);
994     /// ```
995     #[doc(alias = "length")]
996     #[stable(feature = "rust1", since = "1.0.0")]
997     pub fn len(&self) -> usize {
998         self.data.len()
999     }
1000
1001     /// Checks if the binary heap is empty.
1002     ///
1003     /// # Examples
1004     ///
1005     /// Basic usage:
1006     ///
1007     /// ```
1008     /// use std::collections::BinaryHeap;
1009     /// let mut heap = BinaryHeap::new();
1010     ///
1011     /// assert!(heap.is_empty());
1012     ///
1013     /// heap.push(3);
1014     /// heap.push(5);
1015     /// heap.push(1);
1016     ///
1017     /// assert!(!heap.is_empty());
1018     /// ```
1019     #[stable(feature = "rust1", since = "1.0.0")]
1020     pub fn is_empty(&self) -> bool {
1021         self.len() == 0
1022     }
1023
1024     /// Clears the binary heap, returning an iterator over the removed elements.
1025     ///
1026     /// The elements are removed in arbitrary order.
1027     ///
1028     /// # Examples
1029     ///
1030     /// Basic usage:
1031     ///
1032     /// ```
1033     /// use std::collections::BinaryHeap;
1034     /// let mut heap = BinaryHeap::from(vec![1, 3]);
1035     ///
1036     /// assert!(!heap.is_empty());
1037     ///
1038     /// for x in heap.drain() {
1039     ///     println!("{}", x);
1040     /// }
1041     ///
1042     /// assert!(heap.is_empty());
1043     /// ```
1044     #[inline]
1045     #[stable(feature = "drain", since = "1.6.0")]
1046     pub fn drain(&mut self) -> Drain<'_, T> {
1047         Drain { iter: self.data.drain(..) }
1048     }
1049
1050     /// Drops all items from the binary heap.
1051     ///
1052     /// # Examples
1053     ///
1054     /// Basic usage:
1055     ///
1056     /// ```
1057     /// use std::collections::BinaryHeap;
1058     /// let mut heap = BinaryHeap::from(vec![1, 3]);
1059     ///
1060     /// assert!(!heap.is_empty());
1061     ///
1062     /// heap.clear();
1063     ///
1064     /// assert!(heap.is_empty());
1065     /// ```
1066     #[stable(feature = "rust1", since = "1.0.0")]
1067     pub fn clear(&mut self) {
1068         self.drain();
1069     }
1070 }
1071
1072 /// Hole represents a hole in a slice i.e., an index without valid value
1073 /// (because it was moved from or duplicated).
1074 /// In drop, `Hole` will restore the slice by filling the hole
1075 /// position with the value that was originally removed.
1076 struct Hole<'a, T: 'a> {
1077     data: &'a mut [T],
1078     elt: ManuallyDrop<T>,
1079     pos: usize,
1080 }
1081
1082 impl<'a, T> Hole<'a, T> {
1083     /// Create a new `Hole` at index `pos`.
1084     ///
1085     /// Unsafe because pos must be within the data slice.
1086     #[inline]
1087     unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
1088         debug_assert!(pos < data.len());
1089         // SAFE: pos should be inside the slice
1090         let elt = unsafe { ptr::read(data.get_unchecked(pos)) };
1091         Hole { data, elt: ManuallyDrop::new(elt), pos }
1092     }
1093
1094     #[inline]
1095     fn pos(&self) -> usize {
1096         self.pos
1097     }
1098
1099     /// Returns a reference to the element removed.
1100     #[inline]
1101     fn element(&self) -> &T {
1102         &self.elt
1103     }
1104
1105     /// Returns a reference to the element at `index`.
1106     ///
1107     /// Unsafe because index must be within the data slice and not equal to pos.
1108     #[inline]
1109     unsafe fn get(&self, index: usize) -> &T {
1110         debug_assert!(index != self.pos);
1111         debug_assert!(index < self.data.len());
1112         unsafe { self.data.get_unchecked(index) }
1113     }
1114
1115     /// Move hole to new location
1116     ///
1117     /// Unsafe because index must be within the data slice and not equal to pos.
1118     #[inline]
1119     unsafe fn move_to(&mut self, index: usize) {
1120         debug_assert!(index != self.pos);
1121         debug_assert!(index < self.data.len());
1122         unsafe {
1123             let ptr = self.data.as_mut_ptr();
1124             let index_ptr: *const _ = ptr.add(index);
1125             let hole_ptr = ptr.add(self.pos);
1126             ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1127         }
1128         self.pos = index;
1129     }
1130 }
1131
1132 impl<T> Drop for Hole<'_, T> {
1133     #[inline]
1134     fn drop(&mut self) {
1135         // fill the hole again
1136         unsafe {
1137             let pos = self.pos;
1138             ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
1139         }
1140     }
1141 }
1142
1143 /// An iterator over the elements of a `BinaryHeap`.
1144 ///
1145 /// This `struct` is created by [`BinaryHeap::iter()`]. See its
1146 /// documentation for more.
1147 ///
1148 /// [`iter`]: BinaryHeap::iter
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 pub struct Iter<'a, T: 'a> {
1151     iter: slice::Iter<'a, T>,
1152 }
1153
1154 #[stable(feature = "collection_debug", since = "1.17.0")]
1155 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1156     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1157         f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
1158     }
1159 }
1160
1161 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 impl<T> Clone for Iter<'_, T> {
1164     fn clone(&self) -> Self {
1165         Iter { iter: self.iter.clone() }
1166     }
1167 }
1168
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 impl<'a, T> Iterator for Iter<'a, T> {
1171     type Item = &'a T;
1172
1173     #[inline]
1174     fn next(&mut self) -> Option<&'a T> {
1175         self.iter.next()
1176     }
1177
1178     #[inline]
1179     fn size_hint(&self) -> (usize, Option<usize>) {
1180         self.iter.size_hint()
1181     }
1182
1183     #[inline]
1184     fn last(self) -> Option<&'a T> {
1185         self.iter.last()
1186     }
1187 }
1188
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1191     #[inline]
1192     fn next_back(&mut self) -> Option<&'a T> {
1193         self.iter.next_back()
1194     }
1195 }
1196
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 impl<T> ExactSizeIterator for Iter<'_, T> {
1199     fn is_empty(&self) -> bool {
1200         self.iter.is_empty()
1201     }
1202 }
1203
1204 #[stable(feature = "fused", since = "1.26.0")]
1205 impl<T> FusedIterator for Iter<'_, T> {}
1206
1207 /// An owning iterator over the elements of a `BinaryHeap`.
1208 ///
1209 /// This `struct` is created by [`BinaryHeap::into_iter()`]
1210 /// (provided by the `IntoIterator` trait). See its documentation for more.
1211 ///
1212 /// [`into_iter`]: BinaryHeap::into_iter
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 #[derive(Clone)]
1215 pub struct IntoIter<T> {
1216     iter: vec::IntoIter<T>,
1217 }
1218
1219 #[stable(feature = "collection_debug", since = "1.17.0")]
1220 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1221     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1222         f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
1223     }
1224 }
1225
1226 #[stable(feature = "rust1", since = "1.0.0")]
1227 impl<T> Iterator for IntoIter<T> {
1228     type Item = T;
1229
1230     #[inline]
1231     fn next(&mut self) -> Option<T> {
1232         self.iter.next()
1233     }
1234
1235     #[inline]
1236     fn size_hint(&self) -> (usize, Option<usize>) {
1237         self.iter.size_hint()
1238     }
1239 }
1240
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 impl<T> DoubleEndedIterator for IntoIter<T> {
1243     #[inline]
1244     fn next_back(&mut self) -> Option<T> {
1245         self.iter.next_back()
1246     }
1247 }
1248
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 impl<T> ExactSizeIterator for IntoIter<T> {
1251     fn is_empty(&self) -> bool {
1252         self.iter.is_empty()
1253     }
1254 }
1255
1256 #[stable(feature = "fused", since = "1.26.0")]
1257 impl<T> FusedIterator for IntoIter<T> {}
1258
1259 #[unstable(issue = "none", feature = "inplace_iteration")]
1260 unsafe impl<T> SourceIter for IntoIter<T> {
1261     type Source = IntoIter<T>;
1262
1263     #[inline]
1264     unsafe fn as_inner(&mut self) -> &mut Self::Source {
1265         self
1266     }
1267 }
1268
1269 #[unstable(issue = "none", feature = "inplace_iteration")]
1270 unsafe impl<I> InPlaceIterable for IntoIter<I> {}
1271
1272 impl<I> AsIntoIter for IntoIter<I> {
1273     type Item = I;
1274
1275     fn as_into_iter(&mut self) -> &mut vec::IntoIter<Self::Item> {
1276         &mut self.iter
1277     }
1278 }
1279
1280 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1281 #[derive(Clone, Debug)]
1282 pub struct IntoIterSorted<T> {
1283     inner: BinaryHeap<T>,
1284 }
1285
1286 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1287 impl<T: Ord> Iterator for IntoIterSorted<T> {
1288     type Item = T;
1289
1290     #[inline]
1291     fn next(&mut self) -> Option<T> {
1292         self.inner.pop()
1293     }
1294
1295     #[inline]
1296     fn size_hint(&self) -> (usize, Option<usize>) {
1297         let exact = self.inner.len();
1298         (exact, Some(exact))
1299     }
1300 }
1301
1302 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1303 impl<T: Ord> ExactSizeIterator for IntoIterSorted<T> {}
1304
1305 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1306 impl<T: Ord> FusedIterator for IntoIterSorted<T> {}
1307
1308 #[unstable(feature = "trusted_len", issue = "37572")]
1309 unsafe impl<T: Ord> TrustedLen for IntoIterSorted<T> {}
1310
1311 /// A draining iterator over the elements of a `BinaryHeap`.
1312 ///
1313 /// This `struct` is created by [`BinaryHeap::drain()`]. See its
1314 /// documentation for more.
1315 ///
1316 /// [`drain`]: BinaryHeap::drain
1317 #[stable(feature = "drain", since = "1.6.0")]
1318 #[derive(Debug)]
1319 pub struct Drain<'a, T: 'a> {
1320     iter: vec::Drain<'a, T>,
1321 }
1322
1323 #[stable(feature = "drain", since = "1.6.0")]
1324 impl<T> Iterator for Drain<'_, T> {
1325     type Item = T;
1326
1327     #[inline]
1328     fn next(&mut self) -> Option<T> {
1329         self.iter.next()
1330     }
1331
1332     #[inline]
1333     fn size_hint(&self) -> (usize, Option<usize>) {
1334         self.iter.size_hint()
1335     }
1336 }
1337
1338 #[stable(feature = "drain", since = "1.6.0")]
1339 impl<T> DoubleEndedIterator for Drain<'_, T> {
1340     #[inline]
1341     fn next_back(&mut self) -> Option<T> {
1342         self.iter.next_back()
1343     }
1344 }
1345
1346 #[stable(feature = "drain", since = "1.6.0")]
1347 impl<T> ExactSizeIterator for Drain<'_, T> {
1348     fn is_empty(&self) -> bool {
1349         self.iter.is_empty()
1350     }
1351 }
1352
1353 #[stable(feature = "fused", since = "1.26.0")]
1354 impl<T> FusedIterator for Drain<'_, T> {}
1355
1356 /// A draining iterator over the elements of a `BinaryHeap`.
1357 ///
1358 /// This `struct` is created by [`BinaryHeap::drain_sorted()`]. See its
1359 /// documentation for more.
1360 ///
1361 /// [`drain_sorted`]: BinaryHeap::drain_sorted
1362 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1363 #[derive(Debug)]
1364 pub struct DrainSorted<'a, T: Ord> {
1365     inner: &'a mut BinaryHeap<T>,
1366 }
1367
1368 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1369 impl<'a, T: Ord> Drop for DrainSorted<'a, T> {
1370     /// Removes heap elements in heap order.
1371     fn drop(&mut self) {
1372         struct DropGuard<'r, 'a, T: Ord>(&'r mut DrainSorted<'a, T>);
1373
1374         impl<'r, 'a, T: Ord> Drop for DropGuard<'r, 'a, T> {
1375             fn drop(&mut self) {
1376                 while self.0.inner.pop().is_some() {}
1377             }
1378         }
1379
1380         while let Some(item) = self.inner.pop() {
1381             let guard = DropGuard(self);
1382             drop(item);
1383             mem::forget(guard);
1384         }
1385     }
1386 }
1387
1388 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1389 impl<T: Ord> Iterator for DrainSorted<'_, T> {
1390     type Item = T;
1391
1392     #[inline]
1393     fn next(&mut self) -> Option<T> {
1394         self.inner.pop()
1395     }
1396
1397     #[inline]
1398     fn size_hint(&self) -> (usize, Option<usize>) {
1399         let exact = self.inner.len();
1400         (exact, Some(exact))
1401     }
1402 }
1403
1404 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1405 impl<T: Ord> ExactSizeIterator for DrainSorted<'_, T> {}
1406
1407 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1408 impl<T: Ord> FusedIterator for DrainSorted<'_, T> {}
1409
1410 #[unstable(feature = "trusted_len", issue = "37572")]
1411 unsafe impl<T: Ord> TrustedLen for DrainSorted<'_, T> {}
1412
1413 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1414 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1415     /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1416     ///
1417     /// This conversion happens in-place, and has *O*(*n*) time complexity.
1418     fn from(vec: Vec<T>) -> BinaryHeap<T> {
1419         let mut heap = BinaryHeap { data: vec };
1420         heap.rebuild();
1421         heap
1422     }
1423 }
1424
1425 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1426 impl<T> From<BinaryHeap<T>> for Vec<T> {
1427     /// Converts a `BinaryHeap<T>` into a `Vec<T>`.
1428     ///
1429     /// This conversion requires no data movement or allocation, and has
1430     /// constant time complexity.
1431     fn from(heap: BinaryHeap<T>) -> Vec<T> {
1432         heap.data
1433     }
1434 }
1435
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1438     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1439         BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1440     }
1441 }
1442
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl<T> IntoIterator for BinaryHeap<T> {
1445     type Item = T;
1446     type IntoIter = IntoIter<T>;
1447
1448     /// Creates a consuming iterator, that is, one that moves each value out of
1449     /// the binary heap in arbitrary order. The binary heap cannot be used
1450     /// after calling this.
1451     ///
1452     /// # Examples
1453     ///
1454     /// Basic usage:
1455     ///
1456     /// ```
1457     /// use std::collections::BinaryHeap;
1458     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1459     ///
1460     /// // Print 1, 2, 3, 4 in arbitrary order
1461     /// for x in heap.into_iter() {
1462     ///     // x has type i32, not &i32
1463     ///     println!("{}", x);
1464     /// }
1465     /// ```
1466     fn into_iter(self) -> IntoIter<T> {
1467         IntoIter { iter: self.data.into_iter() }
1468     }
1469 }
1470
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 impl<'a, T> IntoIterator for &'a BinaryHeap<T> {
1473     type Item = &'a T;
1474     type IntoIter = Iter<'a, T>;
1475
1476     fn into_iter(self) -> Iter<'a, T> {
1477         self.iter()
1478     }
1479 }
1480
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1483     #[inline]
1484     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1485         <Self as SpecExtend<I>>::spec_extend(self, iter);
1486     }
1487
1488     #[inline]
1489     fn extend_one(&mut self, item: T) {
1490         self.push(item);
1491     }
1492
1493     #[inline]
1494     fn extend_reserve(&mut self, additional: usize) {
1495         self.reserve(additional);
1496     }
1497 }
1498
1499 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1500     default fn spec_extend(&mut self, iter: I) {
1501         self.extend_desugared(iter.into_iter());
1502     }
1503 }
1504
1505 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1506     fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1507         self.append(other);
1508     }
1509 }
1510
1511 impl<T: Ord> BinaryHeap<T> {
1512     fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1513         let iterator = iter.into_iter();
1514         let (lower, _) = iterator.size_hint();
1515
1516         self.reserve(lower);
1517
1518         iterator.for_each(move |elem| self.push(elem));
1519     }
1520 }
1521
1522 #[stable(feature = "extend_ref", since = "1.2.0")]
1523 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1524     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1525         self.extend(iter.into_iter().cloned());
1526     }
1527
1528     #[inline]
1529     fn extend_one(&mut self, &item: &'a T) {
1530         self.push(item);
1531     }
1532
1533     #[inline]
1534     fn extend_reserve(&mut self, additional: usize) {
1535         self.reserve(additional);
1536     }
1537 }