]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/collections/binary_heap.rs
Rollup merge of #75837 - GuillaumeGomez:fix-font-color-help-button, r=Cldfire
[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 //! [`BinaryHeap`]: struct.BinaryHeap.html
19 //!
20 //! ```
21 //! use std::cmp::Ordering;
22 //! use std::collections::BinaryHeap;
23 //!
24 //! #[derive(Copy, Clone, Eq, PartialEq)]
25 //! struct State {
26 //!     cost: usize,
27 //!     position: usize,
28 //! }
29 //!
30 //! // The priority queue depends on `Ord`.
31 //! // Explicitly implement the trait so the queue becomes a min-heap
32 //! // instead of a max-heap.
33 //! impl Ord for State {
34 //!     fn cmp(&self, other: &State) -> Ordering {
35 //!         // Notice that the we flip the ordering on costs.
36 //!         // In case of a tie we compare positions - this step is necessary
37 //!         // to make implementations of `PartialEq` and `Ord` consistent.
38 //!         other.cost.cmp(&self.cost)
39 //!             .then_with(|| self.position.cmp(&other.position))
40 //!     }
41 //! }
42 //!
43 //! // `PartialOrd` needs to be implemented as well.
44 //! impl PartialOrd for State {
45 //!     fn partial_cmp(&self, other: &State) -> Option<Ordering> {
46 //!         Some(self.cmp(other))
47 //!     }
48 //! }
49 //!
50 //! // Each node is represented as an `usize`, for a shorter implementation.
51 //! struct Edge {
52 //!     node: usize,
53 //!     cost: usize,
54 //! }
55 //!
56 //! // Dijkstra's shortest path algorithm.
57 //!
58 //! // Start at `start` and use `dist` to track the current shortest distance
59 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
60 //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
61 //! // for a simpler implementation.
62 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
63 //!     // dist[node] = current shortest distance from `start` to `node`
64 //!     let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
65 //!
66 //!     let mut heap = BinaryHeap::new();
67 //!
68 //!     // We're at `start`, with a zero cost
69 //!     dist[start] = 0;
70 //!     heap.push(State { cost: 0, position: start });
71 //!
72 //!     // Examine the frontier with lower cost nodes first (min-heap)
73 //!     while let Some(State { cost, position }) = heap.pop() {
74 //!         // Alternatively we could have continued to find all shortest paths
75 //!         if position == goal { return Some(cost); }
76 //!
77 //!         // Important as we may have already found a better way
78 //!         if cost > dist[position] { continue; }
79 //!
80 //!         // For each node we can reach, see if we can find a way with
81 //!         // a lower cost going through this node
82 //!         for edge in &adj_list[position] {
83 //!             let next = State { cost: cost + edge.cost, position: edge.node };
84 //!
85 //!             // If so, add it to the frontier and continue
86 //!             if next.cost < dist[next.position] {
87 //!                 heap.push(next);
88 //!                 // Relaxation, we have now found a better way
89 //!                 dist[next.position] = next.cost;
90 //!             }
91 //!         }
92 //!     }
93 //!
94 //!     // Goal not reachable
95 //!     None
96 //! }
97 //!
98 //! fn main() {
99 //!     // This is the directed graph we're going to use.
100 //!     // The node numbers correspond to the different states,
101 //!     // and the edge weights symbolize the cost of moving
102 //!     // from one node to another.
103 //!     // Note that the edges are one-way.
104 //!     //
105 //!     //                  7
106 //!     //          +-----------------+
107 //!     //          |                 |
108 //!     //          v   1        2    |  2
109 //!     //          0 -----> 1 -----> 3 ---> 4
110 //!     //          |        ^        ^      ^
111 //!     //          |        | 1      |      |
112 //!     //          |        |        | 3    | 1
113 //!     //          +------> 2 -------+      |
114 //!     //           10      |               |
115 //!     //                   +---------------+
116 //!     //
117 //!     // The graph is represented as an adjacency list where each index,
118 //!     // corresponding to a node value, has a list of outgoing edges.
119 //!     // Chosen for its efficiency.
120 //!     let graph = vec![
121 //!         // Node 0
122 //!         vec![Edge { node: 2, cost: 10 },
123 //!              Edge { node: 1, cost: 1 }],
124 //!         // Node 1
125 //!         vec![Edge { node: 3, cost: 2 }],
126 //!         // Node 2
127 //!         vec![Edge { node: 1, cost: 1 },
128 //!              Edge { node: 3, cost: 3 },
129 //!              Edge { node: 4, cost: 1 }],
130 //!         // Node 3
131 //!         vec![Edge { node: 0, cost: 7 },
132 //!              Edge { node: 4, cost: 2 }],
133 //!         // Node 4
134 //!         vec![]];
135 //!
136 //!     assert_eq!(shortest_path(&graph, 0, 1), Some(1));
137 //!     assert_eq!(shortest_path(&graph, 0, 3), Some(3));
138 //!     assert_eq!(shortest_path(&graph, 3, 0), Some(7));
139 //!     assert_eq!(shortest_path(&graph, 0, 4), Some(5));
140 //!     assert_eq!(shortest_path(&graph, 4, 0), None);
141 //! }
142 //! ```
143
144 #![allow(missing_docs)]
145 #![stable(feature = "rust1", since = "1.0.0")]
146
147 use core::fmt;
148 use core::iter::{FromIterator, FusedIterator, TrustedLen};
149 use core::mem::{self, size_of, swap, ManuallyDrop};
150 use core::ops::{Deref, DerefMut};
151 use core::ptr;
152
153 use crate::slice;
154 use crate::vec::{self, Vec};
155
156 use super::SpecExtend;
157
158 /// A priority queue implemented with a binary heap.
159 ///
160 /// This will be a max-heap.
161 ///
162 /// It is a logic error for an item to be modified in such a way that the
163 /// item's ordering relative to any other item, as determined by the `Ord`
164 /// trait, changes while it is in the heap. This is normally only possible
165 /// through `Cell`, `RefCell`, global state, I/O, or unsafe code.
166 ///
167 /// # Examples
168 ///
169 /// ```
170 /// use std::collections::BinaryHeap;
171 ///
172 /// // Type inference lets us omit an explicit type signature (which
173 /// // would be `BinaryHeap<i32>` in this example).
174 /// let mut heap = BinaryHeap::new();
175 ///
176 /// // We can use peek to look at the next item in the heap. In this case,
177 /// // there's no items in there yet so we get None.
178 /// assert_eq!(heap.peek(), None);
179 ///
180 /// // Let's add some scores...
181 /// heap.push(1);
182 /// heap.push(5);
183 /// heap.push(2);
184 ///
185 /// // Now peek shows the most important item in the heap.
186 /// assert_eq!(heap.peek(), Some(&5));
187 ///
188 /// // We can check the length of a heap.
189 /// assert_eq!(heap.len(), 3);
190 ///
191 /// // We can iterate over the items in the heap, although they are returned in
192 /// // a random order.
193 /// for x in &heap {
194 ///     println!("{}", x);
195 /// }
196 ///
197 /// // If we instead pop these scores, they should come back in order.
198 /// assert_eq!(heap.pop(), Some(5));
199 /// assert_eq!(heap.pop(), Some(2));
200 /// assert_eq!(heap.pop(), Some(1));
201 /// assert_eq!(heap.pop(), None);
202 ///
203 /// // We can clear the heap of any remaining items.
204 /// heap.clear();
205 ///
206 /// // The heap should now be empty.
207 /// assert!(heap.is_empty())
208 /// ```
209 ///
210 /// ## Min-heap
211 ///
212 /// Either `std::cmp::Reverse` or a custom `Ord` implementation can be used to
213 /// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest
214 /// value instead of the greatest one.
215 ///
216 /// ```
217 /// use std::collections::BinaryHeap;
218 /// use std::cmp::Reverse;
219 ///
220 /// let mut heap = BinaryHeap::new();
221 ///
222 /// // Wrap values in `Reverse`
223 /// heap.push(Reverse(1));
224 /// heap.push(Reverse(5));
225 /// heap.push(Reverse(2));
226 ///
227 /// // If we pop these scores now, they should come back in the reverse order.
228 /// assert_eq!(heap.pop(), Some(Reverse(1)));
229 /// assert_eq!(heap.pop(), Some(Reverse(2)));
230 /// assert_eq!(heap.pop(), Some(Reverse(5)));
231 /// assert_eq!(heap.pop(), None);
232 /// ```
233 ///
234 /// # Time complexity
235 ///
236 /// | [push] | [pop]     | [peek]/[peek\_mut] |
237 /// |--------|-----------|--------------------|
238 /// | O(1)~  | *O*(log(*n*)) | *O*(1)               |
239 ///
240 /// The value for `push` is an expected cost; the method documentation gives a
241 /// more detailed analysis.
242 ///
243 /// [push]: #method.push
244 /// [pop]: #method.pop
245 /// [peek]: #method.peek
246 /// [peek\_mut]: #method.peek_mut
247 #[stable(feature = "rust1", since = "1.0.0")]
248 pub struct BinaryHeap<T> {
249     data: Vec<T>,
250 }
251
252 /// Structure wrapping a mutable reference to the greatest item on a
253 /// `BinaryHeap`.
254 ///
255 /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
256 /// its documentation for more.
257 ///
258 /// [`peek_mut`]: struct.BinaryHeap.html#method.peek_mut
259 /// [`BinaryHeap`]: struct.BinaryHeap.html
260 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
261 pub struct PeekMut<'a, T: 'a + Ord> {
262     heap: &'a mut BinaryHeap<T>,
263     sift: bool,
264 }
265
266 #[stable(feature = "collection_debug", since = "1.17.0")]
267 impl<T: Ord + fmt::Debug> fmt::Debug for PeekMut<'_, T> {
268     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269         f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish()
270     }
271 }
272
273 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
274 impl<T: Ord> Drop for PeekMut<'_, T> {
275     fn drop(&mut self) {
276         if self.sift {
277             self.heap.sift_down(0);
278         }
279     }
280 }
281
282 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
283 impl<T: Ord> Deref for PeekMut<'_, T> {
284     type Target = T;
285     fn deref(&self) -> &T {
286         debug_assert!(!self.heap.is_empty());
287         // SAFE: PeekMut is only instantiated for non-empty heaps
288         unsafe { self.heap.data.get_unchecked(0) }
289     }
290 }
291
292 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
293 impl<T: Ord> DerefMut for PeekMut<'_, T> {
294     fn deref_mut(&mut self) -> &mut T {
295         debug_assert!(!self.heap.is_empty());
296         // SAFE: PeekMut is only instantiated for non-empty heaps
297         unsafe { self.heap.data.get_unchecked_mut(0) }
298     }
299 }
300
301 impl<'a, T: Ord> PeekMut<'a, T> {
302     /// Removes the peeked value from the heap and returns it.
303     #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
304     pub fn pop(mut this: PeekMut<'a, T>) -> T {
305         let value = this.heap.pop().unwrap();
306         this.sift = false;
307         value
308     }
309 }
310
311 #[stable(feature = "rust1", since = "1.0.0")]
312 impl<T: Clone> Clone for BinaryHeap<T> {
313     fn clone(&self) -> Self {
314         BinaryHeap { data: self.data.clone() }
315     }
316
317     fn clone_from(&mut self, source: &Self) {
318         self.data.clone_from(&source.data);
319     }
320 }
321
322 #[stable(feature = "rust1", since = "1.0.0")]
323 impl<T: Ord> Default for BinaryHeap<T> {
324     /// Creates an empty `BinaryHeap<T>`.
325     #[inline]
326     fn default() -> BinaryHeap<T> {
327         BinaryHeap::new()
328     }
329 }
330
331 #[stable(feature = "binaryheap_debug", since = "1.4.0")]
332 impl<T: fmt::Debug> fmt::Debug for BinaryHeap<T> {
333     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334         f.debug_list().entries(self.iter()).finish()
335     }
336 }
337
338 impl<T: Ord> BinaryHeap<T> {
339     /// Creates an empty `BinaryHeap` as a max-heap.
340     ///
341     /// # Examples
342     ///
343     /// Basic usage:
344     ///
345     /// ```
346     /// use std::collections::BinaryHeap;
347     /// let mut heap = BinaryHeap::new();
348     /// heap.push(4);
349     /// ```
350     #[stable(feature = "rust1", since = "1.0.0")]
351     pub fn new() -> BinaryHeap<T> {
352         BinaryHeap { data: vec![] }
353     }
354
355     /// Creates an empty `BinaryHeap` with a specific capacity.
356     /// This preallocates enough memory for `capacity` elements,
357     /// so that the `BinaryHeap` does not have to be reallocated
358     /// until it contains at least that many values.
359     ///
360     /// # Examples
361     ///
362     /// Basic usage:
363     ///
364     /// ```
365     /// use std::collections::BinaryHeap;
366     /// let mut heap = BinaryHeap::with_capacity(10);
367     /// heap.push(4);
368     /// ```
369     #[stable(feature = "rust1", since = "1.0.0")]
370     pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
371         BinaryHeap { data: Vec::with_capacity(capacity) }
372     }
373
374     /// Returns a mutable reference to the greatest item in the binary heap, or
375     /// `None` if it is empty.
376     ///
377     /// Note: If the `PeekMut` value is leaked, the heap may be in an
378     /// inconsistent state.
379     ///
380     /// # Examples
381     ///
382     /// Basic usage:
383     ///
384     /// ```
385     /// use std::collections::BinaryHeap;
386     /// let mut heap = BinaryHeap::new();
387     /// assert!(heap.peek_mut().is_none());
388     ///
389     /// heap.push(1);
390     /// heap.push(5);
391     /// heap.push(2);
392     /// {
393     ///     let mut val = heap.peek_mut().unwrap();
394     ///     *val = 0;
395     /// }
396     /// assert_eq!(heap.peek(), Some(&2));
397     /// ```
398     ///
399     /// # Time complexity
400     ///
401     /// Cost is *O*(1) in the worst case.
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: true }) }
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             8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
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`]: #method.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 index_ptr: *const _ = self.data.get_unchecked(index);
1040             let hole_ptr = self.data.get_unchecked_mut(self.pos);
1041             ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1042         }
1043         self.pos = index;
1044     }
1045 }
1046
1047 impl<T> Drop for Hole<'_, T> {
1048     #[inline]
1049     fn drop(&mut self) {
1050         // fill the hole again
1051         unsafe {
1052             let pos = self.pos;
1053             ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
1054         }
1055     }
1056 }
1057
1058 /// An iterator over the elements of a `BinaryHeap`.
1059 ///
1060 /// This `struct` is created by the [`iter`] method on [`BinaryHeap`]. See its
1061 /// documentation for more.
1062 ///
1063 /// [`iter`]: struct.BinaryHeap.html#method.iter
1064 /// [`BinaryHeap`]: struct.BinaryHeap.html
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 the [`into_iter`] method on [`BinaryHeap`]
1126 /// (provided by the `IntoIterator` trait). See its documentation for more.
1127 ///
1128 /// [`into_iter`]: struct.BinaryHeap.html#method.into_iter
1129 /// [`BinaryHeap`]: struct.BinaryHeap.html
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 #[derive(Clone)]
1132 pub struct IntoIter<T> {
1133     iter: vec::IntoIter<T>,
1134 }
1135
1136 #[stable(feature = "collection_debug", since = "1.17.0")]
1137 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1138     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1139         f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
1140     }
1141 }
1142
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 impl<T> Iterator for IntoIter<T> {
1145     type Item = T;
1146
1147     #[inline]
1148     fn next(&mut self) -> Option<T> {
1149         self.iter.next()
1150     }
1151
1152     #[inline]
1153     fn size_hint(&self) -> (usize, Option<usize>) {
1154         self.iter.size_hint()
1155     }
1156 }
1157
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 impl<T> DoubleEndedIterator for IntoIter<T> {
1160     #[inline]
1161     fn next_back(&mut self) -> Option<T> {
1162         self.iter.next_back()
1163     }
1164 }
1165
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 impl<T> ExactSizeIterator for IntoIter<T> {
1168     fn is_empty(&self) -> bool {
1169         self.iter.is_empty()
1170     }
1171 }
1172
1173 #[stable(feature = "fused", since = "1.26.0")]
1174 impl<T> FusedIterator for IntoIter<T> {}
1175
1176 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1177 #[derive(Clone, Debug)]
1178 pub struct IntoIterSorted<T> {
1179     inner: BinaryHeap<T>,
1180 }
1181
1182 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1183 impl<T: Ord> Iterator for IntoIterSorted<T> {
1184     type Item = T;
1185
1186     #[inline]
1187     fn next(&mut self) -> Option<T> {
1188         self.inner.pop()
1189     }
1190
1191     #[inline]
1192     fn size_hint(&self) -> (usize, Option<usize>) {
1193         let exact = self.inner.len();
1194         (exact, Some(exact))
1195     }
1196 }
1197
1198 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1199 impl<T: Ord> ExactSizeIterator for IntoIterSorted<T> {}
1200
1201 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1202 impl<T: Ord> FusedIterator for IntoIterSorted<T> {}
1203
1204 #[unstable(feature = "trusted_len", issue = "37572")]
1205 unsafe impl<T: Ord> TrustedLen for IntoIterSorted<T> {}
1206
1207 /// A draining iterator over the elements of a `BinaryHeap`.
1208 ///
1209 /// This `struct` is created by the [`drain`] method on [`BinaryHeap`]. See its
1210 /// documentation for more.
1211 ///
1212 /// [`drain`]: struct.BinaryHeap.html#method.drain
1213 /// [`BinaryHeap`]: struct.BinaryHeap.html
1214 #[stable(feature = "drain", since = "1.6.0")]
1215 #[derive(Debug)]
1216 pub struct Drain<'a, T: 'a> {
1217     iter: vec::Drain<'a, T>,
1218 }
1219
1220 #[stable(feature = "drain", since = "1.6.0")]
1221 impl<T> Iterator for Drain<'_, T> {
1222     type Item = T;
1223
1224     #[inline]
1225     fn next(&mut self) -> Option<T> {
1226         self.iter.next()
1227     }
1228
1229     #[inline]
1230     fn size_hint(&self) -> (usize, Option<usize>) {
1231         self.iter.size_hint()
1232     }
1233 }
1234
1235 #[stable(feature = "drain", since = "1.6.0")]
1236 impl<T> DoubleEndedIterator for Drain<'_, T> {
1237     #[inline]
1238     fn next_back(&mut self) -> Option<T> {
1239         self.iter.next_back()
1240     }
1241 }
1242
1243 #[stable(feature = "drain", since = "1.6.0")]
1244 impl<T> ExactSizeIterator for Drain<'_, T> {
1245     fn is_empty(&self) -> bool {
1246         self.iter.is_empty()
1247     }
1248 }
1249
1250 #[stable(feature = "fused", since = "1.26.0")]
1251 impl<T> FusedIterator for Drain<'_, T> {}
1252
1253 /// A draining iterator over the elements of a `BinaryHeap`.
1254 ///
1255 /// This `struct` is created by the [`drain_sorted`] method on [`BinaryHeap`]. See its
1256 /// documentation for more.
1257 ///
1258 /// [`drain_sorted`]: struct.BinaryHeap.html#method.drain_sorted
1259 /// [`BinaryHeap`]: struct.BinaryHeap.html
1260 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1261 #[derive(Debug)]
1262 pub struct DrainSorted<'a, T: Ord> {
1263     inner: &'a mut BinaryHeap<T>,
1264 }
1265
1266 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1267 impl<'a, T: Ord> Drop for DrainSorted<'a, T> {
1268     /// Removes heap elements in heap order.
1269     fn drop(&mut self) {
1270         struct DropGuard<'r, 'a, T: Ord>(&'r mut DrainSorted<'a, T>);
1271
1272         impl<'r, 'a, T: Ord> Drop for DropGuard<'r, 'a, T> {
1273             fn drop(&mut self) {
1274                 while self.0.inner.pop().is_some() {}
1275             }
1276         }
1277
1278         while let Some(item) = self.inner.pop() {
1279             let guard = DropGuard(self);
1280             drop(item);
1281             mem::forget(guard);
1282         }
1283     }
1284 }
1285
1286 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1287 impl<T: Ord> Iterator for DrainSorted<'_, 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_drain_sorted", issue = "59278")]
1303 impl<T: Ord> ExactSizeIterator for DrainSorted<'_, T> {}
1304
1305 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1306 impl<T: Ord> FusedIterator for DrainSorted<'_, T> {}
1307
1308 #[unstable(feature = "trusted_len", issue = "37572")]
1309 unsafe impl<T: Ord> TrustedLen for DrainSorted<'_, T> {}
1310
1311 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1312 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1313     /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1314     ///
1315     /// This conversion happens in-place, and has *O*(*n*) time complexity.
1316     fn from(vec: Vec<T>) -> BinaryHeap<T> {
1317         let mut heap = BinaryHeap { data: vec };
1318         heap.rebuild();
1319         heap
1320     }
1321 }
1322
1323 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1324 impl<T> From<BinaryHeap<T>> for Vec<T> {
1325     fn from(heap: BinaryHeap<T>) -> Vec<T> {
1326         heap.data
1327     }
1328 }
1329
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1332     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1333         BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1334     }
1335 }
1336
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 impl<T> IntoIterator for BinaryHeap<T> {
1339     type Item = T;
1340     type IntoIter = IntoIter<T>;
1341
1342     /// Creates a consuming iterator, that is, one that moves each value out of
1343     /// the binary heap in arbitrary order. The binary heap cannot be used
1344     /// after calling this.
1345     ///
1346     /// # Examples
1347     ///
1348     /// Basic usage:
1349     ///
1350     /// ```
1351     /// use std::collections::BinaryHeap;
1352     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1353     ///
1354     /// // Print 1, 2, 3, 4 in arbitrary order
1355     /// for x in heap.into_iter() {
1356     ///     // x has type i32, not &i32
1357     ///     println!("{}", x);
1358     /// }
1359     /// ```
1360     fn into_iter(self) -> IntoIter<T> {
1361         IntoIter { iter: self.data.into_iter() }
1362     }
1363 }
1364
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 impl<'a, T> IntoIterator for &'a BinaryHeap<T> {
1367     type Item = &'a T;
1368     type IntoIter = Iter<'a, T>;
1369
1370     fn into_iter(self) -> Iter<'a, T> {
1371         self.iter()
1372     }
1373 }
1374
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1377     #[inline]
1378     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1379         <Self as SpecExtend<I>>::spec_extend(self, iter);
1380     }
1381
1382     #[inline]
1383     fn extend_one(&mut self, item: T) {
1384         self.push(item);
1385     }
1386
1387     #[inline]
1388     fn extend_reserve(&mut self, additional: usize) {
1389         self.reserve(additional);
1390     }
1391 }
1392
1393 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1394     default fn spec_extend(&mut self, iter: I) {
1395         self.extend_desugared(iter.into_iter());
1396     }
1397 }
1398
1399 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1400     fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1401         self.append(other);
1402     }
1403 }
1404
1405 impl<T: Ord> BinaryHeap<T> {
1406     fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1407         let iterator = iter.into_iter();
1408         let (lower, _) = iterator.size_hint();
1409
1410         self.reserve(lower);
1411
1412         iterator.for_each(move |elem| self.push(elem));
1413     }
1414 }
1415
1416 #[stable(feature = "extend_ref", since = "1.2.0")]
1417 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1418     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1419         self.extend(iter.into_iter().cloned());
1420     }
1421
1422     #[inline]
1423     fn extend_one(&mut self, &item: &'a T) {
1424         self.push(item);
1425     }
1426
1427     #[inline]
1428     fn extend_reserve(&mut self, additional: usize) {
1429         self.reserve(additional);
1430     }
1431 }