1 //! A priority queue implemented with a binary heap.
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.
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.
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
21 //! use std::cmp::Ordering;
22 //! use std::collections::BinaryHeap;
25 //! #[derive(Copy, Clone, Eq, PartialEq)]
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))
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))
51 //! // Each node is represented as an `usize`, for a shorter implementation.
57 //! // Dijkstra's shortest path algorithm.
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();
67 //! let mut heap = BinaryHeap::new();
69 //! // We're at `start`, with a zero cost
71 //! heap.push(State { cost: 0, position: start });
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); }
78 //! // Important as we may have already found a better way
79 //! if cost > dist[position] { continue; }
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 };
86 //! // If so, add it to the frontier and continue
87 //! if next.cost < dist[next.position] {
89 //! // Relaxation, we have now found a better way
90 //! dist[next.position] = next.cost;
95 //! // Goal not reachable
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.
107 //! // +-----------------+
110 //! // 0 -----> 1 -----> 3 ---> 4
114 //! // +------> 2 -------+ |
116 //! // +---------------+
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![
123 //! vec![Edge { node: 2, cost: 10 },
124 //! Edge { node: 1, cost: 1 }],
126 //! vec![Edge { node: 3, cost: 2 }],
128 //! vec![Edge { node: 1, cost: 1 },
129 //! Edge { node: 3, cost: 3 },
130 //! Edge { node: 4, cost: 1 }],
132 //! vec![Edge { node: 0, cost: 7 },
133 //! Edge { node: 4, cost: 2 }],
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);
145 #![allow(missing_docs)]
146 #![stable(feature = "rust1", since = "1.0.0")]
148 use core::ops::{Deref, DerefMut};
149 use core::iter::{FromIterator, FusedIterator};
150 use core::mem::{swap, size_of, ManuallyDrop};
155 use crate::vec::{self, Vec};
157 use super::SpecExtend;
159 /// A priority queue implemented with a binary heap.
161 /// This will be a max-heap.
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.
171 /// use std::collections::BinaryHeap;
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();
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);
181 /// // Let's add some scores...
186 /// // Now peek shows the most important item in the heap.
187 /// assert_eq!(heap.peek(), Some(&5));
189 /// // We can check the length of a heap.
190 /// assert_eq!(heap.len(), 3);
192 /// // We can iterate over the items in the heap, although they are returned in
193 /// // a random order.
195 /// println!("{}", x);
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);
204 /// // We can clear the heap of any remaining items.
207 /// // The heap should now be empty.
208 /// assert!(heap.is_empty())
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.
218 /// use std::collections::BinaryHeap;
219 /// use std::cmp::Reverse;
221 /// let mut heap = BinaryHeap::new();
223 /// // Wrap values in `Reverse`
224 /// heap.push(Reverse(1));
225 /// heap.push(Reverse(5));
226 /// heap.push(Reverse(2));
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);
235 /// # Time complexity
237 /// | [push] | [pop] | [peek]/[peek\_mut] |
238 /// |--------|----------|--------------------|
239 /// | O(1)~ | O(log n) | O(1) |
241 /// The value for `push` is an expected cost; the method documentation gives a
242 /// more detailed analysis.
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> {
253 /// Structure wrapping a mutable reference to the greatest item on a
256 /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
257 /// its documentation for more.
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>,
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])
276 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
277 impl<T: Ord> Drop for PeekMut<'_, T> {
280 self.heap.sift_down(0);
285 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
286 impl<T: Ord> Deref for PeekMut<'_, 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) }
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) }
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();
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() }
320 fn clone_from(&mut self, source: &Self) {
321 self.data.clone_from(&source.data);
325 #[stable(feature = "rust1", since = "1.0.0")]
326 impl<T: Ord> Default for BinaryHeap<T> {
327 /// Creates an empty `BinaryHeap<T>`.
329 fn default() -> BinaryHeap<T> {
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()
341 impl<T: Ord> BinaryHeap<T> {
342 /// Creates an empty `BinaryHeap` as a max-heap.
349 /// use std::collections::BinaryHeap;
350 /// let mut heap = BinaryHeap::new();
353 #[stable(feature = "rust1", since = "1.0.0")]
354 pub fn new() -> BinaryHeap<T> {
355 BinaryHeap { data: vec![] }
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.
368 /// use std::collections::BinaryHeap;
369 /// let mut heap = BinaryHeap::with_capacity(10);
372 #[stable(feature = "rust1", since = "1.0.0")]
373 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
374 BinaryHeap { data: Vec::with_capacity(capacity) }
377 /// Returns a mutable reference to the greatest item in the binary heap, or
378 /// `None` if it is empty.
380 /// Note: If the `PeekMut` value is leaked, the heap may be in an
381 /// inconsistent state.
388 /// use std::collections::BinaryHeap;
389 /// let mut heap = BinaryHeap::new();
390 /// assert!(heap.peek_mut().is_none());
396 /// let mut val = heap.peek_mut().unwrap();
399 /// assert_eq!(heap.peek(), Some(&2));
402 /// # Time complexity
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>> {
417 /// Removes the greatest item from the binary heap and returns it, or `None` if it
425 /// use std::collections::BinaryHeap;
426 /// let mut heap = BinaryHeap::from(vec![1, 3]);
428 /// assert_eq!(heap.pop(), Some(3));
429 /// assert_eq!(heap.pop(), Some(1));
430 /// assert_eq!(heap.pop(), None);
433 /// # Time complexity
435 /// The worst case cost of `pop` on a heap containing *n* elements is O(log
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);
448 /// Pushes an item onto the binary heap.
455 /// use std::collections::BinaryHeap;
456 /// let mut heap = BinaryHeap::new();
461 /// assert_eq!(heap.len(), 3);
462 /// assert_eq!(heap.peek(), Some(&5));
465 /// # Time complexity
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.
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.
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);
487 /// Consumes the `BinaryHeap` and returns a vector in sorted
488 /// (ascending) order.
495 /// use std::collections::BinaryHeap;
497 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
501 /// let vec = heap.into_sorted_vec();
502 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
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();
509 self.data.swap(0, end);
510 self.sift_down_range(0, end);
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 {
525 // Take out the value at `pos` and create a hole.
526 let mut hole = Hole::new(&mut self.data, pos);
528 while hole.pos() > start {
529 let parent = (hole.pos() - 1) / 2;
530 if hole.element() <= hole.get(parent) {
533 hole.move_to(parent);
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) {
543 let mut hole = Hole::new(&mut self.data, pos);
544 let mut child = 2 * pos + 1;
546 let right = child + 1;
547 // compare with the greater of the two children
548 if right < end && !(hole.get(child) > hole.get(right)) {
551 // if we are already in order, stop.
552 if hole.element() >= hole.get(child) {
556 child = 2 * hole.pos() + 1;
561 fn sift_down(&mut self, pos: usize) {
562 let len = self.len();
563 self.sift_down_range(pos, len);
566 /// Take an element at `pos` and move it all the way down the heap,
567 /// then sift it up to its position.
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();
575 let mut hole = Hole::new(&mut self.data, pos);
576 let mut child = 2 * pos + 1;
578 let right = child + 1;
579 // compare with the greater of the two children
580 if right < end && !(hole.get(child) > hole.get(right)) {
584 child = 2 * hole.pos() + 1;
588 self.sift_up(start, pos);
591 fn rebuild(&mut self) {
592 let mut n = self.len() / 2;
599 /// Moves all the elements of `other` into `self`, leaving `other` empty.
606 /// use std::collections::BinaryHeap;
608 /// let v = vec![-10, 1, 2, 3, 3];
609 /// let mut a = BinaryHeap::from(v);
611 /// let v = vec![-20, 5, 43];
612 /// let mut b = BinaryHeap::from(v);
614 /// a.append(&mut b);
616 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
617 /// assert!(b.is_empty());
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() {
625 if other.is_empty() {
630 fn log2_fast(x: usize) -> usize {
631 8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
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.
640 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
641 2 * (len1 + len2) < len2 * log2_fast(len1)
644 if better_to_rebuild(self.len(), other.len()) {
645 self.data.append(&mut other.data);
648 self.extend(other.drain());
653 impl<T> BinaryHeap<T> {
654 /// Returns an iterator visiting all values in the underlying vector, in
662 /// use std::collections::BinaryHeap;
663 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
665 /// // Print 1, 2, 3, 4 in arbitrary order
666 /// for x in heap.iter() {
667 /// println!("{}", x);
670 #[stable(feature = "rust1", since = "1.0.0")]
671 pub fn iter(&self) -> Iter<'_, T> {
672 Iter { iter: self.data.iter() }
675 /// Returns the greatest item in the binary heap, or `None` if it is empty.
682 /// use std::collections::BinaryHeap;
683 /// let mut heap = BinaryHeap::new();
684 /// assert_eq!(heap.peek(), None);
689 /// assert_eq!(heap.peek(), Some(&5));
693 /// # Time complexity
695 /// Cost is O(1) in the worst case.
696 #[stable(feature = "rust1", since = "1.0.0")]
697 pub fn peek(&self) -> Option<&T> {
701 /// Returns the number of elements the binary heap can hold without reallocating.
708 /// use std::collections::BinaryHeap;
709 /// let mut heap = BinaryHeap::with_capacity(100);
710 /// assert!(heap.capacity() >= 100);
713 #[stable(feature = "rust1", since = "1.0.0")]
714 pub fn capacity(&self) -> usize {
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.
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.
727 /// Panics if the new capacity overflows `usize`.
734 /// use std::collections::BinaryHeap;
735 /// let mut heap = BinaryHeap::new();
736 /// heap.reserve_exact(100);
737 /// assert!(heap.capacity() >= 100);
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);
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.
752 /// Panics if the new capacity overflows `usize`.
759 /// use std::collections::BinaryHeap;
760 /// let mut heap = BinaryHeap::new();
761 /// heap.reserve(100);
762 /// assert!(heap.capacity() >= 100);
765 #[stable(feature = "rust1", since = "1.0.0")]
766 pub fn reserve(&mut self, additional: usize) {
767 self.data.reserve(additional);
770 /// Discards as much additional capacity as possible.
777 /// use std::collections::BinaryHeap;
778 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
780 /// assert!(heap.capacity() >= 100);
781 /// heap.shrink_to_fit();
782 /// assert!(heap.capacity() == 0);
784 #[stable(feature = "rust1", since = "1.0.0")]
785 pub fn shrink_to_fit(&mut self) {
786 self.data.shrink_to_fit();
789 /// Discards capacity with a lower bound.
791 /// The capacity will remain at least as large as both the length
792 /// and the supplied value.
794 /// Panics if the current capacity is smaller than the supplied
795 /// minimum capacity.
800 /// #![feature(shrink_to)]
801 /// use std::collections::BinaryHeap;
802 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
804 /// assert!(heap.capacity() >= 100);
805 /// heap.shrink_to(10);
806 /// assert!(heap.capacity() >= 10);
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)
814 /// Consumes the `BinaryHeap` and returns the underlying vector
815 /// in arbitrary order.
822 /// use std::collections::BinaryHeap;
823 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
824 /// let vec = heap.into_vec();
826 /// // Will print in some order
828 /// println!("{}", x);
831 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
832 pub fn into_vec(self) -> Vec<T> {
836 /// Returns the length of the binary heap.
843 /// use std::collections::BinaryHeap;
844 /// let heap = BinaryHeap::from(vec![1, 3]);
846 /// assert_eq!(heap.len(), 2);
848 #[stable(feature = "rust1", since = "1.0.0")]
849 pub fn len(&self) -> usize {
853 /// Checks if the binary heap is empty.
860 /// use std::collections::BinaryHeap;
861 /// let mut heap = BinaryHeap::new();
863 /// assert!(heap.is_empty());
869 /// assert!(!heap.is_empty());
871 #[stable(feature = "rust1", since = "1.0.0")]
872 pub fn is_empty(&self) -> bool {
876 /// Clears the binary heap, returning an iterator over the removed elements.
878 /// The elements are removed in arbitrary order.
885 /// use std::collections::BinaryHeap;
886 /// let mut heap = BinaryHeap::from(vec![1, 3]);
888 /// assert!(!heap.is_empty());
890 /// for x in heap.drain() {
891 /// println!("{}", x);
894 /// assert!(heap.is_empty());
897 #[stable(feature = "drain", since = "1.6.0")]
898 pub fn drain(&mut self) -> Drain<'_, T> {
899 Drain { iter: self.data.drain(..) }
902 /// Drops all items from the binary heap.
909 /// use std::collections::BinaryHeap;
910 /// let mut heap = BinaryHeap::from(vec![1, 3]);
912 /// assert!(!heap.is_empty());
916 /// assert!(heap.is_empty());
918 #[stable(feature = "rust1", since = "1.0.0")]
919 pub fn clear(&mut self) {
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> {
930 elt: ManuallyDrop<T>,
934 impl<'a, T> Hole<'a, T> {
935 /// Create a new `Hole` at index `pos`.
937 /// Unsafe because pos must be within the data slice.
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));
945 elt: ManuallyDrop::new(elt),
951 fn pos(&self) -> usize {
955 /// Returns a reference to the element removed.
957 fn element(&self) -> &T {
961 /// Returns a reference to the element at `index`.
963 /// Unsafe because index must be within the data slice and not equal to pos.
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)
971 /// Move hole to new location
973 /// Unsafe because index must be within the data slice and not equal to pos.
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);
985 impl<T> Drop for Hole<'_, T> {
988 // fill the hole again
991 ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
996 /// An iterator over the elements of a `BinaryHeap`.
998 /// This `struct` is created by the [`iter`] method on [`BinaryHeap`]. See its
999 /// documentation for more.
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>,
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())
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() }
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 impl<'a, T> Iterator for Iter<'a, T> {
1030 fn next(&mut self) -> Option<&'a T> {
1035 fn size_hint(&self) -> (usize, Option<usize>) {
1036 self.iter.size_hint()
1040 fn last(self) -> Option<&'a T> {
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1048 fn next_back(&mut self) -> Option<&'a T> {
1049 self.iter.next_back()
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()
1060 #[stable(feature = "fused", since = "1.26.0")]
1061 impl<T> FusedIterator for Iter<'_, T> {}
1063 /// An owning iterator over the elements of a `BinaryHeap`.
1065 /// This `struct` is created by the [`into_iter`] method on [`BinaryHeap`][`BinaryHeap`]
1066 /// (provided by the `IntoIterator` trait). See its documentation for more.
1068 /// [`into_iter`]: struct.BinaryHeap.html#method.into_iter
1069 /// [`BinaryHeap`]: struct.BinaryHeap.html
1070 #[stable(feature = "rust1", since = "1.0.0")]
1072 pub struct IntoIter<T> {
1073 iter: vec::IntoIter<T>,
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())
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 impl<T> Iterator for IntoIter<T> {
1090 fn next(&mut self) -> Option<T> {
1095 fn size_hint(&self) -> (usize, Option<usize>) {
1096 self.iter.size_hint()
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 impl<T> DoubleEndedIterator for IntoIter<T> {
1103 fn next_back(&mut self) -> Option<T> {
1104 self.iter.next_back()
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()
1115 #[stable(feature = "fused", since = "1.26.0")]
1116 impl<T> FusedIterator for IntoIter<T> {}
1118 /// A draining iterator over the elements of a `BinaryHeap`.
1120 /// This `struct` is created by the [`drain`] method on [`BinaryHeap`]. See its
1121 /// documentation for more.
1123 /// [`drain`]: struct.BinaryHeap.html#method.drain
1124 /// [`BinaryHeap`]: struct.BinaryHeap.html
1125 #[stable(feature = "drain", since = "1.6.0")]
1127 pub struct Drain<'a, T: 'a> {
1128 iter: vec::Drain<'a, T>,
1131 #[stable(feature = "drain", since = "1.6.0")]
1132 impl<T> Iterator for Drain<'_, T> {
1136 fn next(&mut self) -> Option<T> {
1141 fn size_hint(&self) -> (usize, Option<usize>) {
1142 self.iter.size_hint()
1146 #[stable(feature = "drain", since = "1.6.0")]
1147 impl<T> DoubleEndedIterator for Drain<'_, T> {
1149 fn next_back(&mut self) -> Option<T> {
1150 self.iter.next_back()
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()
1161 #[stable(feature = "fused", since = "1.26.0")]
1162 impl<T> FusedIterator for Drain<'_, T> {}
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>`.
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 };
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> {
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<_>>())
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 impl<T> IntoIterator for BinaryHeap<T> {
1193 type IntoIter = IntoIter<T>;
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.
1204 /// use std::collections::BinaryHeap;
1205 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
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);
1213 fn into_iter(self) -> IntoIter<T> {
1214 IntoIter { iter: self.data.into_iter() }
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<'a, T> IntoIterator for &'a BinaryHeap<T> {
1221 type IntoIter = Iter<'a, T>;
1223 fn into_iter(self) -> Iter<'a, T> {
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1231 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1232 <Self as SpecExtend<I>>::spec_extend(self, iter);
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());
1242 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1243 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
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();
1253 self.reserve(lower);
1255 iterator.for_each(move |elem| self.push(elem));
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());