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