]> git.lizzy.rs Git - rust.git/blob - src/libcollections/binary_heap.rs
Merge pull request #20510 from tshepang/patch-6
[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::uint;
32 //!
33 //! #[derive(Copy, Eq, PartialEq)]
34 //! struct State {
35 //!     cost: uint,
36 //!     position: uint,
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 `uint`, for a shorter implementation.
57 //! struct Edge {
58 //!     node: uint,
59 //!     cost: uint,
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 `uint::MAX` as a sentinel value,
67 //! // for a simpler implementation.
68 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: uint, goal: uint) -> uint {
69 //!     // dist[node] = current shortest distance from `start` to `node`
70 //!     let mut dist: Vec<_> = range(0, adj_list.len()).map(|_| uint::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 //!     uint::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), uint::MAX);
147 //! }
148 //! ```
149
150 #![allow(missing_docs)]
151
152 use core::prelude::*;
153
154 use core::default::Default;
155 use core::iter::FromIterator;
156 use core::mem::{zeroed, replace, swap};
157 use core::ptr;
158
159 use slice;
160 use vec::{self, Vec};
161
162 /// A priority queue implemented with a binary heap.
163 ///
164 /// This will be a max-heap.
165 #[derive(Clone)]
166 #[stable]
167 pub struct BinaryHeap<T> {
168     data: Vec<T>,
169 }
170
171 #[stable]
172 impl<T: Ord> Default for BinaryHeap<T> {
173     #[inline]
174     fn default() -> BinaryHeap<T> { BinaryHeap::new() }
175 }
176
177 impl<T: Ord> BinaryHeap<T> {
178     /// Creates an empty `BinaryHeap` as a max-heap.
179     ///
180     /// # Examples
181     ///
182     /// ```
183     /// use std::collections::BinaryHeap;
184     /// let mut heap = BinaryHeap::new();
185     /// heap.push(4u);
186     /// ```
187     #[stable]
188     pub fn new() -> BinaryHeap<T> { BinaryHeap { data: vec![] } }
189
190     /// Creates an empty `BinaryHeap` with a specific capacity.
191     /// This preallocates enough memory for `capacity` elements,
192     /// so that the `BinaryHeap` does not have to be reallocated
193     /// until it contains at least that many values.
194     ///
195     /// # Examples
196     ///
197     /// ```
198     /// use std::collections::BinaryHeap;
199     /// let mut heap = BinaryHeap::with_capacity(10);
200     /// heap.push(4u);
201     /// ```
202     #[stable]
203     pub fn with_capacity(capacity: uint) -> BinaryHeap<T> {
204         BinaryHeap { data: Vec::with_capacity(capacity) }
205     }
206
207     /// Creates a `BinaryHeap` from a vector. This is sometimes called
208     /// `heapifying` the vector.
209     ///
210     /// # Examples
211     ///
212     /// ```
213     /// use std::collections::BinaryHeap;
214     /// let heap = BinaryHeap::from_vec(vec![9i, 1, 2, 7, 3, 2]);
215     /// ```
216     pub fn from_vec(vec: Vec<T>) -> BinaryHeap<T> {
217         let mut heap = BinaryHeap { data: vec };
218         let mut n = heap.len() / 2;
219         while n > 0 {
220             n -= 1;
221             heap.sift_down(n);
222         }
223         heap
224     }
225
226     /// Returns an iterator visiting all values in the underlying vector, in
227     /// arbitrary order.
228     ///
229     /// # Examples
230     ///
231     /// ```
232     /// use std::collections::BinaryHeap;
233     /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4]);
234     ///
235     /// // Print 1, 2, 3, 4 in arbitrary order
236     /// for x in heap.iter() {
237     ///     println!("{}", x);
238     /// }
239     /// ```
240     #[stable]
241     pub fn iter(&self) -> Iter<T> {
242         Iter { iter: self.data.iter() }
243     }
244
245     /// Creates a consuming iterator, that is, one that moves each value out of
246     /// the binary heap in arbitrary order. The binary heap cannot be used
247     /// after calling this.
248     ///
249     /// # Examples
250     ///
251     /// ```
252     /// use std::collections::BinaryHeap;
253     /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4]);
254     ///
255     /// // Print 1, 2, 3, 4 in arbitrary order
256     /// for x in heap.into_iter() {
257     ///     // x has type int, not &int
258     ///     println!("{}", x);
259     /// }
260     /// ```
261     #[stable]
262     pub fn into_iter(self) -> IntoIter<T> {
263         IntoIter { iter: self.data.into_iter() }
264     }
265
266     /// Returns the greatest item in the binary heap, or `None` if it is empty.
267     ///
268     /// # Examples
269     ///
270     /// ```
271     /// use std::collections::BinaryHeap;
272     /// let mut heap = BinaryHeap::new();
273     /// assert_eq!(heap.peek(), None);
274     ///
275     /// heap.push(1i);
276     /// heap.push(5);
277     /// heap.push(2);
278     /// assert_eq!(heap.peek(), Some(&5));
279     ///
280     /// ```
281     #[stable]
282     pub fn peek(&self) -> Option<&T> {
283         self.data.get(0)
284     }
285
286     /// Returns the number of elements the binary heap can hold without reallocating.
287     ///
288     /// # Examples
289     ///
290     /// ```
291     /// use std::collections::BinaryHeap;
292     /// let mut heap = BinaryHeap::with_capacity(100);
293     /// assert!(heap.capacity() >= 100);
294     /// heap.push(4u);
295     /// ```
296     #[stable]
297     pub fn capacity(&self) -> uint { self.data.capacity() }
298
299     /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
300     /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
301     ///
302     /// Note that the allocator may give the collection more space than it requests. Therefore
303     /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
304     /// insertions are expected.
305     ///
306     /// # Panics
307     ///
308     /// Panics if the new capacity overflows `uint`.
309     ///
310     /// # Examples
311     ///
312     /// ```
313     /// use std::collections::BinaryHeap;
314     /// let mut heap = BinaryHeap::new();
315     /// heap.reserve_exact(100);
316     /// assert!(heap.capacity() >= 100);
317     /// heap.push(4u);
318     /// ```
319     #[stable]
320     pub fn reserve_exact(&mut self, additional: uint) {
321         self.data.reserve_exact(additional);
322     }
323
324     /// Reserves capacity for at least `additional` more elements to be inserted in the
325     /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
326     ///
327     /// # Panics
328     ///
329     /// Panics if the new capacity overflows `uint`.
330     ///
331     /// # Examples
332     ///
333     /// ```
334     /// use std::collections::BinaryHeap;
335     /// let mut heap = BinaryHeap::new();
336     /// heap.reserve(100);
337     /// assert!(heap.capacity() >= 100);
338     /// heap.push(4u);
339     /// ```
340     #[stable]
341     pub fn reserve(&mut self, additional: uint) {
342         self.data.reserve(additional);
343     }
344
345     /// Discards as much additional capacity as possible.
346     #[stable]
347     pub fn shrink_to_fit(&mut self) {
348         self.data.shrink_to_fit();
349     }
350
351     /// Removes the greatest item from the binary heap and returns it, or `None` if it
352     /// is empty.
353     ///
354     /// # Examples
355     ///
356     /// ```
357     /// use std::collections::BinaryHeap;
358     /// let mut heap = BinaryHeap::from_vec(vec![1i, 3]);
359     ///
360     /// assert_eq!(heap.pop(), Some(3));
361     /// assert_eq!(heap.pop(), Some(1));
362     /// assert_eq!(heap.pop(), None);
363     /// ```
364     #[stable]
365     pub fn pop(&mut self) -> Option<T> {
366         self.data.pop().map(|mut item| {
367             if !self.is_empty() {
368                 swap(&mut item, &mut self.data[0]);
369                 self.sift_down(0);
370             }
371             item
372         })
373     }
374
375     /// Pushes an item onto the binary heap.
376     ///
377     /// # Examples
378     ///
379     /// ```
380     /// use std::collections::BinaryHeap;
381     /// let mut heap = BinaryHeap::new();
382     /// heap.push(3i);
383     /// heap.push(5);
384     /// heap.push(1);
385     ///
386     /// assert_eq!(heap.len(), 3);
387     /// assert_eq!(heap.peek(), Some(&5));
388     /// ```
389     #[stable]
390     pub fn push(&mut self, item: T) {
391         let old_len = self.len();
392         self.data.push(item);
393         self.sift_up(0, old_len);
394     }
395
396     /// Pushes an item onto the binary heap, then pops the greatest item off the queue in
397     /// an optimized fashion.
398     ///
399     /// # Examples
400     ///
401     /// ```
402     /// use std::collections::BinaryHeap;
403     /// let mut heap = BinaryHeap::new();
404     /// heap.push(1i);
405     /// heap.push(5);
406     ///
407     /// assert_eq!(heap.push_pop(3), 5);
408     /// assert_eq!(heap.push_pop(9), 9);
409     /// assert_eq!(heap.len(), 2);
410     /// assert_eq!(heap.peek(), Some(&3));
411     /// ```
412     pub fn push_pop(&mut self, mut item: T) -> T {
413         match self.data.get_mut(0) {
414             None => return item,
415             Some(top) => if *top > item {
416                 swap(&mut item, top);
417             } else {
418                 return item;
419             },
420         }
421
422         self.sift_down(0);
423         item
424     }
425
426     /// Pops the greatest item off the binary heap, then pushes an item onto the queue in
427     /// an optimized fashion. The push is done regardless of whether the binary heap
428     /// was empty.
429     ///
430     /// # Examples
431     ///
432     /// ```
433     /// use std::collections::BinaryHeap;
434     /// let mut heap = BinaryHeap::new();
435     ///
436     /// assert_eq!(heap.replace(1i), None);
437     /// assert_eq!(heap.replace(3), Some(1));
438     /// assert_eq!(heap.len(), 1);
439     /// assert_eq!(heap.peek(), Some(&3));
440     /// ```
441     pub fn replace(&mut self, mut item: T) -> Option<T> {
442         if !self.is_empty() {
443             swap(&mut item, &mut self.data[0]);
444             self.sift_down(0);
445             Some(item)
446         } else {
447             self.push(item);
448             None
449         }
450     }
451
452     /// Consumes the `BinaryHeap` and returns the underlying vector
453     /// in arbitrary order.
454     ///
455     /// # Examples
456     ///
457     /// ```
458     /// use std::collections::BinaryHeap;
459     /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4, 5, 6, 7]);
460     /// let vec = heap.into_vec();
461     ///
462     /// // Will print in some order
463     /// for x in vec.iter() {
464     ///     println!("{}", x);
465     /// }
466     /// ```
467     pub fn into_vec(self) -> Vec<T> { self.data }
468
469     /// Consumes the `BinaryHeap` and returns a vector in sorted
470     /// (ascending) order.
471     ///
472     /// # Examples
473     ///
474     /// ```
475     /// use std::collections::BinaryHeap;
476     ///
477     /// let mut heap = BinaryHeap::from_vec(vec![1i, 2, 4, 5, 7]);
478     /// heap.push(6);
479     /// heap.push(3);
480     ///
481     /// let vec = heap.into_sorted_vec();
482     /// assert_eq!(vec, vec![1i, 2, 3, 4, 5, 6, 7]);
483     /// ```
484     pub fn into_sorted_vec(mut self) -> Vec<T> {
485         let mut end = self.len();
486         while end > 1 {
487             end -= 1;
488             self.data.swap(0, end);
489             self.sift_down_range(0, end);
490         }
491         self.into_vec()
492     }
493
494     // The implementations of sift_up and sift_down use unsafe blocks in
495     // order to move an element out of the vector (leaving behind a
496     // zeroed element), shift along the others and move it back into the
497     // vector over the junk element. This reduces the constant factor
498     // compared to using swaps, which involves twice as many moves.
499     fn sift_up(&mut self, start: uint, mut pos: uint) {
500         unsafe {
501             let new = replace(&mut self.data[pos], zeroed());
502
503             while pos > start {
504                 let parent = (pos - 1) >> 1;
505
506                 if new <= self.data[parent] { break; }
507
508                 let x = replace(&mut self.data[parent], zeroed());
509                 ptr::write(&mut self.data[pos], x);
510                 pos = parent;
511             }
512             ptr::write(&mut self.data[pos], new);
513         }
514     }
515
516     fn sift_down_range(&mut self, mut pos: uint, end: uint) {
517         unsafe {
518             let start = pos;
519             let new = replace(&mut self.data[pos], zeroed());
520
521             let mut child = 2 * pos + 1;
522             while child < end {
523                 let right = child + 1;
524                 if right < end && !(self.data[child] > self.data[right]) {
525                     child = right;
526                 }
527                 let x = replace(&mut self.data[child], zeroed());
528                 ptr::write(&mut self.data[pos], x);
529                 pos = child;
530                 child = 2 * pos + 1;
531             }
532
533             ptr::write(&mut self.data[pos], new);
534             self.sift_up(start, pos);
535         }
536     }
537
538     fn sift_down(&mut self, pos: uint) {
539         let len = self.len();
540         self.sift_down_range(pos, len);
541     }
542
543     /// Returns the length of the binary heap.
544     #[stable]
545     pub fn len(&self) -> uint { self.data.len() }
546
547     /// Checks if the binary heap is empty.
548     #[stable]
549     pub fn is_empty(&self) -> bool { self.len() == 0 }
550
551     /// Clears the binary heap, returning an iterator over the removed elements.
552     #[inline]
553     #[unstable = "matches collection reform specification, waiting for dust to settle"]
554     pub fn drain(&mut self) -> Drain<T> {
555         Drain { iter: self.data.drain() }
556     }
557
558     /// Drops all items from the binary heap.
559     #[stable]
560     pub fn clear(&mut self) { self.drain(); }
561 }
562
563 /// `BinaryHeap` iterator.
564 pub struct Iter <'a, T: 'a> {
565     iter: slice::Iter<'a, T>,
566 }
567
568 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
569 impl<'a, T> Clone for Iter<'a, T> {
570     fn clone(&self) -> Iter<'a, T> {
571         Iter { iter: self.iter.clone() }
572     }
573 }
574
575 #[stable]
576 impl<'a, T> Iterator for Iter<'a, T> {
577     type Item = &'a T;
578
579     #[inline]
580     fn next(&mut self) -> Option<&'a T> { self.iter.next() }
581
582     #[inline]
583     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
584 }
585
586 #[stable]
587 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
588     #[inline]
589     fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
590 }
591
592 #[stable]
593 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
594
595 /// An iterator that moves out of a `BinaryHeap`.
596 pub struct IntoIter<T> {
597     iter: vec::IntoIter<T>,
598 }
599
600 #[stable]
601 impl<T> Iterator for IntoIter<T> {
602     type Item = T;
603
604     #[inline]
605     fn next(&mut self) -> Option<T> { self.iter.next() }
606
607     #[inline]
608     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
609 }
610
611 #[stable]
612 impl<T> DoubleEndedIterator for IntoIter<T> {
613     #[inline]
614     fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
615 }
616
617 #[stable]
618 impl<T> ExactSizeIterator for IntoIter<T> {}
619
620 /// An iterator that drains a `BinaryHeap`.
621 pub struct Drain<'a, T: 'a> {
622     iter: vec::Drain<'a, T>,
623 }
624
625 #[stable]
626 impl<'a, T: 'a> Iterator for Drain<'a, T> {
627     type Item = T;
628
629     #[inline]
630     fn next(&mut self) -> Option<T> { self.iter.next() }
631
632     #[inline]
633     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
634 }
635
636 #[stable]
637 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
638     #[inline]
639     fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
640 }
641
642 #[stable]
643 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
644
645 #[stable]
646 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
647     fn from_iter<Iter: Iterator<Item=T>>(iter: Iter) -> BinaryHeap<T> {
648         BinaryHeap::from_vec(iter.collect())
649     }
650 }
651
652 #[stable]
653 impl<T: Ord> Extend<T> for BinaryHeap<T> {
654     fn extend<Iter: Iterator<Item=T>>(&mut self, mut iter: Iter) {
655         let (lower, _) = iter.size_hint();
656
657         self.reserve(lower);
658
659         for elem in iter {
660             self.push(elem);
661         }
662     }
663 }
664
665 #[cfg(test)]
666 mod tests {
667     use prelude::*;
668
669     use super::BinaryHeap;
670
671     #[test]
672     fn test_iterator() {
673         let data = vec!(5i, 9, 3);
674         let iterout = [9i, 5, 3];
675         let heap = BinaryHeap::from_vec(data);
676         let mut i = 0;
677         for el in heap.iter() {
678             assert_eq!(*el, iterout[i]);
679             i += 1;
680         }
681     }
682
683     #[test]
684     fn test_iterator_reverse() {
685         let data = vec!(5i, 9, 3);
686         let iterout = vec!(3i, 5, 9);
687         let pq = BinaryHeap::from_vec(data);
688
689         let v: Vec<int> = pq.iter().rev().map(|&x| x).collect();
690         assert_eq!(v, iterout);
691     }
692
693     #[test]
694     fn test_move_iter() {
695         let data = vec!(5i, 9, 3);
696         let iterout = vec!(9i, 5, 3);
697         let pq = BinaryHeap::from_vec(data);
698
699         let v: Vec<int> = pq.into_iter().collect();
700         assert_eq!(v, iterout);
701     }
702
703     #[test]
704     fn test_move_iter_size_hint() {
705         let data = vec!(5i, 9);
706         let pq = BinaryHeap::from_vec(data);
707
708         let mut it = pq.into_iter();
709
710         assert_eq!(it.size_hint(), (2, Some(2)));
711         assert_eq!(it.next(), Some(9i));
712
713         assert_eq!(it.size_hint(), (1, Some(1)));
714         assert_eq!(it.next(), Some(5i));
715
716         assert_eq!(it.size_hint(), (0, Some(0)));
717         assert_eq!(it.next(), None);
718     }
719
720     #[test]
721     fn test_move_iter_reverse() {
722         let data = vec!(5i, 9, 3);
723         let iterout = vec!(3i, 5, 9);
724         let pq = BinaryHeap::from_vec(data);
725
726         let v: Vec<int> = pq.into_iter().rev().collect();
727         assert_eq!(v, iterout);
728     }
729
730     #[test]
731     fn test_peek_and_pop() {
732         let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1);
733         let mut sorted = data.clone();
734         sorted.sort();
735         let mut heap = BinaryHeap::from_vec(data);
736         while !heap.is_empty() {
737             assert_eq!(heap.peek().unwrap(), sorted.last().unwrap());
738             assert_eq!(heap.pop().unwrap(), sorted.pop().unwrap());
739         }
740     }
741
742     #[test]
743     fn test_push() {
744         let mut heap = BinaryHeap::from_vec(vec!(2i, 4, 9));
745         assert_eq!(heap.len(), 3);
746         assert!(*heap.peek().unwrap() == 9);
747         heap.push(11);
748         assert_eq!(heap.len(), 4);
749         assert!(*heap.peek().unwrap() == 11);
750         heap.push(5);
751         assert_eq!(heap.len(), 5);
752         assert!(*heap.peek().unwrap() == 11);
753         heap.push(27);
754         assert_eq!(heap.len(), 6);
755         assert!(*heap.peek().unwrap() == 27);
756         heap.push(3);
757         assert_eq!(heap.len(), 7);
758         assert!(*heap.peek().unwrap() == 27);
759         heap.push(103);
760         assert_eq!(heap.len(), 8);
761         assert!(*heap.peek().unwrap() == 103);
762     }
763
764     #[test]
765     fn test_push_unique() {
766         let mut heap = BinaryHeap::from_vec(vec!(box 2i, box 4, box 9));
767         assert_eq!(heap.len(), 3);
768         assert!(*heap.peek().unwrap() == box 9);
769         heap.push(box 11);
770         assert_eq!(heap.len(), 4);
771         assert!(*heap.peek().unwrap() == box 11);
772         heap.push(box 5);
773         assert_eq!(heap.len(), 5);
774         assert!(*heap.peek().unwrap() == box 11);
775         heap.push(box 27);
776         assert_eq!(heap.len(), 6);
777         assert!(*heap.peek().unwrap() == box 27);
778         heap.push(box 3);
779         assert_eq!(heap.len(), 7);
780         assert!(*heap.peek().unwrap() == box 27);
781         heap.push(box 103);
782         assert_eq!(heap.len(), 8);
783         assert!(*heap.peek().unwrap() == box 103);
784     }
785
786     #[test]
787     fn test_push_pop() {
788         let mut heap = BinaryHeap::from_vec(vec!(5i, 5, 2, 1, 3));
789         assert_eq!(heap.len(), 5);
790         assert_eq!(heap.push_pop(6), 6);
791         assert_eq!(heap.len(), 5);
792         assert_eq!(heap.push_pop(0), 5);
793         assert_eq!(heap.len(), 5);
794         assert_eq!(heap.push_pop(4), 5);
795         assert_eq!(heap.len(), 5);
796         assert_eq!(heap.push_pop(1), 4);
797         assert_eq!(heap.len(), 5);
798     }
799
800     #[test]
801     fn test_replace() {
802         let mut heap = BinaryHeap::from_vec(vec!(5i, 5, 2, 1, 3));
803         assert_eq!(heap.len(), 5);
804         assert_eq!(heap.replace(6).unwrap(), 5);
805         assert_eq!(heap.len(), 5);
806         assert_eq!(heap.replace(0).unwrap(), 6);
807         assert_eq!(heap.len(), 5);
808         assert_eq!(heap.replace(4).unwrap(), 5);
809         assert_eq!(heap.len(), 5);
810         assert_eq!(heap.replace(1).unwrap(), 4);
811         assert_eq!(heap.len(), 5);
812     }
813
814     fn check_to_vec(mut data: Vec<int>) {
815         let heap = BinaryHeap::from_vec(data.clone());
816         let mut v = heap.clone().into_vec();
817         v.sort();
818         data.sort();
819
820         assert_eq!(v, data);
821         assert_eq!(heap.into_sorted_vec(), data);
822     }
823
824     #[test]
825     fn test_to_vec() {
826         check_to_vec(vec!());
827         check_to_vec(vec!(5i));
828         check_to_vec(vec!(3i, 2));
829         check_to_vec(vec!(2i, 3));
830         check_to_vec(vec!(5i, 1, 2));
831         check_to_vec(vec!(1i, 100, 2, 3));
832         check_to_vec(vec!(1i, 3, 5, 7, 9, 2, 4, 6, 8, 0));
833         check_to_vec(vec!(2i, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
834         check_to_vec(vec!(9i, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
835         check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
836         check_to_vec(vec!(10i, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
837         check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
838         check_to_vec(vec!(5i, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
839     }
840
841     #[test]
842     fn test_empty_pop() {
843         let mut heap = BinaryHeap::<int>::new();
844         assert!(heap.pop().is_none());
845     }
846
847     #[test]
848     fn test_empty_peek() {
849         let empty = BinaryHeap::<int>::new();
850         assert!(empty.peek().is_none());
851     }
852
853     #[test]
854     fn test_empty_replace() {
855         let mut heap = BinaryHeap::<int>::new();
856         assert!(heap.replace(5).is_none());
857     }
858
859     #[test]
860     fn test_from_iter() {
861         let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1);
862
863         let mut q: BinaryHeap<uint> = xs.iter().rev().map(|&x| x).collect();
864
865         for &x in xs.iter() {
866             assert_eq!(q.pop().unwrap(), x);
867         }
868     }
869
870     #[test]
871     fn test_drain() {
872         let mut q: BinaryHeap<_> =
873             [9u, 8, 7, 6, 5, 4, 3, 2, 1].iter().cloned().collect();
874
875         assert_eq!(q.drain().take(5).count(), 5);
876
877         assert!(q.is_empty());
878     }
879 }