]> git.lizzy.rs Git - rust.git/blob - src/liballoc/collections/binary_heap.rs
Add riscv64gc-unknown-none-elf target
[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::ops::{Deref, DerefMut};
149 use core::iter::{FromIterator, FusedIterator};
150 use core::mem::{swap, size_of, ManuallyDrop};
151 use core::ptr;
152 use core::fmt;
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 #[stable(feature = "rust1", since = "1.0.0")]
211 pub struct BinaryHeap<T> {
212     data: Vec<T>,
213 }
214
215 /// Structure wrapping a mutable reference to the greatest item on a
216 /// `BinaryHeap`.
217 ///
218 /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
219 /// its documentation for more.
220 ///
221 /// [`peek_mut`]: struct.BinaryHeap.html#method.peek_mut
222 /// [`BinaryHeap`]: struct.BinaryHeap.html
223 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
224 pub struct PeekMut<'a, T: 'a + Ord> {
225     heap: &'a mut BinaryHeap<T>,
226     sift: bool,
227 }
228
229 #[stable(feature = "collection_debug", since = "1.17.0")]
230 impl<T: Ord + fmt::Debug> fmt::Debug for PeekMut<'_, T> {
231     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232         f.debug_tuple("PeekMut")
233          .field(&self.heap.data[0])
234          .finish()
235     }
236 }
237
238 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
239 impl<T: Ord> Drop for PeekMut<'_, T> {
240     fn drop(&mut self) {
241         if self.sift {
242             self.heap.sift_down(0);
243         }
244     }
245 }
246
247 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
248 impl<T: Ord> Deref for PeekMut<'_, T> {
249     type Target = T;
250     fn deref(&self) -> &T {
251         debug_assert!(!self.heap.is_empty());
252         // SAFE: PeekMut is only instantiated for non-empty heaps
253         unsafe { self.heap.data.get_unchecked(0) }
254     }
255 }
256
257 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
258 impl<T: Ord> DerefMut for PeekMut<'_, T> {
259     fn deref_mut(&mut self) -> &mut T {
260         debug_assert!(!self.heap.is_empty());
261         // SAFE: PeekMut is only instantiated for non-empty heaps
262         unsafe { self.heap.data.get_unchecked_mut(0) }
263     }
264 }
265
266 impl<'a, T: Ord> PeekMut<'a, T> {
267     /// Removes the peeked value from the heap and returns it.
268     #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
269     pub fn pop(mut this: PeekMut<'a, T>) -> T {
270         let value = this.heap.pop().unwrap();
271         this.sift = false;
272         value
273     }
274 }
275
276 #[stable(feature = "rust1", since = "1.0.0")]
277 impl<T: Clone> Clone for BinaryHeap<T> {
278     fn clone(&self) -> Self {
279         BinaryHeap { data: self.data.clone() }
280     }
281
282     fn clone_from(&mut self, source: &Self) {
283         self.data.clone_from(&source.data);
284     }
285 }
286
287 #[stable(feature = "rust1", since = "1.0.0")]
288 impl<T: Ord> Default for BinaryHeap<T> {
289     /// Creates an empty `BinaryHeap<T>`.
290     #[inline]
291     fn default() -> BinaryHeap<T> {
292         BinaryHeap::new()
293     }
294 }
295
296 #[stable(feature = "binaryheap_debug", since = "1.4.0")]
297 impl<T: fmt::Debug + Ord> fmt::Debug for BinaryHeap<T> {
298     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299         f.debug_list().entries(self.iter()).finish()
300     }
301 }
302
303 impl<T: Ord> BinaryHeap<T> {
304     /// Creates an empty `BinaryHeap` as a max-heap.
305     ///
306     /// # Examples
307     ///
308     /// Basic usage:
309     ///
310     /// ```
311     /// use std::collections::BinaryHeap;
312     /// let mut heap = BinaryHeap::new();
313     /// heap.push(4);
314     /// ```
315     #[stable(feature = "rust1", since = "1.0.0")]
316     pub fn new() -> BinaryHeap<T> {
317         BinaryHeap { data: vec![] }
318     }
319
320     /// Creates an empty `BinaryHeap` with a specific capacity.
321     /// This preallocates enough memory for `capacity` elements,
322     /// so that the `BinaryHeap` does not have to be reallocated
323     /// until it contains at least that many values.
324     ///
325     /// # Examples
326     ///
327     /// Basic usage:
328     ///
329     /// ```
330     /// use std::collections::BinaryHeap;
331     /// let mut heap = BinaryHeap::with_capacity(10);
332     /// heap.push(4);
333     /// ```
334     #[stable(feature = "rust1", since = "1.0.0")]
335     pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
336         BinaryHeap { data: Vec::with_capacity(capacity) }
337     }
338
339     /// Returns an iterator visiting all values in the underlying vector, in
340     /// arbitrary order.
341     ///
342     /// # Examples
343     ///
344     /// Basic usage:
345     ///
346     /// ```
347     /// use std::collections::BinaryHeap;
348     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
349     ///
350     /// // Print 1, 2, 3, 4 in arbitrary order
351     /// for x in heap.iter() {
352     ///     println!("{}", x);
353     /// }
354     /// ```
355     #[stable(feature = "rust1", since = "1.0.0")]
356     pub fn iter(&self) -> Iter<'_, T> {
357         Iter { iter: self.data.iter() }
358     }
359
360     /// Returns the greatest item in the binary heap, or `None` if it is empty.
361     ///
362     /// # Examples
363     ///
364     /// Basic usage:
365     ///
366     /// ```
367     /// use std::collections::BinaryHeap;
368     /// let mut heap = BinaryHeap::new();
369     /// assert_eq!(heap.peek(), None);
370     ///
371     /// heap.push(1);
372     /// heap.push(5);
373     /// heap.push(2);
374     /// assert_eq!(heap.peek(), Some(&5));
375     ///
376     /// ```
377     #[stable(feature = "rust1", since = "1.0.0")]
378     pub fn peek(&self) -> Option<&T> {
379         self.data.get(0)
380     }
381
382     /// Returns a mutable reference to the greatest item in the binary heap, or
383     /// `None` if it is empty.
384     ///
385     /// Note: If the `PeekMut` value is leaked, the heap may be in an
386     /// inconsistent state.
387     ///
388     /// # Examples
389     ///
390     /// Basic usage:
391     ///
392     /// ```
393     /// use std::collections::BinaryHeap;
394     /// let mut heap = BinaryHeap::new();
395     /// assert!(heap.peek_mut().is_none());
396     ///
397     /// heap.push(1);
398     /// heap.push(5);
399     /// heap.push(2);
400     /// {
401     ///     let mut val = heap.peek_mut().unwrap();
402     ///     *val = 0;
403     /// }
404     /// assert_eq!(heap.peek(), Some(&2));
405     /// ```
406     #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
407     pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T>> {
408         if self.is_empty() {
409             None
410         } else {
411             Some(PeekMut {
412                 heap: self,
413                 sift: true,
414             })
415         }
416     }
417
418     /// Returns the number of elements the binary heap can hold without reallocating.
419     ///
420     /// # Examples
421     ///
422     /// Basic usage:
423     ///
424     /// ```
425     /// use std::collections::BinaryHeap;
426     /// let mut heap = BinaryHeap::with_capacity(100);
427     /// assert!(heap.capacity() >= 100);
428     /// heap.push(4);
429     /// ```
430     #[stable(feature = "rust1", since = "1.0.0")]
431     pub fn capacity(&self) -> usize {
432         self.data.capacity()
433     }
434
435     /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
436     /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
437     ///
438     /// Note that the allocator may give the collection more space than it requests. Therefore
439     /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
440     /// insertions are expected.
441     ///
442     /// # Panics
443     ///
444     /// Panics if the new capacity overflows `usize`.
445     ///
446     /// # Examples
447     ///
448     /// Basic usage:
449     ///
450     /// ```
451     /// use std::collections::BinaryHeap;
452     /// let mut heap = BinaryHeap::new();
453     /// heap.reserve_exact(100);
454     /// assert!(heap.capacity() >= 100);
455     /// heap.push(4);
456     /// ```
457     ///
458     /// [`reserve`]: #method.reserve
459     #[stable(feature = "rust1", since = "1.0.0")]
460     pub fn reserve_exact(&mut self, additional: usize) {
461         self.data.reserve_exact(additional);
462     }
463
464     /// Reserves capacity for at least `additional` more elements to be inserted in the
465     /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
466     ///
467     /// # Panics
468     ///
469     /// Panics if the new capacity overflows `usize`.
470     ///
471     /// # Examples
472     ///
473     /// Basic usage:
474     ///
475     /// ```
476     /// use std::collections::BinaryHeap;
477     /// let mut heap = BinaryHeap::new();
478     /// heap.reserve(100);
479     /// assert!(heap.capacity() >= 100);
480     /// heap.push(4);
481     /// ```
482     #[stable(feature = "rust1", since = "1.0.0")]
483     pub fn reserve(&mut self, additional: usize) {
484         self.data.reserve(additional);
485     }
486
487     /// Discards as much additional capacity as possible.
488     ///
489     /// # Examples
490     ///
491     /// Basic usage:
492     ///
493     /// ```
494     /// use std::collections::BinaryHeap;
495     /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
496     ///
497     /// assert!(heap.capacity() >= 100);
498     /// heap.shrink_to_fit();
499     /// assert!(heap.capacity() == 0);
500     /// ```
501     #[stable(feature = "rust1", since = "1.0.0")]
502     pub fn shrink_to_fit(&mut self) {
503         self.data.shrink_to_fit();
504     }
505
506     /// Discards capacity with a lower bound.
507     ///
508     /// The capacity will remain at least as large as both the length
509     /// and the supplied value.
510     ///
511     /// Panics if the current capacity is smaller than the supplied
512     /// minimum capacity.
513     ///
514     /// # Examples
515     ///
516     /// ```
517     /// #![feature(shrink_to)]
518     /// use std::collections::BinaryHeap;
519     /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
520     ///
521     /// assert!(heap.capacity() >= 100);
522     /// heap.shrink_to(10);
523     /// assert!(heap.capacity() >= 10);
524     /// ```
525     #[inline]
526     #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
527     pub fn shrink_to(&mut self, min_capacity: usize) {
528         self.data.shrink_to(min_capacity)
529     }
530
531     /// Removes the greatest item from the binary heap and returns it, or `None` if it
532     /// is empty.
533     ///
534     /// # Examples
535     ///
536     /// Basic usage:
537     ///
538     /// ```
539     /// use std::collections::BinaryHeap;
540     /// let mut heap = BinaryHeap::from(vec![1, 3]);
541     ///
542     /// assert_eq!(heap.pop(), Some(3));
543     /// assert_eq!(heap.pop(), Some(1));
544     /// assert_eq!(heap.pop(), None);
545     /// ```
546     #[stable(feature = "rust1", since = "1.0.0")]
547     pub fn pop(&mut self) -> Option<T> {
548         self.data.pop().map(|mut item| {
549             if !self.is_empty() {
550                 swap(&mut item, &mut self.data[0]);
551                 self.sift_down_to_bottom(0);
552             }
553             item
554         })
555     }
556
557     /// Pushes an item onto the binary heap.
558     ///
559     /// # Examples
560     ///
561     /// Basic usage:
562     ///
563     /// ```
564     /// use std::collections::BinaryHeap;
565     /// let mut heap = BinaryHeap::new();
566     /// heap.push(3);
567     /// heap.push(5);
568     /// heap.push(1);
569     ///
570     /// assert_eq!(heap.len(), 3);
571     /// assert_eq!(heap.peek(), Some(&5));
572     /// ```
573     #[stable(feature = "rust1", since = "1.0.0")]
574     pub fn push(&mut self, item: T) {
575         let old_len = self.len();
576         self.data.push(item);
577         self.sift_up(0, old_len);
578     }
579
580     /// Consumes the `BinaryHeap` and returns the underlying vector
581     /// in arbitrary order.
582     ///
583     /// # Examples
584     ///
585     /// Basic usage:
586     ///
587     /// ```
588     /// use std::collections::BinaryHeap;
589     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
590     /// let vec = heap.into_vec();
591     ///
592     /// // Will print in some order
593     /// for x in vec {
594     ///     println!("{}", x);
595     /// }
596     /// ```
597     #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
598     pub fn into_vec(self) -> Vec<T> {
599         self.into()
600     }
601
602     /// Consumes the `BinaryHeap` and returns a vector in sorted
603     /// (ascending) order.
604     ///
605     /// # Examples
606     ///
607     /// Basic usage:
608     ///
609     /// ```
610     /// use std::collections::BinaryHeap;
611     ///
612     /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
613     /// heap.push(6);
614     /// heap.push(3);
615     ///
616     /// let vec = heap.into_sorted_vec();
617     /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
618     /// ```
619     #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
620     pub fn into_sorted_vec(mut self) -> Vec<T> {
621         let mut end = self.len();
622         while end > 1 {
623             end -= 1;
624             self.data.swap(0, end);
625             self.sift_down_range(0, end);
626         }
627         self.into_vec()
628     }
629
630     // The implementations of sift_up and sift_down use unsafe blocks in
631     // order to move an element out of the vector (leaving behind a
632     // hole), shift along the others and move the removed element back into the
633     // vector at the final location of the hole.
634     // The `Hole` type is used to represent this, and make sure
635     // the hole is filled back at the end of its scope, even on panic.
636     // Using a hole reduces the constant factor compared to using swaps,
637     // which involves twice as many moves.
638     fn sift_up(&mut self, start: usize, pos: usize) -> usize {
639         unsafe {
640             // Take out the value at `pos` and create a hole.
641             let mut hole = Hole::new(&mut self.data, pos);
642
643             while hole.pos() > start {
644                 let parent = (hole.pos() - 1) / 2;
645                 if hole.element() <= hole.get(parent) {
646                     break;
647                 }
648                 hole.move_to(parent);
649             }
650             hole.pos()
651         }
652     }
653
654     /// Take an element at `pos` and move it down the heap,
655     /// while its children are larger.
656     fn sift_down_range(&mut self, pos: usize, end: usize) {
657         unsafe {
658             let mut hole = Hole::new(&mut self.data, pos);
659             let mut child = 2 * pos + 1;
660             while child < end {
661                 let right = child + 1;
662                 // compare with the greater of the two children
663                 if right < end && !(hole.get(child) > hole.get(right)) {
664                     child = right;
665                 }
666                 // if we are already in order, stop.
667                 if hole.element() >= hole.get(child) {
668                     break;
669                 }
670                 hole.move_to(child);
671                 child = 2 * hole.pos() + 1;
672             }
673         }
674     }
675
676     fn sift_down(&mut self, pos: usize) {
677         let len = self.len();
678         self.sift_down_range(pos, len);
679     }
680
681     /// Take an element at `pos` and move it all the way down the heap,
682     /// then sift it up to its position.
683     ///
684     /// Note: This is faster when the element is known to be large / should
685     /// be closer to the bottom.
686     fn sift_down_to_bottom(&mut self, mut pos: usize) {
687         let end = self.len();
688         let start = pos;
689         unsafe {
690             let mut hole = Hole::new(&mut self.data, pos);
691             let mut child = 2 * pos + 1;
692             while child < end {
693                 let right = child + 1;
694                 // compare with the greater of the two children
695                 if right < end && !(hole.get(child) > hole.get(right)) {
696                     child = right;
697                 }
698                 hole.move_to(child);
699                 child = 2 * hole.pos() + 1;
700             }
701             pos = hole.pos;
702         }
703         self.sift_up(start, pos);
704     }
705
706     /// Returns the length of the binary heap.
707     ///
708     /// # Examples
709     ///
710     /// Basic usage:
711     ///
712     /// ```
713     /// use std::collections::BinaryHeap;
714     /// let heap = BinaryHeap::from(vec![1, 3]);
715     ///
716     /// assert_eq!(heap.len(), 2);
717     /// ```
718     #[stable(feature = "rust1", since = "1.0.0")]
719     pub fn len(&self) -> usize {
720         self.data.len()
721     }
722
723     /// Checks if the binary heap is empty.
724     ///
725     /// # Examples
726     ///
727     /// Basic usage:
728     ///
729     /// ```
730     /// use std::collections::BinaryHeap;
731     /// let mut heap = BinaryHeap::new();
732     ///
733     /// assert!(heap.is_empty());
734     ///
735     /// heap.push(3);
736     /// heap.push(5);
737     /// heap.push(1);
738     ///
739     /// assert!(!heap.is_empty());
740     /// ```
741     #[stable(feature = "rust1", since = "1.0.0")]
742     pub fn is_empty(&self) -> bool {
743         self.len() == 0
744     }
745
746     /// Clears the binary heap, returning an iterator over the removed elements.
747     ///
748     /// The elements are removed in arbitrary order.
749     ///
750     /// # Examples
751     ///
752     /// Basic usage:
753     ///
754     /// ```
755     /// use std::collections::BinaryHeap;
756     /// let mut heap = BinaryHeap::from(vec![1, 3]);
757     ///
758     /// assert!(!heap.is_empty());
759     ///
760     /// for x in heap.drain() {
761     ///     println!("{}", x);
762     /// }
763     ///
764     /// assert!(heap.is_empty());
765     /// ```
766     #[inline]
767     #[stable(feature = "drain", since = "1.6.0")]
768     pub fn drain(&mut self) -> Drain<'_, T> {
769         Drain { iter: self.data.drain(..) }
770     }
771
772     /// Drops all items from the binary heap.
773     ///
774     /// # Examples
775     ///
776     /// Basic usage:
777     ///
778     /// ```
779     /// use std::collections::BinaryHeap;
780     /// let mut heap = BinaryHeap::from(vec![1, 3]);
781     ///
782     /// assert!(!heap.is_empty());
783     ///
784     /// heap.clear();
785     ///
786     /// assert!(heap.is_empty());
787     /// ```
788     #[stable(feature = "rust1", since = "1.0.0")]
789     pub fn clear(&mut self) {
790         self.drain();
791     }
792
793     fn rebuild(&mut self) {
794         let mut n = self.len() / 2;
795         while n > 0 {
796             n -= 1;
797             self.sift_down(n);
798         }
799     }
800
801     /// Moves all the elements of `other` into `self`, leaving `other` empty.
802     ///
803     /// # Examples
804     ///
805     /// Basic usage:
806     ///
807     /// ```
808     /// use std::collections::BinaryHeap;
809     ///
810     /// let v = vec![-10, 1, 2, 3, 3];
811     /// let mut a = BinaryHeap::from(v);
812     ///
813     /// let v = vec![-20, 5, 43];
814     /// let mut b = BinaryHeap::from(v);
815     ///
816     /// a.append(&mut b);
817     ///
818     /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
819     /// assert!(b.is_empty());
820     /// ```
821     #[stable(feature = "binary_heap_append", since = "1.11.0")]
822     pub fn append(&mut self, other: &mut Self) {
823         if self.len() < other.len() {
824             swap(self, other);
825         }
826
827         if other.is_empty() {
828             return;
829         }
830
831         #[inline(always)]
832         fn log2_fast(x: usize) -> usize {
833             8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
834         }
835
836         // `rebuild` takes O(len1 + len2) operations
837         // and about 2 * (len1 + len2) comparisons in the worst case
838         // while `extend` takes O(len2 * log_2(len1)) operations
839         // and about 1 * len2 * log_2(len1) comparisons in the worst case,
840         // assuming len1 >= len2.
841         #[inline]
842         fn better_to_rebuild(len1: usize, len2: usize) -> bool {
843             2 * (len1 + len2) < len2 * log2_fast(len1)
844         }
845
846         if better_to_rebuild(self.len(), other.len()) {
847             self.data.append(&mut other.data);
848             self.rebuild();
849         } else {
850             self.extend(other.drain());
851         }
852     }
853 }
854
855 /// Hole represents a hole in a slice i.e., an index without valid value
856 /// (because it was moved from or duplicated).
857 /// In drop, `Hole` will restore the slice by filling the hole
858 /// position with the value that was originally removed.
859 struct Hole<'a, T: 'a> {
860     data: &'a mut [T],
861     elt: ManuallyDrop<T>,
862     pos: usize,
863 }
864
865 impl<'a, T> Hole<'a, T> {
866     /// Create a new Hole at index `pos`.
867     ///
868     /// Unsafe because pos must be within the data slice.
869     #[inline]
870     unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
871         debug_assert!(pos < data.len());
872         // SAFE: pos should be inside the slice
873         let elt = ptr::read(data.get_unchecked(pos));
874         Hole {
875             data,
876             elt: ManuallyDrop::new(elt),
877             pos,
878         }
879     }
880
881     #[inline]
882     fn pos(&self) -> usize {
883         self.pos
884     }
885
886     /// Returns a reference to the element removed.
887     #[inline]
888     fn element(&self) -> &T {
889         &self.elt
890     }
891
892     /// Returns a reference to the element at `index`.
893     ///
894     /// Unsafe because index must be within the data slice and not equal to pos.
895     #[inline]
896     unsafe fn get(&self, index: usize) -> &T {
897         debug_assert!(index != self.pos);
898         debug_assert!(index < self.data.len());
899         self.data.get_unchecked(index)
900     }
901
902     /// Move hole to new location
903     ///
904     /// Unsafe because index must be within the data slice and not equal to pos.
905     #[inline]
906     unsafe fn move_to(&mut self, index: usize) {
907         debug_assert!(index != self.pos);
908         debug_assert!(index < self.data.len());
909         let index_ptr: *const _ = self.data.get_unchecked(index);
910         let hole_ptr = self.data.get_unchecked_mut(self.pos);
911         ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
912         self.pos = index;
913     }
914 }
915
916 impl<T> Drop for Hole<'_, T> {
917     #[inline]
918     fn drop(&mut self) {
919         // fill the hole again
920         unsafe {
921             let pos = self.pos;
922             ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
923         }
924     }
925 }
926
927 /// An iterator over the elements of a `BinaryHeap`.
928 ///
929 /// This `struct` is created by the [`iter`] method on [`BinaryHeap`]. See its
930 /// documentation for more.
931 ///
932 /// [`iter`]: struct.BinaryHeap.html#method.iter
933 /// [`BinaryHeap`]: struct.BinaryHeap.html
934 #[stable(feature = "rust1", since = "1.0.0")]
935 pub struct Iter<'a, T: 'a> {
936     iter: slice::Iter<'a, T>,
937 }
938
939 #[stable(feature = "collection_debug", since = "1.17.0")]
940 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
941     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
942         f.debug_tuple("Iter")
943          .field(&self.iter.as_slice())
944          .finish()
945     }
946 }
947
948 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl<'a, T> Clone for Iter<'a, T> {
951     fn clone(&self) -> Iter<'a, T> {
952         Iter { iter: self.iter.clone() }
953     }
954 }
955
956 #[stable(feature = "rust1", since = "1.0.0")]
957 impl<'a, T> Iterator for Iter<'a, T> {
958     type Item = &'a T;
959
960     #[inline]
961     fn next(&mut self) -> Option<&'a T> {
962         self.iter.next()
963     }
964
965     #[inline]
966     fn size_hint(&self) -> (usize, Option<usize>) {
967         self.iter.size_hint()
968     }
969 }
970
971 #[stable(feature = "rust1", since = "1.0.0")]
972 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
973     #[inline]
974     fn next_back(&mut self) -> Option<&'a T> {
975         self.iter.next_back()
976     }
977 }
978
979 #[stable(feature = "rust1", since = "1.0.0")]
980 impl<T> ExactSizeIterator for Iter<'_, T> {
981     fn is_empty(&self) -> bool {
982         self.iter.is_empty()
983     }
984 }
985
986 #[stable(feature = "fused", since = "1.26.0")]
987 impl<T> FusedIterator for Iter<'_, T> {}
988
989 /// An owning iterator over the elements of a `BinaryHeap`.
990 ///
991 /// This `struct` is created by the [`into_iter`] method on [`BinaryHeap`][`BinaryHeap`]
992 /// (provided by the `IntoIterator` trait). See its documentation for more.
993 ///
994 /// [`into_iter`]: struct.BinaryHeap.html#method.into_iter
995 /// [`BinaryHeap`]: struct.BinaryHeap.html
996 #[stable(feature = "rust1", since = "1.0.0")]
997 #[derive(Clone)]
998 pub struct IntoIter<T> {
999     iter: vec::IntoIter<T>,
1000 }
1001
1002 #[stable(feature = "collection_debug", since = "1.17.0")]
1003 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1004     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1005         f.debug_tuple("IntoIter")
1006          .field(&self.iter.as_slice())
1007          .finish()
1008     }
1009 }
1010
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 impl<T> Iterator for IntoIter<T> {
1013     type Item = T;
1014
1015     #[inline]
1016     fn next(&mut self) -> Option<T> {
1017         self.iter.next()
1018     }
1019
1020     #[inline]
1021     fn size_hint(&self) -> (usize, Option<usize>) {
1022         self.iter.size_hint()
1023     }
1024 }
1025
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 impl<T> DoubleEndedIterator for IntoIter<T> {
1028     #[inline]
1029     fn next_back(&mut self) -> Option<T> {
1030         self.iter.next_back()
1031     }
1032 }
1033
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 impl<T> ExactSizeIterator for IntoIter<T> {
1036     fn is_empty(&self) -> bool {
1037         self.iter.is_empty()
1038     }
1039 }
1040
1041 #[stable(feature = "fused", since = "1.26.0")]
1042 impl<T> FusedIterator for IntoIter<T> {}
1043
1044 /// A draining iterator over the elements of a `BinaryHeap`.
1045 ///
1046 /// This `struct` is created by the [`drain`] method on [`BinaryHeap`]. See its
1047 /// documentation for more.
1048 ///
1049 /// [`drain`]: struct.BinaryHeap.html#method.drain
1050 /// [`BinaryHeap`]: struct.BinaryHeap.html
1051 #[stable(feature = "drain", since = "1.6.0")]
1052 #[derive(Debug)]
1053 pub struct Drain<'a, T: 'a> {
1054     iter: vec::Drain<'a, T>,
1055 }
1056
1057 #[stable(feature = "drain", since = "1.6.0")]
1058 impl<T> Iterator for Drain<'_, T> {
1059     type Item = T;
1060
1061     #[inline]
1062     fn next(&mut self) -> Option<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
1072 #[stable(feature = "drain", since = "1.6.0")]
1073 impl<T> DoubleEndedIterator for Drain<'_, T> {
1074     #[inline]
1075     fn next_back(&mut self) -> Option<T> {
1076         self.iter.next_back()
1077     }
1078 }
1079
1080 #[stable(feature = "drain", since = "1.6.0")]
1081 impl<T> ExactSizeIterator for Drain<'_, T> {
1082     fn is_empty(&self) -> bool {
1083         self.iter.is_empty()
1084     }
1085 }
1086
1087 #[stable(feature = "fused", since = "1.26.0")]
1088 impl<T> FusedIterator for Drain<'_, T> {}
1089
1090 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1091 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1092     fn from(vec: Vec<T>) -> BinaryHeap<T> {
1093         let mut heap = BinaryHeap { data: vec };
1094         heap.rebuild();
1095         heap
1096     }
1097 }
1098
1099 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1100 impl<T> From<BinaryHeap<T>> for Vec<T> {
1101     fn from(heap: BinaryHeap<T>) -> Vec<T> {
1102         heap.data
1103     }
1104 }
1105
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1108     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1109         BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1110     }
1111 }
1112
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 impl<T: Ord> IntoIterator for BinaryHeap<T> {
1115     type Item = T;
1116     type IntoIter = IntoIter<T>;
1117
1118     /// Creates a consuming iterator, that is, one that moves each value out of
1119     /// the binary heap in arbitrary order. The binary heap cannot be used
1120     /// after calling this.
1121     ///
1122     /// # Examples
1123     ///
1124     /// Basic usage:
1125     ///
1126     /// ```
1127     /// use std::collections::BinaryHeap;
1128     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1129     ///
1130     /// // Print 1, 2, 3, 4 in arbitrary order
1131     /// for x in heap.into_iter() {
1132     ///     // x has type i32, not &i32
1133     ///     println!("{}", x);
1134     /// }
1135     /// ```
1136     fn into_iter(self) -> IntoIter<T> {
1137         IntoIter { iter: self.data.into_iter() }
1138     }
1139 }
1140
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 impl<'a, T> IntoIterator for &'a BinaryHeap<T>
1143     where T: Ord
1144 {
1145     type Item = &'a T;
1146     type IntoIter = Iter<'a, T>;
1147
1148     fn into_iter(self) -> Iter<'a, T> {
1149         self.iter()
1150     }
1151 }
1152
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1155     #[inline]
1156     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1157         <Self as SpecExtend<I>>::spec_extend(self, iter);
1158     }
1159 }
1160
1161 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1162     default fn spec_extend(&mut self, iter: I) {
1163         self.extend_desugared(iter.into_iter());
1164     }
1165 }
1166
1167 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1168     fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1169         self.append(other);
1170     }
1171 }
1172
1173 impl<T: Ord> BinaryHeap<T> {
1174     fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1175         let iterator = iter.into_iter();
1176         let (lower, _) = iterator.size_hint();
1177
1178         self.reserve(lower);
1179
1180         for elem in iterator {
1181             self.push(elem);
1182         }
1183     }
1184 }
1185
1186 #[stable(feature = "extend_ref", since = "1.2.0")]
1187 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1188     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1189         self.extend(iter.into_iter().cloned());
1190     }
1191 }