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