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