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