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