]> git.lizzy.rs Git - rust.git/blob - src/liballoc/binary_heap.rs
Merge branch 'refactor-select' of https://github.com/aravind-pg/rust into update...
[rust.git] / src / liballoc / 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, Place, Placer, InPlace};
159 use core::iter::{FromIterator, FusedIterator};
160 use core::mem::{swap, size_of};
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     /// Removes the greatest item from the binary heap and returns it, or `None` if it
513     /// is empty.
514     ///
515     /// # Examples
516     ///
517     /// Basic usage:
518     ///
519     /// ```
520     /// use std::collections::BinaryHeap;
521     /// let mut heap = BinaryHeap::from(vec![1, 3]);
522     ///
523     /// assert_eq!(heap.pop(), Some(3));
524     /// assert_eq!(heap.pop(), Some(1));
525     /// assert_eq!(heap.pop(), None);
526     /// ```
527     #[stable(feature = "rust1", since = "1.0.0")]
528     pub fn pop(&mut self) -> Option<T> {
529         self.data.pop().map(|mut item| {
530             if !self.is_empty() {
531                 swap(&mut item, &mut self.data[0]);
532                 self.sift_down_to_bottom(0);
533             }
534             item
535         })
536     }
537
538     /// Pushes an item onto the binary heap.
539     ///
540     /// # Examples
541     ///
542     /// Basic usage:
543     ///
544     /// ```
545     /// use std::collections::BinaryHeap;
546     /// let mut heap = BinaryHeap::new();
547     /// heap.push(3);
548     /// heap.push(5);
549     /// heap.push(1);
550     ///
551     /// assert_eq!(heap.len(), 3);
552     /// assert_eq!(heap.peek(), Some(&5));
553     /// ```
554     #[stable(feature = "rust1", since = "1.0.0")]
555     pub fn push(&mut self, item: T) {
556         let old_len = self.len();
557         self.data.push(item);
558         self.sift_up(0, old_len);
559     }
560
561     /// Consumes the `BinaryHeap` and returns the underlying vector
562     /// in arbitrary order.
563     ///
564     /// # Examples
565     ///
566     /// Basic usage:
567     ///
568     /// ```
569     /// use std::collections::BinaryHeap;
570     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
571     /// let vec = heap.into_vec();
572     ///
573     /// // Will print in some order
574     /// for x in vec {
575     ///     println!("{}", x);
576     /// }
577     /// ```
578     #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
579     pub fn into_vec(self) -> Vec<T> {
580         self.into()
581     }
582
583     /// Consumes the `BinaryHeap` and returns a vector in sorted
584     /// (ascending) order.
585     ///
586     /// # Examples
587     ///
588     /// Basic usage:
589     ///
590     /// ```
591     /// use std::collections::BinaryHeap;
592     ///
593     /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
594     /// heap.push(6);
595     /// heap.push(3);
596     ///
597     /// let vec = heap.into_sorted_vec();
598     /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
599     /// ```
600     #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
601     pub fn into_sorted_vec(mut self) -> Vec<T> {
602         let mut end = self.len();
603         while end > 1 {
604             end -= 1;
605             self.data.swap(0, end);
606             self.sift_down_range(0, end);
607         }
608         self.into_vec()
609     }
610
611     // The implementations of sift_up and sift_down use unsafe blocks in
612     // order to move an element out of the vector (leaving behind a
613     // hole), shift along the others and move the removed element back into the
614     // vector at the final location of the hole.
615     // The `Hole` type is used to represent this, and make sure
616     // the hole is filled back at the end of its scope, even on panic.
617     // Using a hole reduces the constant factor compared to using swaps,
618     // which involves twice as many moves.
619     fn sift_up(&mut self, start: usize, pos: usize) -> usize {
620         unsafe {
621             // Take out the value at `pos` and create a hole.
622             let mut hole = Hole::new(&mut self.data, pos);
623
624             while hole.pos() > start {
625                 let parent = (hole.pos() - 1) / 2;
626                 if hole.element() <= hole.get(parent) {
627                     break;
628                 }
629                 hole.move_to(parent);
630             }
631             hole.pos()
632         }
633     }
634
635     /// Take an element at `pos` and move it down the heap,
636     /// while its children are larger.
637     fn sift_down_range(&mut self, pos: usize, end: usize) {
638         unsafe {
639             let mut hole = Hole::new(&mut self.data, pos);
640             let mut child = 2 * pos + 1;
641             while child < end {
642                 let right = child + 1;
643                 // compare with the greater of the two children
644                 if right < end && !(hole.get(child) > hole.get(right)) {
645                     child = right;
646                 }
647                 // if we are already in order, stop.
648                 if hole.element() >= hole.get(child) {
649                     break;
650                 }
651                 hole.move_to(child);
652                 child = 2 * hole.pos() + 1;
653             }
654         }
655     }
656
657     fn sift_down(&mut self, pos: usize) {
658         let len = self.len();
659         self.sift_down_range(pos, len);
660     }
661
662     /// Take an element at `pos` and move it all the way down the heap,
663     /// then sift it up to its position.
664     ///
665     /// Note: This is faster when the element is known to be large / should
666     /// be closer to the bottom.
667     fn sift_down_to_bottom(&mut self, mut pos: usize) {
668         let end = self.len();
669         let start = pos;
670         unsafe {
671             let mut hole = Hole::new(&mut self.data, pos);
672             let mut child = 2 * pos + 1;
673             while child < end {
674                 let right = child + 1;
675                 // compare with the greater of the two children
676                 if right < end && !(hole.get(child) > hole.get(right)) {
677                     child = right;
678                 }
679                 hole.move_to(child);
680                 child = 2 * hole.pos() + 1;
681             }
682             pos = hole.pos;
683         }
684         self.sift_up(start, pos);
685     }
686
687     /// Returns the length of the binary heap.
688     ///
689     /// # Examples
690     ///
691     /// Basic usage:
692     ///
693     /// ```
694     /// use std::collections::BinaryHeap;
695     /// let heap = BinaryHeap::from(vec![1, 3]);
696     ///
697     /// assert_eq!(heap.len(), 2);
698     /// ```
699     #[stable(feature = "rust1", since = "1.0.0")]
700     pub fn len(&self) -> usize {
701         self.data.len()
702     }
703
704     /// Checks if the binary heap is empty.
705     ///
706     /// # Examples
707     ///
708     /// Basic usage:
709     ///
710     /// ```
711     /// use std::collections::BinaryHeap;
712     /// let mut heap = BinaryHeap::new();
713     ///
714     /// assert!(heap.is_empty());
715     ///
716     /// heap.push(3);
717     /// heap.push(5);
718     /// heap.push(1);
719     ///
720     /// assert!(!heap.is_empty());
721     /// ```
722     #[stable(feature = "rust1", since = "1.0.0")]
723     pub fn is_empty(&self) -> bool {
724         self.len() == 0
725     }
726
727     /// Clears the binary heap, returning an iterator over the removed elements.
728     ///
729     /// The elements are removed in arbitrary order.
730     ///
731     /// # Examples
732     ///
733     /// Basic usage:
734     ///
735     /// ```
736     /// use std::collections::BinaryHeap;
737     /// let mut heap = BinaryHeap::from(vec![1, 3]);
738     ///
739     /// assert!(!heap.is_empty());
740     ///
741     /// for x in heap.drain() {
742     ///     println!("{}", x);
743     /// }
744     ///
745     /// assert!(heap.is_empty());
746     /// ```
747     #[inline]
748     #[stable(feature = "drain", since = "1.6.0")]
749     pub fn drain(&mut self) -> Drain<T> {
750         Drain { iter: self.data.drain(..) }
751     }
752
753     /// Drops all items from the binary heap.
754     ///
755     /// # Examples
756     ///
757     /// Basic usage:
758     ///
759     /// ```
760     /// use std::collections::BinaryHeap;
761     /// let mut heap = BinaryHeap::from(vec![1, 3]);
762     ///
763     /// assert!(!heap.is_empty());
764     ///
765     /// heap.clear();
766     ///
767     /// assert!(heap.is_empty());
768     /// ```
769     #[stable(feature = "rust1", since = "1.0.0")]
770     pub fn clear(&mut self) {
771         self.drain();
772     }
773
774     fn rebuild(&mut self) {
775         let mut n = self.len() / 2;
776         while n > 0 {
777             n -= 1;
778             self.sift_down(n);
779         }
780     }
781
782     /// Moves all the elements of `other` into `self`, leaving `other` empty.
783     ///
784     /// # Examples
785     ///
786     /// Basic usage:
787     ///
788     /// ```
789     /// use std::collections::BinaryHeap;
790     ///
791     /// let v = vec![-10, 1, 2, 3, 3];
792     /// let mut a = BinaryHeap::from(v);
793     ///
794     /// let v = vec![-20, 5, 43];
795     /// let mut b = BinaryHeap::from(v);
796     ///
797     /// a.append(&mut b);
798     ///
799     /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
800     /// assert!(b.is_empty());
801     /// ```
802     #[stable(feature = "binary_heap_append", since = "1.11.0")]
803     pub fn append(&mut self, other: &mut Self) {
804         if self.len() < other.len() {
805             swap(self, other);
806         }
807
808         if other.is_empty() {
809             return;
810         }
811
812         #[inline(always)]
813         fn log2_fast(x: usize) -> usize {
814             8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
815         }
816
817         // `rebuild` takes O(len1 + len2) operations
818         // and about 2 * (len1 + len2) comparisons in the worst case
819         // while `extend` takes O(len2 * log_2(len1)) operations
820         // and about 1 * len2 * log_2(len1) comparisons in the worst case,
821         // assuming len1 >= len2.
822         #[inline]
823         fn better_to_rebuild(len1: usize, len2: usize) -> bool {
824             2 * (len1 + len2) < len2 * log2_fast(len1)
825         }
826
827         if better_to_rebuild(self.len(), other.len()) {
828             self.data.append(&mut other.data);
829             self.rebuild();
830         } else {
831             self.extend(other.drain());
832         }
833     }
834 }
835
836 /// Hole represents a hole in a slice i.e. an index without valid value
837 /// (because it was moved from or duplicated).
838 /// In drop, `Hole` will restore the slice by filling the hole
839 /// position with the value that was originally removed.
840 struct Hole<'a, T: 'a> {
841     data: &'a mut [T],
842     /// `elt` is always `Some` from new until drop.
843     elt: Option<T>,
844     pos: usize,
845 }
846
847 impl<'a, T> Hole<'a, T> {
848     /// Create a new Hole at index `pos`.
849     ///
850     /// Unsafe because pos must be within the data slice.
851     #[inline]
852     unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
853         debug_assert!(pos < data.len());
854         let elt = ptr::read(&data[pos]);
855         Hole {
856             data,
857             elt: Some(elt),
858             pos,
859         }
860     }
861
862     #[inline]
863     fn pos(&self) -> usize {
864         self.pos
865     }
866
867     /// Returns a reference to the element removed.
868     #[inline]
869     fn element(&self) -> &T {
870         self.elt.as_ref().unwrap()
871     }
872
873     /// Returns a reference to the element at `index`.
874     ///
875     /// Unsafe because index must be within the data slice and not equal to pos.
876     #[inline]
877     unsafe fn get(&self, index: usize) -> &T {
878         debug_assert!(index != self.pos);
879         debug_assert!(index < self.data.len());
880         self.data.get_unchecked(index)
881     }
882
883     /// Move hole to new location
884     ///
885     /// Unsafe because index must be within the data slice and not equal to pos.
886     #[inline]
887     unsafe fn move_to(&mut self, index: usize) {
888         debug_assert!(index != self.pos);
889         debug_assert!(index < self.data.len());
890         let index_ptr: *const _ = self.data.get_unchecked(index);
891         let hole_ptr = self.data.get_unchecked_mut(self.pos);
892         ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
893         self.pos = index;
894     }
895 }
896
897 impl<'a, T> Drop for Hole<'a, T> {
898     #[inline]
899     fn drop(&mut self) {
900         // fill the hole again
901         unsafe {
902             let pos = self.pos;
903             ptr::write(self.data.get_unchecked_mut(pos), self.elt.take().unwrap());
904         }
905     }
906 }
907
908 /// An iterator over the elements of a `BinaryHeap`.
909 ///
910 /// This `struct` is created by the [`iter`] method on [`BinaryHeap`]. See its
911 /// documentation for more.
912 ///
913 /// [`iter`]: struct.BinaryHeap.html#method.iter
914 /// [`BinaryHeap`]: struct.BinaryHeap.html
915 #[stable(feature = "rust1", since = "1.0.0")]
916 pub struct Iter<'a, T: 'a> {
917     iter: slice::Iter<'a, T>,
918 }
919
920 #[stable(feature = "collection_debug", since = "1.17.0")]
921 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
922     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
923         f.debug_tuple("Iter")
924          .field(&self.iter.as_slice())
925          .finish()
926     }
927 }
928
929 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
930 #[stable(feature = "rust1", since = "1.0.0")]
931 impl<'a, T> Clone for Iter<'a, T> {
932     fn clone(&self) -> Iter<'a, T> {
933         Iter { iter: self.iter.clone() }
934     }
935 }
936
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<'a, T> Iterator for Iter<'a, T> {
939     type Item = &'a T;
940
941     #[inline]
942     fn next(&mut self) -> Option<&'a T> {
943         self.iter.next()
944     }
945
946     #[inline]
947     fn size_hint(&self) -> (usize, Option<usize>) {
948         self.iter.size_hint()
949     }
950 }
951
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
954     #[inline]
955     fn next_back(&mut self) -> Option<&'a T> {
956         self.iter.next_back()
957     }
958 }
959
960 #[stable(feature = "rust1", since = "1.0.0")]
961 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
962     fn is_empty(&self) -> bool {
963         self.iter.is_empty()
964     }
965 }
966
967 #[stable(feature = "fused", since = "1.26.0")]
968 impl<'a, T> FusedIterator for Iter<'a, T> {}
969
970 /// An owning iterator over the elements of a `BinaryHeap`.
971 ///
972 /// This `struct` is created by the [`into_iter`] method on [`BinaryHeap`][`BinaryHeap`]
973 /// (provided by the `IntoIterator` trait). See its documentation for more.
974 ///
975 /// [`into_iter`]: struct.BinaryHeap.html#method.into_iter
976 /// [`BinaryHeap`]: struct.BinaryHeap.html
977 #[stable(feature = "rust1", since = "1.0.0")]
978 #[derive(Clone)]
979 pub struct IntoIter<T> {
980     iter: vec::IntoIter<T>,
981 }
982
983 #[stable(feature = "collection_debug", since = "1.17.0")]
984 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
985     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
986         f.debug_tuple("IntoIter")
987          .field(&self.iter.as_slice())
988          .finish()
989     }
990 }
991
992 #[stable(feature = "rust1", since = "1.0.0")]
993 impl<T> Iterator for IntoIter<T> {
994     type Item = T;
995
996     #[inline]
997     fn next(&mut self) -> Option<T> {
998         self.iter.next()
999     }
1000
1001     #[inline]
1002     fn size_hint(&self) -> (usize, Option<usize>) {
1003         self.iter.size_hint()
1004     }
1005 }
1006
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 impl<T> DoubleEndedIterator for IntoIter<T> {
1009     #[inline]
1010     fn next_back(&mut self) -> Option<T> {
1011         self.iter.next_back()
1012     }
1013 }
1014
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 impl<T> ExactSizeIterator for IntoIter<T> {
1017     fn is_empty(&self) -> bool {
1018         self.iter.is_empty()
1019     }
1020 }
1021
1022 #[stable(feature = "fused", since = "1.26.0")]
1023 impl<T> FusedIterator for IntoIter<T> {}
1024
1025 /// A draining iterator over the elements of a `BinaryHeap`.
1026 ///
1027 /// This `struct` is created by the [`drain`] method on [`BinaryHeap`]. See its
1028 /// documentation for more.
1029 ///
1030 /// [`drain`]: struct.BinaryHeap.html#method.drain
1031 /// [`BinaryHeap`]: struct.BinaryHeap.html
1032 #[stable(feature = "drain", since = "1.6.0")]
1033 #[derive(Debug)]
1034 pub struct Drain<'a, T: 'a> {
1035     iter: vec::Drain<'a, T>,
1036 }
1037
1038 #[stable(feature = "drain", since = "1.6.0")]
1039 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1040     type Item = T;
1041
1042     #[inline]
1043     fn next(&mut self) -> Option<T> {
1044         self.iter.next()
1045     }
1046
1047     #[inline]
1048     fn size_hint(&self) -> (usize, Option<usize>) {
1049         self.iter.size_hint()
1050     }
1051 }
1052
1053 #[stable(feature = "drain", since = "1.6.0")]
1054 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1055     #[inline]
1056     fn next_back(&mut self) -> Option<T> {
1057         self.iter.next_back()
1058     }
1059 }
1060
1061 #[stable(feature = "drain", since = "1.6.0")]
1062 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {
1063     fn is_empty(&self) -> bool {
1064         self.iter.is_empty()
1065     }
1066 }
1067
1068 #[stable(feature = "fused", since = "1.26.0")]
1069 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
1070
1071 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1072 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1073     fn from(vec: Vec<T>) -> BinaryHeap<T> {
1074         let mut heap = BinaryHeap { data: vec };
1075         heap.rebuild();
1076         heap
1077     }
1078 }
1079
1080 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1081 impl<T> From<BinaryHeap<T>> for Vec<T> {
1082     fn from(heap: BinaryHeap<T>) -> Vec<T> {
1083         heap.data
1084     }
1085 }
1086
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1089     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1090         BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1091     }
1092 }
1093
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 impl<T: Ord> IntoIterator for BinaryHeap<T> {
1096     type Item = T;
1097     type IntoIter = IntoIter<T>;
1098
1099     /// Creates a consuming iterator, that is, one that moves each value out of
1100     /// the binary heap in arbitrary order. The binary heap cannot be used
1101     /// after calling this.
1102     ///
1103     /// # Examples
1104     ///
1105     /// Basic usage:
1106     ///
1107     /// ```
1108     /// use std::collections::BinaryHeap;
1109     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1110     ///
1111     /// // Print 1, 2, 3, 4 in arbitrary order
1112     /// for x in heap.into_iter() {
1113     ///     // x has type i32, not &i32
1114     ///     println!("{}", x);
1115     /// }
1116     /// ```
1117     fn into_iter(self) -> IntoIter<T> {
1118         IntoIter { iter: self.data.into_iter() }
1119     }
1120 }
1121
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 impl<'a, T> IntoIterator for &'a BinaryHeap<T>
1124     where T: Ord
1125 {
1126     type Item = &'a T;
1127     type IntoIter = Iter<'a, T>;
1128
1129     fn into_iter(self) -> Iter<'a, T> {
1130         self.iter()
1131     }
1132 }
1133
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1136     #[inline]
1137     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1138         <Self as SpecExtend<I>>::spec_extend(self, iter);
1139     }
1140 }
1141
1142 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1143     default fn spec_extend(&mut self, iter: I) {
1144         self.extend_desugared(iter.into_iter());
1145     }
1146 }
1147
1148 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1149     fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1150         self.append(other);
1151     }
1152 }
1153
1154 impl<T: Ord> BinaryHeap<T> {
1155     fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1156         let iterator = iter.into_iter();
1157         let (lower, _) = iterator.size_hint();
1158
1159         self.reserve(lower);
1160
1161         for elem in iterator {
1162             self.push(elem);
1163         }
1164     }
1165 }
1166
1167 #[stable(feature = "extend_ref", since = "1.2.0")]
1168 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1169     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1170         self.extend(iter.into_iter().cloned());
1171     }
1172 }
1173
1174 #[unstable(feature = "collection_placement",
1175            reason = "placement protocol is subject to change",
1176            issue = "30172")]
1177 pub struct BinaryHeapPlace<'a, T: 'a>
1178 where T: Clone + Ord {
1179     heap: *mut BinaryHeap<T>,
1180     place: vec::PlaceBack<'a, T>,
1181 }
1182
1183 #[unstable(feature = "collection_placement",
1184            reason = "placement protocol is subject to change",
1185            issue = "30172")]
1186 impl<'a, T: Clone + Ord + fmt::Debug> fmt::Debug for BinaryHeapPlace<'a, T> {
1187     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1188         f.debug_tuple("BinaryHeapPlace")
1189          .field(&self.place)
1190          .finish()
1191     }
1192 }
1193
1194 #[unstable(feature = "collection_placement",
1195            reason = "placement protocol is subject to change",
1196            issue = "30172")]
1197 impl<'a, T: 'a> Placer<T> for &'a mut BinaryHeap<T>
1198 where T: Clone + Ord {
1199     type Place = BinaryHeapPlace<'a, T>;
1200
1201     fn make_place(self) -> Self::Place {
1202         let ptr = self as *mut BinaryHeap<T>;
1203         let place = Placer::make_place(self.data.place_back());
1204         BinaryHeapPlace {
1205             heap: ptr,
1206             place,
1207         }
1208     }
1209 }
1210
1211 #[unstable(feature = "collection_placement",
1212            reason = "placement protocol is subject to change",
1213            issue = "30172")]
1214 unsafe impl<'a, T> Place<T> for BinaryHeapPlace<'a, T>
1215 where T: Clone + Ord {
1216     fn pointer(&mut self) -> *mut T {
1217         self.place.pointer()
1218     }
1219 }
1220
1221 #[unstable(feature = "collection_placement",
1222            reason = "placement protocol is subject to change",
1223            issue = "30172")]
1224 impl<'a, T> InPlace<T> for BinaryHeapPlace<'a, T>
1225 where T: Clone + Ord {
1226     type Owner = &'a T;
1227
1228     unsafe fn finalize(self) -> &'a T {
1229         self.place.finalize();
1230
1231         let heap: &mut BinaryHeap<T> = &mut *self.heap;
1232         let len = heap.len();
1233         let i = heap.sift_up(0, len - 1);
1234         heap.data.get_unchecked(i)
1235     }
1236 }