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