]> git.lizzy.rs Git - rust.git/blob - src/libcollections/binary_heap.rs
More methods for str boxes.
[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     /// Pushes an item onto the binary heap, then pops the greatest item off the queue in
559     /// an optimized fashion.
560     ///
561     /// # Examples
562     ///
563     /// Basic usage:
564     ///
565     /// ```
566     /// #![feature(binary_heap_extras)]
567     /// #![allow(deprecated)]
568     ///
569     /// use std::collections::BinaryHeap;
570     /// let mut heap = BinaryHeap::new();
571     /// heap.push(1);
572     /// heap.push(5);
573     ///
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));
578     /// ```
579     #[unstable(feature = "binary_heap_extras",
580                reason = "needs to be audited",
581                issue = "28147")]
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) {
585             None => return item,
586             Some(top) => {
587                 if *top > item {
588                     swap(&mut item, top);
589                 } else {
590                     return item;
591                 }
592             }
593         }
594
595         self.sift_down(0);
596         item
597     }
598
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
601     /// was empty.
602     ///
603     /// # Examples
604     ///
605     /// Basic usage:
606     ///
607     /// ```
608     /// #![feature(binary_heap_extras)]
609     /// #![allow(deprecated)]
610     ///
611     /// use std::collections::BinaryHeap;
612     /// let mut heap = BinaryHeap::new();
613     ///
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));
618     /// ```
619     #[unstable(feature = "binary_heap_extras",
620                reason = "needs to be audited",
621                issue = "28147")]
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]);
626             self.sift_down(0);
627             Some(item)
628         } else {
629             self.push(item);
630             None
631         }
632     }
633
634     /// Consumes the `BinaryHeap` and returns the underlying vector
635     /// in arbitrary order.
636     ///
637     /// # Examples
638     ///
639     /// Basic usage:
640     ///
641     /// ```
642     /// use std::collections::BinaryHeap;
643     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
644     /// let vec = heap.into_vec();
645     ///
646     /// // Will print in some order
647     /// for x in vec {
648     ///     println!("{}", x);
649     /// }
650     /// ```
651     #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
652     pub fn into_vec(self) -> Vec<T> {
653         self.into()
654     }
655
656     /// Consumes the `BinaryHeap` and returns a vector in sorted
657     /// (ascending) order.
658     ///
659     /// # Examples
660     ///
661     /// Basic usage:
662     ///
663     /// ```
664     /// use std::collections::BinaryHeap;
665     ///
666     /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
667     /// heap.push(6);
668     /// heap.push(3);
669     ///
670     /// let vec = heap.into_sorted_vec();
671     /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
672     /// ```
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();
676         while end > 1 {
677             end -= 1;
678             self.data.swap(0, end);
679             self.sift_down_range(0, end);
680         }
681         self.into_vec()
682     }
683
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 {
693         unsafe {
694             // Take out the value at `pos` and create a hole.
695             let mut hole = Hole::new(&mut self.data, pos);
696
697             while hole.pos() > start {
698                 let parent = (hole.pos() - 1) / 2;
699                 if hole.element() <= hole.get(parent) {
700                     break;
701                 }
702                 hole.move_to(parent);
703             }
704             hole.pos()
705         }
706     }
707
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) {
711         unsafe {
712             let mut hole = Hole::new(&mut self.data, pos);
713             let mut child = 2 * pos + 1;
714             while child < end {
715                 let right = child + 1;
716                 // compare with the greater of the two children
717                 if right < end && !(hole.get(child) > hole.get(right)) {
718                     child = right;
719                 }
720                 // if we are already in order, stop.
721                 if hole.element() >= hole.get(child) {
722                     break;
723                 }
724                 hole.move_to(child);
725                 child = 2 * hole.pos() + 1;
726             }
727         }
728     }
729
730     fn sift_down(&mut self, pos: usize) {
731         let len = self.len();
732         self.sift_down_range(pos, len);
733     }
734
735     /// Take an element at `pos` and move it all the way down the heap,
736     /// then sift it up to its position.
737     ///
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();
742         let start = pos;
743         unsafe {
744             let mut hole = Hole::new(&mut self.data, pos);
745             let mut child = 2 * pos + 1;
746             while child < end {
747                 let right = child + 1;
748                 // compare with the greater of the two children
749                 if right < end && !(hole.get(child) > hole.get(right)) {
750                     child = right;
751                 }
752                 hole.move_to(child);
753                 child = 2 * hole.pos() + 1;
754             }
755             pos = hole.pos;
756         }
757         self.sift_up(start, pos);
758     }
759
760     /// Returns the length of the binary heap.
761     ///
762     /// # Examples
763     ///
764     /// Basic usage:
765     ///
766     /// ```
767     /// use std::collections::BinaryHeap;
768     /// let heap = BinaryHeap::from(vec![1, 3]);
769     ///
770     /// assert_eq!(heap.len(), 2);
771     /// ```
772     #[stable(feature = "rust1", since = "1.0.0")]
773     pub fn len(&self) -> usize {
774         self.data.len()
775     }
776
777     /// Checks if the binary heap is empty.
778     ///
779     /// # Examples
780     ///
781     /// Basic usage:
782     ///
783     /// ```
784     /// use std::collections::BinaryHeap;
785     /// let mut heap = BinaryHeap::new();
786     ///
787     /// assert!(heap.is_empty());
788     ///
789     /// heap.push(3);
790     /// heap.push(5);
791     /// heap.push(1);
792     ///
793     /// assert!(!heap.is_empty());
794     /// ```
795     #[stable(feature = "rust1", since = "1.0.0")]
796     pub fn is_empty(&self) -> bool {
797         self.len() == 0
798     }
799
800     /// Clears the binary heap, returning an iterator over the removed elements.
801     ///
802     /// The elements are removed in arbitrary order.
803     ///
804     /// # Examples
805     ///
806     /// Basic usage:
807     ///
808     /// ```
809     /// use std::collections::BinaryHeap;
810     /// let mut heap = BinaryHeap::from(vec![1, 3]);
811     ///
812     /// assert!(!heap.is_empty());
813     ///
814     /// for x in heap.drain() {
815     ///     println!("{}", x);
816     /// }
817     ///
818     /// assert!(heap.is_empty());
819     /// ```
820     #[inline]
821     #[stable(feature = "drain", since = "1.6.0")]
822     pub fn drain(&mut self) -> Drain<T> {
823         Drain { iter: self.data.drain(..) }
824     }
825
826     /// Drops all items from the binary heap.
827     ///
828     /// # Examples
829     ///
830     /// Basic usage:
831     ///
832     /// ```
833     /// use std::collections::BinaryHeap;
834     /// let mut heap = BinaryHeap::from(vec![1, 3]);
835     ///
836     /// assert!(!heap.is_empty());
837     ///
838     /// heap.clear();
839     ///
840     /// assert!(heap.is_empty());
841     /// ```
842     #[stable(feature = "rust1", since = "1.0.0")]
843     pub fn clear(&mut self) {
844         self.drain();
845     }
846
847     fn rebuild(&mut self) {
848         let mut n = self.len() / 2;
849         while n > 0 {
850             n -= 1;
851             self.sift_down(n);
852         }
853     }
854
855     /// Moves all the elements of `other` into `self`, leaving `other` empty.
856     ///
857     /// # Examples
858     ///
859     /// Basic usage:
860     ///
861     /// ```
862     /// use std::collections::BinaryHeap;
863     ///
864     /// let v = vec![-10, 1, 2, 3, 3];
865     /// let mut a = BinaryHeap::from(v);
866     ///
867     /// let v = vec![-20, 5, 43];
868     /// let mut b = BinaryHeap::from(v);
869     ///
870     /// a.append(&mut b);
871     ///
872     /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
873     /// assert!(b.is_empty());
874     /// ```
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() {
878             swap(self, other);
879         }
880
881         if other.is_empty() {
882             return;
883         }
884
885         #[inline(always)]
886         fn log2_fast(x: usize) -> usize {
887             8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
888         }
889
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.
895         #[inline]
896         fn better_to_rebuild(len1: usize, len2: usize) -> bool {
897             2 * (len1 + len2) < len2 * log2_fast(len1)
898         }
899
900         if better_to_rebuild(self.len(), other.len()) {
901             self.data.append(&mut other.data);
902             self.rebuild();
903         } else {
904             self.extend(other.drain());
905         }
906     }
907 }
908
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> {
914     data: &'a mut [T],
915     /// `elt` is always `Some` from new until drop.
916     elt: Option<T>,
917     pos: usize,
918 }
919
920 impl<'a, T> Hole<'a, T> {
921     /// Create a new Hole at index `pos`.
922     ///
923     /// Unsafe because pos must be within the data slice.
924     #[inline]
925     unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
926         debug_assert!(pos < data.len());
927         let elt = ptr::read(&data[pos]);
928         Hole {
929             data: data,
930             elt: Some(elt),
931             pos: pos,
932         }
933     }
934
935     #[inline]
936     fn pos(&self) -> usize {
937         self.pos
938     }
939
940     /// Returns a reference to the element removed.
941     #[inline]
942     fn element(&self) -> &T {
943         self.elt.as_ref().unwrap()
944     }
945
946     /// Returns a reference to the element at `index`.
947     ///
948     /// Unsafe because index must be within the data slice and not equal to pos.
949     #[inline]
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)
954     }
955
956     /// Move hole to new location
957     ///
958     /// Unsafe because index must be within the data slice and not equal to pos.
959     #[inline]
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);
966         self.pos = index;
967     }
968 }
969
970 impl<'a, T> Drop for Hole<'a, T> {
971     #[inline]
972     fn drop(&mut self) {
973         // fill the hole again
974         unsafe {
975             let pos = self.pos;
976             ptr::write(self.data.get_unchecked_mut(pos), self.elt.take().unwrap());
977         }
978     }
979 }
980
981 /// An iterator over the elements of a `BinaryHeap`.
982 ///
983 /// This `struct` is created by the [`iter`] method on [`BinaryHeap`]. See its
984 /// documentation for more.
985 ///
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>,
991 }
992
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())
998          .finish()
999     }
1000 }
1001
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() }
1007     }
1008 }
1009
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 impl<'a, T> Iterator for Iter<'a, T> {
1012     type Item = &'a T;
1013
1014     #[inline]
1015     fn next(&mut self) -> Option<&'a T> {
1016         self.iter.next()
1017     }
1018
1019     #[inline]
1020     fn size_hint(&self) -> (usize, Option<usize>) {
1021         self.iter.size_hint()
1022     }
1023 }
1024
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1027     #[inline]
1028     fn next_back(&mut self) -> Option<&'a T> {
1029         self.iter.next_back()
1030     }
1031 }
1032
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()
1037     }
1038 }
1039
1040 #[unstable(feature = "fused", issue = "35602")]
1041 impl<'a, T> FusedIterator for Iter<'a, T> {}
1042
1043 /// An owning iterator over the elements of a `BinaryHeap`.
1044 ///
1045 /// This `struct` is created by the [`into_iter`] method on [`BinaryHeap`]
1046 /// (provided by the `IntoIterator` trait). See its documentation for more.
1047 ///
1048 /// [`into_iter`]: struct.BinaryHeap.html#method.into_iter
1049 /// [`BinaryHeap`]: struct.BinaryHeap.html
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 #[derive(Clone)]
1052 pub struct IntoIter<T> {
1053     iter: vec::IntoIter<T>,
1054 }
1055
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())
1061          .finish()
1062     }
1063 }
1064
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 impl<T> Iterator for IntoIter<T> {
1067     type Item = T;
1068
1069     #[inline]
1070     fn next(&mut self) -> Option<T> {
1071         self.iter.next()
1072     }
1073
1074     #[inline]
1075     fn size_hint(&self) -> (usize, Option<usize>) {
1076         self.iter.size_hint()
1077     }
1078 }
1079
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl<T> DoubleEndedIterator for IntoIter<T> {
1082     #[inline]
1083     fn next_back(&mut self) -> Option<T> {
1084         self.iter.next_back()
1085     }
1086 }
1087
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()
1092     }
1093 }
1094
1095 #[unstable(feature = "fused", issue = "35602")]
1096 impl<T> FusedIterator for IntoIter<T> {}
1097
1098 /// A draining iterator over the elements of a `BinaryHeap`.
1099 ///
1100 /// This `struct` is created by the [`drain`] method on [`BinaryHeap`]. See its
1101 /// documentation for more.
1102 ///
1103 /// [`drain`]: struct.BinaryHeap.html#method.drain
1104 /// [`BinaryHeap`]: struct.BinaryHeap.html
1105 #[stable(feature = "drain", since = "1.6.0")]
1106 #[derive(Debug)]
1107 pub struct Drain<'a, T: 'a> {
1108     iter: vec::Drain<'a, T>,
1109 }
1110
1111 #[stable(feature = "drain", since = "1.6.0")]
1112 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1113     type Item = T;
1114
1115     #[inline]
1116     fn next(&mut self) -> Option<T> {
1117         self.iter.next()
1118     }
1119
1120     #[inline]
1121     fn size_hint(&self) -> (usize, Option<usize>) {
1122         self.iter.size_hint()
1123     }
1124 }
1125
1126 #[stable(feature = "drain", since = "1.6.0")]
1127 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1128     #[inline]
1129     fn next_back(&mut self) -> Option<T> {
1130         self.iter.next_back()
1131     }
1132 }
1133
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()
1138     }
1139 }
1140
1141 #[unstable(feature = "fused", issue = "35602")]
1142 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
1143
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 };
1148         heap.rebuild();
1149         heap
1150     }
1151 }
1152
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> {
1156         heap.data
1157     }
1158 }
1159
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<_>>())
1164     }
1165 }
1166
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 impl<T: Ord> IntoIterator for BinaryHeap<T> {
1169     type Item = T;
1170     type IntoIter = IntoIter<T>;
1171
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.
1175     ///
1176     /// # Examples
1177     ///
1178     /// Basic usage:
1179     ///
1180     /// ```
1181     /// use std::collections::BinaryHeap;
1182     /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1183     ///
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);
1188     /// }
1189     /// ```
1190     fn into_iter(self) -> IntoIter<T> {
1191         IntoIter { iter: self.data.into_iter() }
1192     }
1193 }
1194
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 impl<'a, T> IntoIterator for &'a BinaryHeap<T>
1197     where T: Ord
1198 {
1199     type Item = &'a T;
1200     type IntoIter = Iter<'a, T>;
1201
1202     fn into_iter(self) -> Iter<'a, T> {
1203         self.iter()
1204     }
1205 }
1206
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1209     #[inline]
1210     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1211         <Self as SpecExtend<I>>::spec_extend(self, iter);
1212     }
1213 }
1214
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());
1218     }
1219 }
1220
1221 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1222     fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1223         self.append(other);
1224     }
1225 }
1226
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();
1231
1232         self.reserve(lower);
1233
1234         for elem in iterator {
1235             self.push(elem);
1236         }
1237     }
1238 }
1239
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());
1244     }
1245 }
1246
1247 #[unstable(feature = "collection_placement",
1248            reason = "placement protocol is subject to change",
1249            issue = "30172")]
1250 pub struct BinaryHeapPlace<'a, T: 'a>
1251 where T: Clone + Ord {
1252     heap: *mut BinaryHeap<T>,
1253     place: vec::PlaceBack<'a, T>,
1254 }
1255
1256 #[unstable(feature = "collection_placement",
1257            reason = "placement protocol is subject to change",
1258            issue = "30172")]
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")
1262          .field(&self.place)
1263          .finish()
1264     }
1265 }
1266
1267 #[unstable(feature = "collection_placement",
1268            reason = "placement protocol is subject to change",
1269            issue = "30172")]
1270 impl<'a, T: 'a> Placer<T> for &'a mut BinaryHeap<T>
1271 where T: Clone + Ord {
1272     type Place = BinaryHeapPlace<'a, T>;
1273
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());
1277         BinaryHeapPlace {
1278             heap: ptr,
1279             place: place,
1280         }
1281     }
1282 }
1283
1284 #[unstable(feature = "collection_placement",
1285            reason = "placement protocol is subject to change",
1286            issue = "30172")]
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()
1291     }
1292 }
1293
1294 #[unstable(feature = "collection_placement",
1295            reason = "placement protocol is subject to change",
1296            issue = "30172")]
1297 impl<'a, T> InPlace<T> for BinaryHeapPlace<'a, T>
1298 where T: Clone + Ord {
1299     type Owner = &'a T;
1300
1301     unsafe fn finalize(self) -> &'a T {
1302         self.place.finalize();
1303
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)
1308     }
1309 }