1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A priority queue implemented with a binary heap.
13 //! Insertion and popping the largest element have `O(log n)` time complexity.
14 //! Checking the largest element is `O(1)`. Converting a vector to a binary heap
15 //! can be done in-place, and has `O(n)` complexity. A binary heap can also be
16 //! converted to a sorted vector in-place, allowing it to be used for an `O(n
17 //! log n)` in-place heapsort.
21 //! This is a larger example that implements [Dijkstra's algorithm][dijkstra]
22 //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
23 //! It shows how to use [`BinaryHeap`] with custom types.
25 //! [dijkstra]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
26 //! [sssp]: http://en.wikipedia.org/wiki/Shortest_path_problem
27 //! [dir_graph]: http://en.wikipedia.org/wiki/Directed_graph
28 //! [`BinaryHeap`]: struct.BinaryHeap.html
31 //! use std::cmp::Ordering;
32 //! use std::collections::BinaryHeap;
35 //! #[derive(Copy, Clone, Eq, PartialEq)]
41 //! // The priority queue depends on `Ord`.
42 //! // Explicitly implement the trait so the queue becomes a min-heap
43 //! // instead of a max-heap.
44 //! impl Ord for State {
45 //! fn cmp(&self, other: &State) -> Ordering {
46 //! // Notice that the we flip the ordering here
47 //! other.cost.cmp(&self.cost)
51 //! // `PartialOrd` needs to be implemented as well.
52 //! impl PartialOrd for State {
53 //! fn partial_cmp(&self, other: &State) -> Option<Ordering> {
54 //! Some(self.cmp(other))
58 //! // Each node is represented as an `usize`, for a shorter implementation.
64 //! // Dijkstra's shortest path algorithm.
66 //! // Start at `start` and use `dist` to track the current shortest distance
67 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
68 //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
69 //! // for a simpler implementation.
70 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
71 //! // dist[node] = current shortest distance from `start` to `node`
72 //! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
74 //! let mut heap = BinaryHeap::new();
76 //! // We're at `start`, with a zero cost
78 //! heap.push(State { cost: 0, position: start });
80 //! // Examine the frontier with lower cost nodes first (min-heap)
81 //! while let Some(State { cost, position }) = heap.pop() {
82 //! // Alternatively we could have continued to find all shortest paths
83 //! if position == goal { return Some(cost); }
85 //! // Important as we may have already found a better way
86 //! if cost > dist[position] { continue; }
88 //! // For each node we can reach, see if we can find a way with
89 //! // a lower cost going through this node
90 //! for edge in &adj_list[position] {
91 //! let next = State { cost: cost + edge.cost, position: edge.node };
93 //! // If so, add it to the frontier and continue
94 //! if next.cost < dist[next.position] {
96 //! // Relaxation, we have now found a better way
97 //! dist[next.position] = next.cost;
102 //! // Goal not reachable
107 //! // This is the directed graph we're going to use.
108 //! // The node numbers correspond to the different states,
109 //! // and the edge weights symbolize the cost of moving
110 //! // from one node to another.
111 //! // Note that the edges are one-way.
114 //! // +-----------------+
117 //! // 0 -----> 1 -----> 3 ---> 4
121 //! // +------> 2 -------+ |
123 //! // +---------------+
125 //! // The graph is represented as an adjacency list where each index,
126 //! // corresponding to a node value, has a list of outgoing edges.
127 //! // Chosen for its efficiency.
128 //! let graph = vec![
130 //! vec![Edge { node: 2, cost: 10 },
131 //! Edge { node: 1, cost: 1 }],
133 //! vec![Edge { node: 3, cost: 2 }],
135 //! vec![Edge { node: 1, cost: 1 },
136 //! Edge { node: 3, cost: 3 },
137 //! Edge { node: 4, cost: 1 }],
139 //! vec![Edge { node: 0, cost: 7 },
140 //! Edge { node: 4, cost: 2 }],
144 //! assert_eq!(shortest_path(&graph, 0, 1), Some(1));
145 //! assert_eq!(shortest_path(&graph, 0, 3), Some(3));
146 //! assert_eq!(shortest_path(&graph, 3, 0), Some(7));
147 //! assert_eq!(shortest_path(&graph, 0, 4), Some(5));
148 //! assert_eq!(shortest_path(&graph, 4, 0), None);
152 #![allow(missing_docs)]
153 #![stable(feature = "rust1", since = "1.0.0")]
155 use core::ops::{Deref, DerefMut, Place, Placer, InPlace};
156 use core::iter::{FromIterator, FusedIterator};
157 use core::mem::{swap, size_of};
162 use vec::{self, Vec};
164 use super::SpecExtend;
166 /// A priority queue implemented with a binary heap.
168 /// This will be a max-heap.
170 /// It is a logic error for an item to be modified in such a way that the
171 /// item's ordering relative to any other item, as determined by the `Ord`
172 /// trait, changes while it is in the heap. This is normally only possible
173 /// through `Cell`, `RefCell`, global state, I/O, or unsafe code.
178 /// use std::collections::BinaryHeap;
180 /// // Type inference lets us omit an explicit type signature (which
181 /// // would be `BinaryHeap<i32>` in this example).
182 /// let mut heap = BinaryHeap::new();
184 /// // We can use peek to look at the next item in the heap. In this case,
185 /// // there's no items in there yet so we get None.
186 /// assert_eq!(heap.peek(), None);
188 /// // Let's add some scores...
193 /// // Now peek shows the most important item in the heap.
194 /// assert_eq!(heap.peek(), Some(&5));
196 /// // We can check the length of a heap.
197 /// assert_eq!(heap.len(), 3);
199 /// // We can iterate over the items in the heap, although they are returned in
200 /// // a random order.
202 /// println!("{}", x);
205 /// // If we instead pop these scores, they should come back in order.
206 /// assert_eq!(heap.pop(), Some(5));
207 /// assert_eq!(heap.pop(), Some(2));
208 /// assert_eq!(heap.pop(), Some(1));
209 /// assert_eq!(heap.pop(), None);
211 /// // We can clear the heap of any remaining items.
214 /// // The heap should now be empty.
215 /// assert!(heap.is_empty())
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub struct BinaryHeap<T> {
222 /// Structure wrapping a mutable reference to the greatest item on a
225 /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
226 /// its documentation for more.
228 /// [`peek_mut`]: struct.BinaryHeap.html#method.peek_mut
229 /// [`BinaryHeap`]: struct.BinaryHeap.html
230 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
231 pub struct PeekMut<'a, T: 'a + Ord> {
232 heap: &'a mut BinaryHeap<T>,
236 #[stable(feature = "collection_debug", since = "1.17.0")]
237 impl<'a, T: Ord + fmt::Debug> fmt::Debug for PeekMut<'a, T> {
238 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
239 f.debug_tuple("PeekMut")
240 .field(&self.heap.data[0])
245 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
246 impl<'a, T: Ord> Drop for PeekMut<'a, T> {
249 self.heap.sift_down(0);
254 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
255 impl<'a, T: Ord> Deref for PeekMut<'a, T> {
257 fn deref(&self) -> &T {
262 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
263 impl<'a, T: Ord> DerefMut for PeekMut<'a, T> {
264 fn deref_mut(&mut self) -> &mut T {
265 &mut self.heap.data[0]
269 impl<'a, T: Ord> PeekMut<'a, T> {
270 /// Removes the peeked value from the heap and returns it.
271 #[unstable(feature = "binary_heap_peek_mut_pop", issue = "38863")]
272 pub fn pop(mut this: PeekMut<'a, T>) -> T {
273 let value = this.heap.pop().unwrap();
279 #[stable(feature = "rust1", since = "1.0.0")]
280 impl<T: Clone> Clone for BinaryHeap<T> {
281 fn clone(&self) -> Self {
282 BinaryHeap { data: self.data.clone() }
285 fn clone_from(&mut self, source: &Self) {
286 self.data.clone_from(&source.data);
290 #[stable(feature = "rust1", since = "1.0.0")]
291 impl<T: Ord> Default for BinaryHeap<T> {
292 /// Creates an empty `BinaryHeap<T>`.
294 fn default() -> BinaryHeap<T> {
299 #[stable(feature = "binaryheap_debug", since = "1.4.0")]
300 impl<T: fmt::Debug + Ord> fmt::Debug for BinaryHeap<T> {
301 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
302 f.debug_list().entries(self.iter()).finish()
306 impl<T: Ord> BinaryHeap<T> {
307 /// Creates an empty `BinaryHeap` as a max-heap.
314 /// use std::collections::BinaryHeap;
315 /// let mut heap = BinaryHeap::new();
318 #[stable(feature = "rust1", since = "1.0.0")]
319 pub fn new() -> BinaryHeap<T> {
320 BinaryHeap { data: vec![] }
323 /// Creates an empty `BinaryHeap` with a specific capacity.
324 /// This preallocates enough memory for `capacity` elements,
325 /// so that the `BinaryHeap` does not have to be reallocated
326 /// until it contains at least that many values.
333 /// use std::collections::BinaryHeap;
334 /// let mut heap = BinaryHeap::with_capacity(10);
337 #[stable(feature = "rust1", since = "1.0.0")]
338 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
339 BinaryHeap { data: Vec::with_capacity(capacity) }
342 /// Returns an iterator visiting all values in the underlying vector, in
350 /// use std::collections::BinaryHeap;
351 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
353 /// // Print 1, 2, 3, 4 in arbitrary order
354 /// for x in heap.iter() {
355 /// println!("{}", x);
358 #[stable(feature = "rust1", since = "1.0.0")]
359 pub fn iter(&self) -> Iter<T> {
360 Iter { iter: self.data.iter() }
363 /// Returns the greatest item in the binary heap, or `None` if it is empty.
370 /// use std::collections::BinaryHeap;
371 /// let mut heap = BinaryHeap::new();
372 /// assert_eq!(heap.peek(), None);
377 /// assert_eq!(heap.peek(), Some(&5));
380 #[stable(feature = "rust1", since = "1.0.0")]
381 pub fn peek(&self) -> Option<&T> {
385 /// Returns a mutable reference to the greatest item in the binary heap, or
386 /// `None` if it is empty.
388 /// Note: If the `PeekMut` value is leaked, the heap may be in an
389 /// inconsistent state.
396 /// use std::collections::BinaryHeap;
397 /// let mut heap = BinaryHeap::new();
398 /// assert!(heap.peek_mut().is_none());
404 /// let mut val = heap.peek_mut().unwrap();
407 /// assert_eq!(heap.peek(), Some(&2));
409 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
410 pub fn peek_mut(&mut self) -> Option<PeekMut<T>> {
421 /// Returns the number of elements the binary heap can hold without reallocating.
428 /// use std::collections::BinaryHeap;
429 /// let mut heap = BinaryHeap::with_capacity(100);
430 /// assert!(heap.capacity() >= 100);
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn capacity(&self) -> usize {
438 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
439 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
441 /// Note that the allocator may give the collection more space than it requests. Therefore
442 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
443 /// insertions are expected.
447 /// Panics if the new capacity overflows `usize`.
454 /// use std::collections::BinaryHeap;
455 /// let mut heap = BinaryHeap::new();
456 /// heap.reserve_exact(100);
457 /// assert!(heap.capacity() >= 100);
461 /// [`reserve`]: #method.reserve
462 #[stable(feature = "rust1", since = "1.0.0")]
463 pub fn reserve_exact(&mut self, additional: usize) {
464 self.data.reserve_exact(additional);
467 /// Reserves capacity for at least `additional` more elements to be inserted in the
468 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
472 /// Panics if the new capacity overflows `usize`.
479 /// use std::collections::BinaryHeap;
480 /// let mut heap = BinaryHeap::new();
481 /// heap.reserve(100);
482 /// assert!(heap.capacity() >= 100);
485 #[stable(feature = "rust1", since = "1.0.0")]
486 pub fn reserve(&mut self, additional: usize) {
487 self.data.reserve(additional);
490 /// Discards as much additional capacity as possible.
497 /// use std::collections::BinaryHeap;
498 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
500 /// assert!(heap.capacity() >= 100);
501 /// heap.shrink_to_fit();
502 /// assert!(heap.capacity() == 0);
504 #[stable(feature = "rust1", since = "1.0.0")]
505 pub fn shrink_to_fit(&mut self) {
506 self.data.shrink_to_fit();
509 /// Removes the greatest item from the binary heap and returns it, or `None` if it
517 /// use std::collections::BinaryHeap;
518 /// let mut heap = BinaryHeap::from(vec![1, 3]);
520 /// assert_eq!(heap.pop(), Some(3));
521 /// assert_eq!(heap.pop(), Some(1));
522 /// assert_eq!(heap.pop(), None);
524 #[stable(feature = "rust1", since = "1.0.0")]
525 pub fn pop(&mut self) -> Option<T> {
526 self.data.pop().map(|mut item| {
527 if !self.is_empty() {
528 swap(&mut item, &mut self.data[0]);
529 self.sift_down_to_bottom(0);
535 /// Pushes an item onto the binary heap.
542 /// use std::collections::BinaryHeap;
543 /// let mut heap = BinaryHeap::new();
548 /// assert_eq!(heap.len(), 3);
549 /// assert_eq!(heap.peek(), Some(&5));
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn push(&mut self, item: T) {
553 let old_len = self.len();
554 self.data.push(item);
555 self.sift_up(0, old_len);
558 /// Pushes an item onto the binary heap, then pops the greatest item off the queue in
559 /// an optimized fashion.
566 /// #![feature(binary_heap_extras)]
567 /// #![allow(deprecated)]
569 /// use std::collections::BinaryHeap;
570 /// let mut heap = BinaryHeap::new();
574 /// assert_eq!(heap.push_pop(3), 5);
575 /// assert_eq!(heap.push_pop(9), 9);
576 /// assert_eq!(heap.len(), 2);
577 /// assert_eq!(heap.peek(), Some(&3));
579 #[unstable(feature = "binary_heap_extras",
580 reason = "needs to be audited",
582 #[rustc_deprecated(since = "1.13.0", reason = "use `peek_mut` instead")]
583 pub fn push_pop(&mut self, mut item: T) -> T {
584 match self.data.get_mut(0) {
588 swap(&mut item, top);
599 /// Pops the greatest item off the binary heap, then pushes an item onto the queue in
600 /// an optimized fashion. The push is done regardless of whether the binary heap
608 /// #![feature(binary_heap_extras)]
609 /// #![allow(deprecated)]
611 /// use std::collections::BinaryHeap;
612 /// let mut heap = BinaryHeap::new();
614 /// assert_eq!(heap.replace(1), None);
615 /// assert_eq!(heap.replace(3), Some(1));
616 /// assert_eq!(heap.len(), 1);
617 /// assert_eq!(heap.peek(), Some(&3));
619 #[unstable(feature = "binary_heap_extras",
620 reason = "needs to be audited",
622 #[rustc_deprecated(since = "1.13.0", reason = "use `peek_mut` instead")]
623 pub fn replace(&mut self, mut item: T) -> Option<T> {
624 if !self.is_empty() {
625 swap(&mut item, &mut self.data[0]);
634 /// Consumes the `BinaryHeap` and returns the underlying vector
635 /// in arbitrary order.
642 /// use std::collections::BinaryHeap;
643 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
644 /// let vec = heap.into_vec();
646 /// // Will print in some order
648 /// println!("{}", x);
651 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
652 pub fn into_vec(self) -> Vec<T> {
656 /// Consumes the `BinaryHeap` and returns a vector in sorted
657 /// (ascending) order.
664 /// use std::collections::BinaryHeap;
666 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
670 /// let vec = heap.into_sorted_vec();
671 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
673 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
674 pub fn into_sorted_vec(mut self) -> Vec<T> {
675 let mut end = self.len();
678 self.data.swap(0, end);
679 self.sift_down_range(0, end);
684 // The implementations of sift_up and sift_down use unsafe blocks in
685 // order to move an element out of the vector (leaving behind a
686 // hole), shift along the others and move the removed element back into the
687 // vector at the final location of the hole.
688 // The `Hole` type is used to represent this, and make sure
689 // the hole is filled back at the end of its scope, even on panic.
690 // Using a hole reduces the constant factor compared to using swaps,
691 // which involves twice as many moves.
692 fn sift_up(&mut self, start: usize, pos: usize) -> usize {
694 // Take out the value at `pos` and create a hole.
695 let mut hole = Hole::new(&mut self.data, pos);
697 while hole.pos() > start {
698 let parent = (hole.pos() - 1) / 2;
699 if hole.element() <= hole.get(parent) {
702 hole.move_to(parent);
708 /// Take an element at `pos` and move it down the heap,
709 /// while its children are larger.
710 fn sift_down_range(&mut self, pos: usize, end: usize) {
712 let mut hole = Hole::new(&mut self.data, pos);
713 let mut child = 2 * pos + 1;
715 let right = child + 1;
716 // compare with the greater of the two children
717 if right < end && !(hole.get(child) > hole.get(right)) {
720 // if we are already in order, stop.
721 if hole.element() >= hole.get(child) {
725 child = 2 * hole.pos() + 1;
730 fn sift_down(&mut self, pos: usize) {
731 let len = self.len();
732 self.sift_down_range(pos, len);
735 /// Take an element at `pos` and move it all the way down the heap,
736 /// then sift it up to its position.
738 /// Note: This is faster when the element is known to be large / should
739 /// be closer to the bottom.
740 fn sift_down_to_bottom(&mut self, mut pos: usize) {
741 let end = self.len();
744 let mut hole = Hole::new(&mut self.data, pos);
745 let mut child = 2 * pos + 1;
747 let right = child + 1;
748 // compare with the greater of the two children
749 if right < end && !(hole.get(child) > hole.get(right)) {
753 child = 2 * hole.pos() + 1;
757 self.sift_up(start, pos);
760 /// Returns the length of the binary heap.
767 /// use std::collections::BinaryHeap;
768 /// let heap = BinaryHeap::from(vec![1, 3]);
770 /// assert_eq!(heap.len(), 2);
772 #[stable(feature = "rust1", since = "1.0.0")]
773 pub fn len(&self) -> usize {
777 /// Checks if the binary heap is empty.
784 /// use std::collections::BinaryHeap;
785 /// let mut heap = BinaryHeap::new();
787 /// assert!(heap.is_empty());
793 /// assert!(!heap.is_empty());
795 #[stable(feature = "rust1", since = "1.0.0")]
796 pub fn is_empty(&self) -> bool {
800 /// Clears the binary heap, returning an iterator over the removed elements.
802 /// The elements are removed in arbitrary order.
809 /// use std::collections::BinaryHeap;
810 /// let mut heap = BinaryHeap::from(vec![1, 3]);
812 /// assert!(!heap.is_empty());
814 /// for x in heap.drain() {
815 /// println!("{}", x);
818 /// assert!(heap.is_empty());
821 #[stable(feature = "drain", since = "1.6.0")]
822 pub fn drain(&mut self) -> Drain<T> {
823 Drain { iter: self.data.drain(..) }
826 /// Drops all items from the binary heap.
833 /// use std::collections::BinaryHeap;
834 /// let mut heap = BinaryHeap::from(vec![1, 3]);
836 /// assert!(!heap.is_empty());
840 /// assert!(heap.is_empty());
842 #[stable(feature = "rust1", since = "1.0.0")]
843 pub fn clear(&mut self) {
847 fn rebuild(&mut self) {
848 let mut n = self.len() / 2;
855 /// Moves all the elements of `other` into `self`, leaving `other` empty.
862 /// use std::collections::BinaryHeap;
864 /// let v = vec![-10, 1, 2, 3, 3];
865 /// let mut a = BinaryHeap::from(v);
867 /// let v = vec![-20, 5, 43];
868 /// let mut b = BinaryHeap::from(v);
870 /// a.append(&mut b);
872 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
873 /// assert!(b.is_empty());
875 #[stable(feature = "binary_heap_append", since = "1.11.0")]
876 pub fn append(&mut self, other: &mut Self) {
877 if self.len() < other.len() {
881 if other.is_empty() {
886 fn log2_fast(x: usize) -> usize {
887 8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
890 // `rebuild` takes O(len1 + len2) operations
891 // and about 2 * (len1 + len2) comparisons in the worst case
892 // while `extend` takes O(len2 * log_2(len1)) operations
893 // and about 1 * len2 * log_2(len1) comparisons in the worst case,
894 // assuming len1 >= len2.
896 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
897 2 * (len1 + len2) < len2 * log2_fast(len1)
900 if better_to_rebuild(self.len(), other.len()) {
901 self.data.append(&mut other.data);
904 self.extend(other.drain());
909 /// Hole represents a hole in a slice i.e. an index without valid value
910 /// (because it was moved from or duplicated).
911 /// In drop, `Hole` will restore the slice by filling the hole
912 /// position with the value that was originally removed.
913 struct Hole<'a, T: 'a> {
915 /// `elt` is always `Some` from new until drop.
920 impl<'a, T> Hole<'a, T> {
921 /// Create a new Hole at index `pos`.
923 /// Unsafe because pos must be within the data slice.
925 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
926 debug_assert!(pos < data.len());
927 let elt = ptr::read(&data[pos]);
936 fn pos(&self) -> usize {
940 /// Returns a reference to the element removed.
942 fn element(&self) -> &T {
943 self.elt.as_ref().unwrap()
946 /// Returns a reference to the element at `index`.
948 /// Unsafe because index must be within the data slice and not equal to pos.
950 unsafe fn get(&self, index: usize) -> &T {
951 debug_assert!(index != self.pos);
952 debug_assert!(index < self.data.len());
953 self.data.get_unchecked(index)
956 /// Move hole to new location
958 /// Unsafe because index must be within the data slice and not equal to pos.
960 unsafe fn move_to(&mut self, index: usize) {
961 debug_assert!(index != self.pos);
962 debug_assert!(index < self.data.len());
963 let index_ptr: *const _ = self.data.get_unchecked(index);
964 let hole_ptr = self.data.get_unchecked_mut(self.pos);
965 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
970 impl<'a, T> Drop for Hole<'a, T> {
973 // fill the hole again
976 ptr::write(self.data.get_unchecked_mut(pos), self.elt.take().unwrap());
981 /// An iterator over the elements of a `BinaryHeap`.
983 /// This `struct` is created by the [`iter`] method on [`BinaryHeap`]. See its
984 /// documentation for more.
986 /// [`iter`]: struct.BinaryHeap.html#method.iter
987 /// [`BinaryHeap`]: struct.BinaryHeap.html
988 #[stable(feature = "rust1", since = "1.0.0")]
989 pub struct Iter<'a, T: 'a> {
990 iter: slice::Iter<'a, T>,
993 #[stable(feature = "collection_debug", since = "1.17.0")]
994 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
995 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
996 f.debug_tuple("Iter")
997 .field(&self.iter.as_slice())
1002 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004 impl<'a, T> Clone for Iter<'a, T> {
1005 fn clone(&self) -> Iter<'a, T> {
1006 Iter { iter: self.iter.clone() }
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 impl<'a, T> Iterator for Iter<'a, T> {
1015 fn next(&mut self) -> Option<&'a T> {
1020 fn size_hint(&self) -> (usize, Option<usize>) {
1021 self.iter.size_hint()
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1028 fn next_back(&mut self) -> Option<&'a T> {
1029 self.iter.next_back()
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
1035 fn is_empty(&self) -> bool {
1036 self.iter.is_empty()
1040 #[unstable(feature = "fused", issue = "35602")]
1041 impl<'a, T> FusedIterator for Iter<'a, T> {}
1043 /// An owning iterator over the elements of a `BinaryHeap`.
1045 /// This `struct` is created by the [`into_iter`] method on [`BinaryHeap`]
1046 /// (provided by the `IntoIterator` trait). See its documentation for more.
1048 /// [`into_iter`]: struct.BinaryHeap.html#method.into_iter
1049 /// [`BinaryHeap`]: struct.BinaryHeap.html
1050 #[stable(feature = "rust1", since = "1.0.0")]
1052 pub struct IntoIter<T> {
1053 iter: vec::IntoIter<T>,
1056 #[stable(feature = "collection_debug", since = "1.17.0")]
1057 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1058 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1059 f.debug_tuple("IntoIter")
1060 .field(&self.iter.as_slice())
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 impl<T> Iterator for IntoIter<T> {
1070 fn next(&mut self) -> Option<T> {
1075 fn size_hint(&self) -> (usize, Option<usize>) {
1076 self.iter.size_hint()
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl<T> DoubleEndedIterator for IntoIter<T> {
1083 fn next_back(&mut self) -> Option<T> {
1084 self.iter.next_back()
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 impl<T> ExactSizeIterator for IntoIter<T> {
1090 fn is_empty(&self) -> bool {
1091 self.iter.is_empty()
1095 #[unstable(feature = "fused", issue = "35602")]
1096 impl<T> FusedIterator for IntoIter<T> {}
1098 /// A draining iterator over the elements of a `BinaryHeap`.
1100 /// This `struct` is created by the [`drain`] method on [`BinaryHeap`]. See its
1101 /// documentation for more.
1103 /// [`drain`]: struct.BinaryHeap.html#method.drain
1104 /// [`BinaryHeap`]: struct.BinaryHeap.html
1105 #[stable(feature = "drain", since = "1.6.0")]
1107 pub struct Drain<'a, T: 'a> {
1108 iter: vec::Drain<'a, T>,
1111 #[stable(feature = "drain", since = "1.6.0")]
1112 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1116 fn next(&mut self) -> Option<T> {
1121 fn size_hint(&self) -> (usize, Option<usize>) {
1122 self.iter.size_hint()
1126 #[stable(feature = "drain", since = "1.6.0")]
1127 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1129 fn next_back(&mut self) -> Option<T> {
1130 self.iter.next_back()
1134 #[stable(feature = "drain", since = "1.6.0")]
1135 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {
1136 fn is_empty(&self) -> bool {
1137 self.iter.is_empty()
1141 #[unstable(feature = "fused", issue = "35602")]
1142 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
1144 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1145 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1146 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1147 let mut heap = BinaryHeap { data: vec };
1153 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1154 impl<T> From<BinaryHeap<T>> for Vec<T> {
1155 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1160 #[stable(feature = "rust1", since = "1.0.0")]
1161 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1162 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1163 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 impl<T: Ord> IntoIterator for BinaryHeap<T> {
1170 type IntoIter = IntoIter<T>;
1172 /// Creates a consuming iterator, that is, one that moves each value out of
1173 /// the binary heap in arbitrary order. The binary heap cannot be used
1174 /// after calling this.
1181 /// use std::collections::BinaryHeap;
1182 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1184 /// // Print 1, 2, 3, 4 in arbitrary order
1185 /// for x in heap.into_iter() {
1186 /// // x has type i32, not &i32
1187 /// println!("{}", x);
1190 fn into_iter(self) -> IntoIter<T> {
1191 IntoIter { iter: self.data.into_iter() }
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 impl<'a, T> IntoIterator for &'a BinaryHeap<T>
1200 type IntoIter = Iter<'a, T>;
1202 fn into_iter(self) -> Iter<'a, T> {
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1210 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1211 <Self as SpecExtend<I>>::spec_extend(self, iter);
1215 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1216 default fn spec_extend(&mut self, iter: I) {
1217 self.extend_desugared(iter.into_iter());
1221 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1222 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1227 impl<T: Ord> BinaryHeap<T> {
1228 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1229 let iterator = iter.into_iter();
1230 let (lower, _) = iterator.size_hint();
1232 self.reserve(lower);
1234 for elem in iterator {
1240 #[stable(feature = "extend_ref", since = "1.2.0")]
1241 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1242 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1243 self.extend(iter.into_iter().cloned());
1247 #[unstable(feature = "collection_placement",
1248 reason = "placement protocol is subject to change",
1250 pub struct BinaryHeapPlace<'a, T: 'a>
1251 where T: Clone + Ord {
1252 heap: *mut BinaryHeap<T>,
1253 place: vec::PlaceBack<'a, T>,
1256 #[unstable(feature = "collection_placement",
1257 reason = "placement protocol is subject to change",
1259 impl<'a, T: Clone + Ord + fmt::Debug> fmt::Debug for BinaryHeapPlace<'a, T> {
1260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1261 f.debug_tuple("BinaryHeapPlace")
1267 #[unstable(feature = "collection_placement",
1268 reason = "placement protocol is subject to change",
1270 impl<'a, T: 'a> Placer<T> for &'a mut BinaryHeap<T>
1271 where T: Clone + Ord {
1272 type Place = BinaryHeapPlace<'a, T>;
1274 fn make_place(self) -> Self::Place {
1275 let ptr = self as *mut BinaryHeap<T>;
1276 let place = Placer::make_place(self.data.place_back());
1284 #[unstable(feature = "collection_placement",
1285 reason = "placement protocol is subject to change",
1287 impl<'a, T> Place<T> for BinaryHeapPlace<'a, T>
1288 where T: Clone + Ord {
1289 fn pointer(&mut self) -> *mut T {
1290 self.place.pointer()
1294 #[unstable(feature = "collection_placement",
1295 reason = "placement protocol is subject to change",
1297 impl<'a, T> InPlace<T> for BinaryHeapPlace<'a, T>
1298 where T: Clone + Ord {
1301 unsafe fn finalize(self) -> &'a T {
1302 self.place.finalize();
1304 let heap: &mut BinaryHeap<T> = &mut *self.heap;
1305 let len = heap.len();
1306 let i = heap.sift_up(0, len - 1);
1307 heap.data.get_unchecked(i)