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