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