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