]> git.lizzy.rs Git - rust.git/blob - src/libcollections/binary_heap.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[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. Checking the largest
14 //! element is `O(1)`. Converting a vector to a binary heap can be done in-place, and has `O(n)`
15 //! complexity. A binary heap can also be converted to a sorted vector in-place, allowing it to
16 //! be used for an `O(n log n)` in-place heapsort.
17 //!
18 //! # Examples
19 //!
20 //! This is a larger example that implements [Dijkstra's algorithm][dijkstra]
21 //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
22 //! It shows how to use `BinaryHeap` with custom types.
23 //!
24 //! [dijkstra]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
25 //! [sssp]: http://en.wikipedia.org/wiki/Shortest_path_problem
26 //! [dir_graph]: http://en.wikipedia.org/wiki/Directed_graph
27 //!
28 //! ```
29 //! use std::cmp::Ordering;
30 //! use std::collections::BinaryHeap;
31 //! use std::usize;
32 //!
33 //! #[derive(Copy, Eq, PartialEq)]
34 //! struct State {
35 //!     cost: usize,
36 //!     position: usize,
37 //! }
38 //!
39 //! // The priority queue depends on `Ord`.
40 //! // Explicitly implement the trait so the queue becomes a min-heap
41 //! // instead of a max-heap.
42 //! impl Ord for State {
43 //!     fn cmp(&self, other: &State) -> Ordering {
44 //!         // Notice that the we flip the ordering here
45 //!         other.cost.cmp(&self.cost)
46 //!     }
47 //! }
48 //!
49 //! // `PartialOrd` needs to be implemented as well.
50 //! impl PartialOrd for State {
51 //!     fn partial_cmp(&self, other: &State) -> Option<Ordering> {
52 //!         Some(self.cmp(other))
53 //!     }
54 //! }
55 //!
56 //! // Each node is represented as an `usize`, for a shorter implementation.
57 //! struct Edge {
58 //!     node: usize,
59 //!     cost: usize,
60 //! }
61 //!
62 //! // Dijkstra's shortest path algorithm.
63 //!
64 //! // Start at `start` and use `dist` to track the current shortest distance
65 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
66 //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
67 //! // for a simpler implementation.
68 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> usize {
69 //!     // dist[node] = current shortest distance from `start` to `node`
70 //!     let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
71 //!
72 //!     let mut heap = BinaryHeap::new();
73 //!
74 //!     // We're at `start`, with a zero cost
75 //!     dist[start] = 0;
76 //!     heap.push(State { cost: 0, position: start });
77 //!
78 //!     // Examine the frontier with lower cost nodes first (min-heap)
79 //!     while let Some(State { cost, position }) = heap.pop() {
80 //!         // Alternatively we could have continued to find all shortest paths
81 //!         if position == goal { return cost; }
82 //!
83 //!         // Important as we may have already found a better way
84 //!         if cost > dist[position] { continue; }
85 //!
86 //!         // For each node we can reach, see if we can find a way with
87 //!         // a lower cost going through this node
88 //!         for edge in adj_list[position].iter() {
89 //!             let next = State { cost: cost + edge.cost, position: edge.node };
90 //!
91 //!             // If so, add it to the frontier and continue
92 //!             if next.cost < dist[next.position] {
93 //!                 heap.push(next);
94 //!                 // Relaxation, we have now found a better way
95 //!                 dist[next.position] = next.cost;
96 //!             }
97 //!         }
98 //!     }
99 //!
100 //!     // Goal not reachable
101 //!     usize::MAX
102 //! }
103 //!
104 //! fn main() {
105 //!     // This is the directed graph we're going to use.
106 //!     // The node numbers correspond to the different states,
107 //!     // and the edge weights symbolize the cost of moving
108 //!     // from one node to another.
109 //!     // Note that the edges are one-way.
110 //!     //
111 //!     //                  7
112 //!     //          +-----------------+
113 //!     //          |                 |
114 //!     //          v   1        2    |
115 //!     //          0 -----> 1 -----> 3 ---> 4
116 //!     //          |        ^        ^      ^
117 //!     //          |        | 1      |      |
118 //!     //          |        |        | 3    | 1
119 //!     //          +------> 2 -------+      |
120 //!     //           10      |               |
121 //!     //                   +---------------+
122 //!     //
123 //!     // The graph is represented as an adjacency list where each index,
124 //!     // corresponding to a node value, has a list of outgoing edges.
125 //!     // Chosen for its efficiency.
126 //!     let graph = vec![
127 //!         // Node 0
128 //!         vec![Edge { node: 2, cost: 10 },
129 //!              Edge { node: 1, cost: 1 }],
130 //!         // Node 1
131 //!         vec![Edge { node: 3, cost: 2 }],
132 //!         // Node 2
133 //!         vec![Edge { node: 1, cost: 1 },
134 //!              Edge { node: 3, cost: 3 },
135 //!              Edge { node: 4, cost: 1 }],
136 //!         // Node 3
137 //!         vec![Edge { node: 0, cost: 7 },
138 //!              Edge { node: 4, cost: 2 }],
139 //!         // Node 4
140 //!         vec![]];
141 //!
142 //!     assert_eq!(shortest_path(&graph, 0, 1), 1);
143 //!     assert_eq!(shortest_path(&graph, 0, 3), 3);
144 //!     assert_eq!(shortest_path(&graph, 3, 0), 7);
145 //!     assert_eq!(shortest_path(&graph, 0, 4), 5);
146 //!     assert_eq!(shortest_path(&graph, 4, 0), usize::MAX);
147 //! }
148 //! ```
149
150 #![allow(missing_docs)]
151 #![stable(feature = "rust1", since = "1.0.0")]
152
153 use core::prelude::*;
154
155 use core::default::Default;
156 use core::iter::{FromIterator, IntoIterator};
157 use core::mem::{zeroed, replace, swap};
158 use core::ptr;
159
160 use slice;
161 use vec::{self, Vec};
162
163 /// A priority queue implemented with a binary heap.
164 ///
165 /// This will be a max-heap.
166 #[derive(Clone)]
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub struct BinaryHeap<T> {
169     data: Vec<T>,
170 }
171
172 #[stable(feature = "rust1", since = "1.0.0")]
173 impl<T: Ord> Default for BinaryHeap<T> {
174     #[inline]
175     fn default() -> BinaryHeap<T> { BinaryHeap::new() }
176 }
177
178 impl<T: Ord> BinaryHeap<T> {
179     /// Creates an empty `BinaryHeap` as a max-heap.
180     ///
181     /// # Examples
182     ///
183     /// ```
184     /// use std::collections::BinaryHeap;
185     /// let mut heap = BinaryHeap::new();
186     /// heap.push(4);
187     /// ```
188     #[stable(feature = "rust1", since = "1.0.0")]
189     pub fn new() -> BinaryHeap<T> { BinaryHeap { data: vec![] } }
190
191     /// Creates an empty `BinaryHeap` with a specific capacity.
192     /// This preallocates enough memory for `capacity` elements,
193     /// so that the `BinaryHeap` does not have to be reallocated
194     /// until it contains at least that many values.
195     ///
196     /// # Examples
197     ///
198     /// ```
199     /// use std::collections::BinaryHeap;
200     /// let mut heap = BinaryHeap::with_capacity(10);
201     /// heap.push(4);
202     /// ```
203     #[stable(feature = "rust1", since = "1.0.0")]
204     pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
205         BinaryHeap { data: Vec::with_capacity(capacity) }
206     }
207
208     /// Creates a `BinaryHeap` from a vector. This is sometimes called
209     /// `heapifying` the vector.
210     ///
211     /// # Examples
212     ///
213     /// ```
214     /// use std::collections::BinaryHeap;
215     /// let heap = BinaryHeap::from_vec(vec![9, 1, 2, 7, 3, 2]);
216     /// ```
217     pub fn from_vec(vec: Vec<T>) -> BinaryHeap<T> {
218         let mut heap = BinaryHeap { data: vec };
219         let mut n = heap.len() / 2;
220         while n > 0 {
221             n -= 1;
222             heap.sift_down(n);
223         }
224         heap
225     }
226
227     /// Returns an iterator visiting all values in the underlying vector, in
228     /// arbitrary order.
229     ///
230     /// # Examples
231     ///
232     /// ```
233     /// use std::collections::BinaryHeap;
234     /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
235     ///
236     /// // Print 1, 2, 3, 4 in arbitrary order
237     /// for x in heap.iter() {
238     ///     println!("{}", x);
239     /// }
240     /// ```
241     #[stable(feature = "rust1", since = "1.0.0")]
242     pub fn iter(&self) -> Iter<T> {
243         Iter { iter: self.data.iter() }
244     }
245
246     /// Creates a consuming iterator, that is, one that moves each value out of
247     /// the binary heap in arbitrary order. The binary heap cannot be used
248     /// after calling this.
249     ///
250     /// # Examples
251     ///
252     /// ```
253     /// use std::collections::BinaryHeap;
254     /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
255     ///
256     /// // Print 1, 2, 3, 4 in arbitrary order
257     /// for x in heap.into_iter() {
258     ///     // x has type i32, not &i32
259     ///     println!("{}", x);
260     /// }
261     /// ```
262     #[stable(feature = "rust1", since = "1.0.0")]
263     pub fn into_iter(self) -> IntoIter<T> {
264         IntoIter { iter: self.data.into_iter() }
265     }
266
267     /// Returns the greatest item in the binary heap, or `None` if it is empty.
268     ///
269     /// # Examples
270     ///
271     /// ```
272     /// use std::collections::BinaryHeap;
273     /// let mut heap = BinaryHeap::new();
274     /// assert_eq!(heap.peek(), None);
275     ///
276     /// heap.push(1);
277     /// heap.push(5);
278     /// heap.push(2);
279     /// assert_eq!(heap.peek(), Some(&5));
280     ///
281     /// ```
282     #[stable(feature = "rust1", since = "1.0.0")]
283     pub fn peek(&self) -> Option<&T> {
284         self.data.get(0)
285     }
286
287     /// Returns the number of elements the binary heap can hold without reallocating.
288     ///
289     /// # Examples
290     ///
291     /// ```
292     /// use std::collections::BinaryHeap;
293     /// let mut heap = BinaryHeap::with_capacity(100);
294     /// assert!(heap.capacity() >= 100);
295     /// heap.push(4);
296     /// ```
297     #[stable(feature = "rust1", since = "1.0.0")]
298     pub fn capacity(&self) -> usize { self.data.capacity() }
299
300     /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
301     /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
302     ///
303     /// Note that the allocator may give the collection more space than it requests. Therefore
304     /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
305     /// insertions are expected.
306     ///
307     /// # Panics
308     ///
309     /// Panics if the new capacity overflows `usize`.
310     ///
311     /// # Examples
312     ///
313     /// ```
314     /// use std::collections::BinaryHeap;
315     /// let mut heap = BinaryHeap::new();
316     /// heap.reserve_exact(100);
317     /// assert!(heap.capacity() >= 100);
318     /// heap.push(4);
319     /// ```
320     #[stable(feature = "rust1", since = "1.0.0")]
321     pub fn reserve_exact(&mut self, additional: usize) {
322         self.data.reserve_exact(additional);
323     }
324
325     /// Reserves capacity for at least `additional` more elements to be inserted in the
326     /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
327     ///
328     /// # Panics
329     ///
330     /// Panics if the new capacity overflows `usize`.
331     ///
332     /// # Examples
333     ///
334     /// ```
335     /// use std::collections::BinaryHeap;
336     /// let mut heap = BinaryHeap::new();
337     /// heap.reserve(100);
338     /// assert!(heap.capacity() >= 100);
339     /// heap.push(4);
340     /// ```
341     #[stable(feature = "rust1", since = "1.0.0")]
342     pub fn reserve(&mut self, additional: usize) {
343         self.data.reserve(additional);
344     }
345
346     /// Discards as much additional capacity as possible.
347     #[stable(feature = "rust1", since = "1.0.0")]
348     pub fn shrink_to_fit(&mut self) {
349         self.data.shrink_to_fit();
350     }
351
352     /// Removes the greatest item from the binary heap and returns it, or `None` if it
353     /// is empty.
354     ///
355     /// # Examples
356     ///
357     /// ```
358     /// use std::collections::BinaryHeap;
359     /// let mut heap = BinaryHeap::from_vec(vec![1, 3]);
360     ///
361     /// assert_eq!(heap.pop(), Some(3));
362     /// assert_eq!(heap.pop(), Some(1));
363     /// assert_eq!(heap.pop(), None);
364     /// ```
365     #[stable(feature = "rust1", since = "1.0.0")]
366     pub fn pop(&mut self) -> Option<T> {
367         self.data.pop().map(|mut item| {
368             if !self.is_empty() {
369                 swap(&mut item, &mut self.data[0]);
370                 self.sift_down(0);
371             }
372             item
373         })
374     }
375
376     /// Pushes an item onto the binary heap.
377     ///
378     /// # Examples
379     ///
380     /// ```
381     /// use std::collections::BinaryHeap;
382     /// let mut heap = BinaryHeap::new();
383     /// heap.push(3);
384     /// heap.push(5);
385     /// heap.push(1);
386     ///
387     /// assert_eq!(heap.len(), 3);
388     /// assert_eq!(heap.peek(), Some(&5));
389     /// ```
390     #[stable(feature = "rust1", since = "1.0.0")]
391     pub fn push(&mut self, item: T) {
392         let old_len = self.len();
393         self.data.push(item);
394         self.sift_up(0, old_len);
395     }
396
397     /// Pushes an item onto the binary heap, then pops the greatest item off the queue in
398     /// an optimized fashion.
399     ///
400     /// # Examples
401     ///
402     /// ```
403     /// use std::collections::BinaryHeap;
404     /// let mut heap = BinaryHeap::new();
405     /// heap.push(1);
406     /// heap.push(5);
407     ///
408     /// assert_eq!(heap.push_pop(3), 5);
409     /// assert_eq!(heap.push_pop(9), 9);
410     /// assert_eq!(heap.len(), 2);
411     /// assert_eq!(heap.peek(), Some(&3));
412     /// ```
413     pub fn push_pop(&mut self, mut item: T) -> T {
414         match self.data.get_mut(0) {
415             None => return item,
416             Some(top) => if *top > item {
417                 swap(&mut item, top);
418             } else {
419                 return item;
420             },
421         }
422
423         self.sift_down(0);
424         item
425     }
426
427     /// Pops the greatest item off the binary heap, then pushes an item onto the queue in
428     /// an optimized fashion. The push is done regardless of whether the binary heap
429     /// was empty.
430     ///
431     /// # Examples
432     ///
433     /// ```
434     /// use std::collections::BinaryHeap;
435     /// let mut heap = BinaryHeap::new();
436     ///
437     /// assert_eq!(heap.replace(1), None);
438     /// assert_eq!(heap.replace(3), Some(1));
439     /// assert_eq!(heap.len(), 1);
440     /// assert_eq!(heap.peek(), Some(&3));
441     /// ```
442     pub fn replace(&mut self, mut item: T) -> Option<T> {
443         if !self.is_empty() {
444             swap(&mut item, &mut self.data[0]);
445             self.sift_down(0);
446             Some(item)
447         } else {
448             self.push(item);
449             None
450         }
451     }
452
453     /// Consumes the `BinaryHeap` and returns the underlying vector
454     /// in arbitrary order.
455     ///
456     /// # Examples
457     ///
458     /// ```
459     /// use std::collections::BinaryHeap;
460     /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4, 5, 6, 7]);
461     /// let vec = heap.into_vec();
462     ///
463     /// // Will print in some order
464     /// for x in vec.iter() {
465     ///     println!("{}", x);
466     /// }
467     /// ```
468     pub fn into_vec(self) -> Vec<T> { self.data }
469
470     /// Consumes the `BinaryHeap` and returns a vector in sorted
471     /// (ascending) order.
472     ///
473     /// # Examples
474     ///
475     /// ```
476     /// use std::collections::BinaryHeap;
477     ///
478     /// let mut heap = BinaryHeap::from_vec(vec![1, 2, 4, 5, 7]);
479     /// heap.push(6);
480     /// heap.push(3);
481     ///
482     /// let vec = heap.into_sorted_vec();
483     /// assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7]);
484     /// ```
485     pub fn into_sorted_vec(mut self) -> Vec<T> {
486         let mut end = self.len();
487         while end > 1 {
488             end -= 1;
489             self.data.swap(0, end);
490             self.sift_down_range(0, end);
491         }
492         self.into_vec()
493     }
494
495     // The implementations of sift_up and sift_down use unsafe blocks in
496     // order to move an element out of the vector (leaving behind a
497     // zeroed element), shift along the others and move it back into the
498     // vector over the junk element. This reduces the constant factor
499     // compared to using swaps, which involves twice as many moves.
500     fn sift_up(&mut self, start: usize, mut pos: usize) {
501         unsafe {
502             let new = replace(&mut self.data[pos], zeroed());
503
504             while pos > start {
505                 let parent = (pos - 1) >> 1;
506
507                 if new <= self.data[parent] { break; }
508
509                 let x = replace(&mut self.data[parent], zeroed());
510                 ptr::write(&mut self.data[pos], x);
511                 pos = parent;
512             }
513             ptr::write(&mut self.data[pos], new);
514         }
515     }
516
517     fn sift_down_range(&mut self, mut pos: usize, end: usize) {
518         unsafe {
519             let start = pos;
520             let new = replace(&mut self.data[pos], zeroed());
521
522             let mut child = 2 * pos + 1;
523             while child < end {
524                 let right = child + 1;
525                 if right < end && !(self.data[child] > self.data[right]) {
526                     child = right;
527                 }
528                 let x = replace(&mut self.data[child], zeroed());
529                 ptr::write(&mut self.data[pos], x);
530                 pos = child;
531                 child = 2 * pos + 1;
532             }
533
534             ptr::write(&mut self.data[pos], new);
535             self.sift_up(start, pos);
536         }
537     }
538
539     fn sift_down(&mut self, pos: usize) {
540         let len = self.len();
541         self.sift_down_range(pos, len);
542     }
543
544     /// Returns the length of the binary heap.
545     #[stable(feature = "rust1", since = "1.0.0")]
546     pub fn len(&self) -> usize { self.data.len() }
547
548     /// Checks if the binary heap is empty.
549     #[stable(feature = "rust1", since = "1.0.0")]
550     pub fn is_empty(&self) -> bool { self.len() == 0 }
551
552     /// Clears the binary heap, returning an iterator over the removed elements.
553     #[inline]
554     #[unstable(feature = "collections",
555                reason = "matches collection reform specification, waiting for dust to settle")]
556     pub fn drain(&mut self) -> Drain<T> {
557         Drain { iter: self.data.drain() }
558     }
559
560     /// Drops all items from the binary heap.
561     #[stable(feature = "rust1", since = "1.0.0")]
562     pub fn clear(&mut self) { self.drain(); }
563 }
564
565 /// `BinaryHeap` iterator.
566 #[stable(feature = "rust1", since = "1.0.0")]
567 pub struct Iter <'a, T: 'a> {
568     iter: slice::Iter<'a, T>,
569 }
570
571 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl<'a, T> Clone for Iter<'a, T> {
574     fn clone(&self) -> Iter<'a, T> {
575         Iter { iter: self.iter.clone() }
576     }
577 }
578
579 #[stable(feature = "rust1", since = "1.0.0")]
580 impl<'a, T> Iterator for Iter<'a, T> {
581     type Item = &'a T;
582
583     #[inline]
584     fn next(&mut self) -> Option<&'a T> { self.iter.next() }
585
586     #[inline]
587     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
588 }
589
590 #[stable(feature = "rust1", since = "1.0.0")]
591 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
592     #[inline]
593     fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
594 }
595
596 #[stable(feature = "rust1", since = "1.0.0")]
597 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
598
599 /// An iterator that moves out of a `BinaryHeap`.
600 #[stable(feature = "rust1", since = "1.0.0")]
601 pub struct IntoIter<T> {
602     iter: vec::IntoIter<T>,
603 }
604
605 #[stable(feature = "rust1", since = "1.0.0")]
606 impl<T> Iterator for IntoIter<T> {
607     type Item = T;
608
609     #[inline]
610     fn next(&mut self) -> Option<T> { self.iter.next() }
611
612     #[inline]
613     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
614 }
615
616 #[stable(feature = "rust1", since = "1.0.0")]
617 impl<T> DoubleEndedIterator for IntoIter<T> {
618     #[inline]
619     fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
620 }
621
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl<T> ExactSizeIterator for IntoIter<T> {}
624
625 /// An iterator that drains a `BinaryHeap`.
626 #[unstable(feature = "collections", reason = "recent addition")]
627 pub struct Drain<'a, T: 'a> {
628     iter: vec::Drain<'a, T>,
629 }
630
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl<'a, T: 'a> Iterator for Drain<'a, T> {
633     type Item = T;
634
635     #[inline]
636     fn next(&mut self) -> Option<T> { self.iter.next() }
637
638     #[inline]
639     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
640 }
641
642 #[stable(feature = "rust1", since = "1.0.0")]
643 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
644     #[inline]
645     fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
646 }
647
648 #[stable(feature = "rust1", since = "1.0.0")]
649 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
650
651 #[stable(feature = "rust1", since = "1.0.0")]
652 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
653     fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> BinaryHeap<T> {
654         BinaryHeap::from_vec(iter.into_iter().collect())
655     }
656 }
657
658 #[stable(feature = "rust1", since = "1.0.0")]
659 impl<T: Ord> IntoIterator for BinaryHeap<T> {
660     type Item = T;
661     type IntoIter = IntoIter<T>;
662
663     fn into_iter(self) -> IntoIter<T> {
664         self.into_iter()
665     }
666 }
667
668 #[stable(feature = "rust1", since = "1.0.0")]
669 impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord {
670     type Item = &'a T;
671     type IntoIter = Iter<'a, T>;
672
673     fn into_iter(self) -> Iter<'a, T> {
674         self.iter()
675     }
676 }
677
678 #[stable(feature = "rust1", since = "1.0.0")]
679 impl<T: Ord> Extend<T> for BinaryHeap<T> {
680     fn extend<I: IntoIterator<Item=T>>(&mut self, iterable: I) {
681         let iter = iterable.into_iter();
682         let (lower, _) = iter.size_hint();
683
684         self.reserve(lower);
685
686         for elem in iter {
687             self.push(elem);
688         }
689     }
690 }
691
692 #[cfg(test)]
693 mod tests {
694     use prelude::*;
695
696     use super::BinaryHeap;
697
698     #[test]
699     fn test_iterator() {
700         let data = vec![5, 9, 3];
701         let iterout = [9, 5, 3];
702         let heap = BinaryHeap::from_vec(data);
703         let mut i = 0;
704         for el in &heap {
705             assert_eq!(*el, iterout[i]);
706             i += 1;
707         }
708     }
709
710     #[test]
711     fn test_iterator_reverse() {
712         let data = vec![5, 9, 3];
713         let iterout = vec![3, 5, 9];
714         let pq = BinaryHeap::from_vec(data);
715
716         let v: Vec<_> = pq.iter().rev().cloned().collect();
717         assert_eq!(v, iterout);
718     }
719
720     #[test]
721     fn test_move_iter() {
722         let data = vec![5, 9, 3];
723         let iterout = vec![9, 5, 3];
724         let pq = BinaryHeap::from_vec(data);
725
726         let v: Vec<_> = pq.into_iter().collect();
727         assert_eq!(v, iterout);
728     }
729
730     #[test]
731     fn test_move_iter_size_hint() {
732         let data = vec![5, 9];
733         let pq = BinaryHeap::from_vec(data);
734
735         let mut it = pq.into_iter();
736
737         assert_eq!(it.size_hint(), (2, Some(2)));
738         assert_eq!(it.next(), Some(9));
739
740         assert_eq!(it.size_hint(), (1, Some(1)));
741         assert_eq!(it.next(), Some(5));
742
743         assert_eq!(it.size_hint(), (0, Some(0)));
744         assert_eq!(it.next(), None);
745     }
746
747     #[test]
748     fn test_move_iter_reverse() {
749         let data = vec![5, 9, 3];
750         let iterout = vec![3, 5, 9];
751         let pq = BinaryHeap::from_vec(data);
752
753         let v: Vec<_> = pq.into_iter().rev().collect();
754         assert_eq!(v, iterout);
755     }
756
757     #[test]
758     fn test_peek_and_pop() {
759         let data = vec![2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1];
760         let mut sorted = data.clone();
761         sorted.sort();
762         let mut heap = BinaryHeap::from_vec(data);
763         while !heap.is_empty() {
764             assert_eq!(heap.peek().unwrap(), sorted.last().unwrap());
765             assert_eq!(heap.pop().unwrap(), sorted.pop().unwrap());
766         }
767     }
768
769     #[test]
770     fn test_push() {
771         let mut heap = BinaryHeap::from_vec(vec![2, 4, 9]);
772         assert_eq!(heap.len(), 3);
773         assert!(*heap.peek().unwrap() == 9);
774         heap.push(11);
775         assert_eq!(heap.len(), 4);
776         assert!(*heap.peek().unwrap() == 11);
777         heap.push(5);
778         assert_eq!(heap.len(), 5);
779         assert!(*heap.peek().unwrap() == 11);
780         heap.push(27);
781         assert_eq!(heap.len(), 6);
782         assert!(*heap.peek().unwrap() == 27);
783         heap.push(3);
784         assert_eq!(heap.len(), 7);
785         assert!(*heap.peek().unwrap() == 27);
786         heap.push(103);
787         assert_eq!(heap.len(), 8);
788         assert!(*heap.peek().unwrap() == 103);
789     }
790
791     #[test]
792     fn test_push_unique() {
793         let mut heap = BinaryHeap::from_vec(vec![box 2, box 4, box 9]);
794         assert_eq!(heap.len(), 3);
795         assert!(*heap.peek().unwrap() == box 9);
796         heap.push(box 11);
797         assert_eq!(heap.len(), 4);
798         assert!(*heap.peek().unwrap() == box 11);
799         heap.push(box 5);
800         assert_eq!(heap.len(), 5);
801         assert!(*heap.peek().unwrap() == box 11);
802         heap.push(box 27);
803         assert_eq!(heap.len(), 6);
804         assert!(*heap.peek().unwrap() == box 27);
805         heap.push(box 3);
806         assert_eq!(heap.len(), 7);
807         assert!(*heap.peek().unwrap() == box 27);
808         heap.push(box 103);
809         assert_eq!(heap.len(), 8);
810         assert!(*heap.peek().unwrap() == box 103);
811     }
812
813     #[test]
814     fn test_push_pop() {
815         let mut heap = BinaryHeap::from_vec(vec![5, 5, 2, 1, 3]);
816         assert_eq!(heap.len(), 5);
817         assert_eq!(heap.push_pop(6), 6);
818         assert_eq!(heap.len(), 5);
819         assert_eq!(heap.push_pop(0), 5);
820         assert_eq!(heap.len(), 5);
821         assert_eq!(heap.push_pop(4), 5);
822         assert_eq!(heap.len(), 5);
823         assert_eq!(heap.push_pop(1), 4);
824         assert_eq!(heap.len(), 5);
825     }
826
827     #[test]
828     fn test_replace() {
829         let mut heap = BinaryHeap::from_vec(vec![5, 5, 2, 1, 3]);
830         assert_eq!(heap.len(), 5);
831         assert_eq!(heap.replace(6).unwrap(), 5);
832         assert_eq!(heap.len(), 5);
833         assert_eq!(heap.replace(0).unwrap(), 6);
834         assert_eq!(heap.len(), 5);
835         assert_eq!(heap.replace(4).unwrap(), 5);
836         assert_eq!(heap.len(), 5);
837         assert_eq!(heap.replace(1).unwrap(), 4);
838         assert_eq!(heap.len(), 5);
839     }
840
841     fn check_to_vec(mut data: Vec<i32>) {
842         let heap = BinaryHeap::from_vec(data.clone());
843         let mut v = heap.clone().into_vec();
844         v.sort();
845         data.sort();
846
847         assert_eq!(v, data);
848         assert_eq!(heap.into_sorted_vec(), data);
849     }
850
851     #[test]
852     fn test_to_vec() {
853         check_to_vec(vec![]);
854         check_to_vec(vec![5]);
855         check_to_vec(vec![3, 2]);
856         check_to_vec(vec![2, 3]);
857         check_to_vec(vec![5, 1, 2]);
858         check_to_vec(vec![1, 100, 2, 3]);
859         check_to_vec(vec![1, 3, 5, 7, 9, 2, 4, 6, 8, 0]);
860         check_to_vec(vec![2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1]);
861         check_to_vec(vec![9, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0]);
862         check_to_vec(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
863         check_to_vec(vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
864         check_to_vec(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2]);
865         check_to_vec(vec![5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1]);
866     }
867
868     #[test]
869     fn test_empty_pop() {
870         let mut heap = BinaryHeap::<i32>::new();
871         assert!(heap.pop().is_none());
872     }
873
874     #[test]
875     fn test_empty_peek() {
876         let empty = BinaryHeap::<i32>::new();
877         assert!(empty.peek().is_none());
878     }
879
880     #[test]
881     fn test_empty_replace() {
882         let mut heap = BinaryHeap::new();
883         assert!(heap.replace(5).is_none());
884     }
885
886     #[test]
887     fn test_from_iter() {
888         let xs = vec![9, 8, 7, 6, 5, 4, 3, 2, 1];
889
890         let mut q: BinaryHeap<_> = xs.iter().rev().cloned().collect();
891
892         for &x in &xs {
893             assert_eq!(q.pop().unwrap(), x);
894         }
895     }
896
897     #[test]
898     fn test_drain() {
899         let mut q: BinaryHeap<_> = [9, 8, 7, 6, 5, 4, 3, 2, 1].iter().cloned().collect();
900
901         assert_eq!(q.drain().take(5).count(), 5);
902
903         assert!(q.is_empty());
904     }
905 }