]> git.lizzy.rs Git - rust.git/blob - src/libcollections/priority_queue.rs
Move info into individual modules.
[rust.git] / src / libcollections / priority_queue.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 //! Insertions have `O(log n)` time complexity and checking or popping the largest element is
14 //! `O(1)`. Converting a vector to a priority queue can be done in-place, and has `O(n)`
15 //! complexity. A priority queue 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 //! # Example
19 //!
20 //! This is a larger example which implements [Dijkstra's algorithm][dijkstra]
21 //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
22 //! It showcases how to use the `PriorityQueue` 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::collections::PriorityQueue;
30 //! use std::uint;
31 //!
32 //! #[deriving(Eq, PartialEq)]
33 //! struct State {
34 //!     cost: uint,
35 //!     position: uint
36 //! }
37 //!
38 //! // The priority queue depends on `Ord`.
39 //! // Explicitly implement the trait so the queue becomes a min-heap
40 //! // instead of a max-heap.
41 //! impl Ord for State {
42 //!     fn cmp(&self, other: &State) -> Ordering {
43 //!         // Notice that the we flip the ordering here
44 //!         other.cost.cmp(&self.cost)
45 //!     }
46 //! }
47 //!
48 //! // `PartialOrd` needs to be implemented as well.
49 //! impl PartialOrd for State {
50 //!     fn partial_cmp(&self, other: &State) -> Option<Ordering> {
51 //!         Some(self.cmp(other))
52 //!     }
53 //! }
54 //!
55 //! // Each node is represented as an `uint`, for a shorter implementation.
56 //! struct Edge {
57 //!     node: uint,
58 //!     cost: uint
59 //! }
60 //!
61 //! // Dijkstra's shortest path algorithm.
62 //!
63 //! // Start at `start` and use `dist` to track the current shortest distance
64 //! // to each node. This implementation isn't memory efficient as it may leave duplicate
65 //! // nodes in the queue. It also uses `uint::MAX` as a sentinel value,
66 //! // for a simpler implementation.
67 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: uint, goal: uint) -> uint {
68 //!     // dist[node] = current shortest distance from `start` to `node`
69 //!     let mut dist = Vec::from_elem(adj_list.len(), uint::MAX);
70 //!
71 //!     let mut pq = PriorityQueue::new();
72 //!
73 //!     // We're at `start`, with a zero cost
74 //!     *dist.get_mut(start) = 0u;
75 //!     pq.push(State { cost: 0u, position: start });
76 //!
77 //!     // Examine the frontier with lower cost nodes first (min-heap)
78 //!     loop {
79 //!         let State { cost, position } = match pq.pop() {
80 //!             None => break, // empty
81 //!             Some(s) => s
82 //!         };
83 //!
84 //!         // Alternatively we could have continued to find all shortest paths
85 //!         if position == goal { return cost }
86 //!
87 //!         // Important as we may have already found a better way
88 //!         if cost > dist[position] { continue }
89 //!
90 //!         // For each node we can reach, see if we can find a way with
91 //!         // a lower cost going through this node
92 //!         for edge in adj_list[position].iter() {
93 //!             let next = State { cost: cost + edge.cost, position: edge.node };
94 //!
95 //!             // If so, add it to the frontier and continue
96 //!             if next.cost < dist[next.position] {
97 //!                 pq.push(next);
98 //!                 // Relaxation, we have now found a better way
99 //!                 *dist.get_mut(next.position) = next.cost;
100 //!             }
101 //!         }
102 //!     }
103 //!
104 //!     // Goal not reachable
105 //!     uint::MAX
106 //! }
107 //!
108 //! fn main() {
109 //!     // This is the directed graph we're going to use.
110 //!     // The node numbers correspond to the different states,
111 //!     // and the edge weights symbolises the cost of moving
112 //!     // from one node to another.
113 //!     // Note that the edges are one-way.
114 //!     //
115 //!     //                  7
116 //!     //          +-----------------+
117 //!     //          |                 |
118 //!     //          v   1        2    |
119 //!     //          0 -----> 1 -----> 3 ---> 4
120 //!     //          |        ^        ^      ^
121 //!     //          |        | 1      |      |
122 //!     //          |        |        | 3    | 1
123 //!     //          +------> 2 -------+      |
124 //!     //           10      |               |
125 //!     //                   +---------------+
126 //!     //
127 //!     // The graph is represented as an adjacency list where each index,
128 //!     // corresponding to a node value, has a list of outgoing edges.
129 //!     // Chosen for it's efficiency.
130 //!     let graph = vec![
131 //!         // Node 0
132 //!         vec![Edge { node: 2, cost: 10 },
133 //!              Edge { node: 1, cost: 1 }],
134 //!         // Node 1
135 //!         vec![Edge { node: 3, cost: 2 }],
136 //!         // Node 2
137 //!         vec![Edge { node: 1, cost: 1 },
138 //!              Edge { node: 3, cost: 3 },
139 //!              Edge { node: 4, cost: 1 }],
140 //!         // Node 3
141 //!         vec![Edge { node: 0, cost: 7 },
142 //!              Edge { node: 4, cost: 2 }],
143 //!         // Node 4
144 //!         vec![]];
145 //!
146 //!     assert_eq!(shortest_path(&graph, 0, 1), 1);
147 //!     assert_eq!(shortest_path(&graph, 0, 3), 3);
148 //!     assert_eq!(shortest_path(&graph, 3, 0), 7);
149 //!     assert_eq!(shortest_path(&graph, 0, 4), 5);
150 //!     assert_eq!(shortest_path(&graph, 4, 0), uint::MAX);
151 //! }
152 //! ```
153
154 #![allow(missing_doc)]
155
156 use core::prelude::*;
157
158 use core::default::Default;
159 use core::mem::{zeroed, replace, swap};
160 use core::ptr;
161
162 use {Mutable, MutableSeq};
163 use slice;
164 use vec::Vec;
165
166 /// A priority queue implemented with a binary heap.
167 ///
168 /// This will be a max-heap.
169 #[deriving(Clone)]
170 pub struct PriorityQueue<T> {
171     data: Vec<T>,
172 }
173
174 impl<T: Ord> Collection for PriorityQueue<T> {
175     /// Returns the length of the queue.
176     fn len(&self) -> uint { self.data.len() }
177 }
178
179 impl<T: Ord> Mutable for PriorityQueue<T> {
180     /// Drops all items from the queue.
181     fn clear(&mut self) { self.data.truncate(0) }
182 }
183
184 impl<T: Ord> Default for PriorityQueue<T> {
185     #[inline]
186     fn default() -> PriorityQueue<T> { PriorityQueue::new() }
187 }
188
189 impl<T: Ord> PriorityQueue<T> {
190     /// Creates an empty `PriorityQueue` as a max-heap.
191     ///
192     /// # Example
193     ///
194     /// ```
195     /// use std::collections::PriorityQueue;
196     /// let pq: PriorityQueue<uint> = PriorityQueue::new();
197     /// ```
198     pub fn new() -> PriorityQueue<T> { PriorityQueue{data: vec!(),} }
199
200     /// Creates an empty `PriorityQueue` with a specific capacity.
201     /// This preallocates enough memory for `capacity` elements,
202     /// so that the `PriorityQueue` does not have to be reallocated
203     /// until it contains at least that many values.
204     ///
205     /// # Example
206     ///
207     /// ```
208     /// use std::collections::PriorityQueue;
209     /// let pq: PriorityQueue<uint> = PriorityQueue::with_capacity(10u);
210     /// ```
211     pub fn with_capacity(capacity: uint) -> PriorityQueue<T> {
212         PriorityQueue { data: Vec::with_capacity(capacity) }
213     }
214
215     /// Creates a `PriorityQueue` from a vector. This is sometimes called
216     /// `heapifying` the vector.
217     ///
218     /// # Example
219     ///
220     /// ```
221     /// use std::collections::PriorityQueue;
222     /// let pq = PriorityQueue::from_vec(vec![9i, 1, 2, 7, 3, 2]);
223     /// ```
224     pub fn from_vec(xs: Vec<T>) -> PriorityQueue<T> {
225         let mut q = PriorityQueue{data: xs,};
226         let mut n = q.len() / 2;
227         while n > 0 {
228             n -= 1;
229             q.siftdown(n)
230         }
231         q
232     }
233
234     /// An iterator visiting all values in underlying vector, in
235     /// arbitrary order.
236     ///
237     /// # Example
238     ///
239     /// ```
240     /// use std::collections::PriorityQueue;
241     /// let pq = PriorityQueue::from_vec(vec![1i, 2, 3, 4]);
242     ///
243     /// // Print 1, 2, 3, 4 in arbitrary order
244     /// for x in pq.iter() {
245     ///     println!("{}", x);
246     /// }
247     /// ```
248     pub fn iter<'a>(&'a self) -> Items<'a, T> {
249         Items { iter: self.data.iter() }
250     }
251
252     /// Returns the greatest item in a queue, or `None` if it is empty.
253     ///
254     /// # Example
255     ///
256     /// ```
257     /// use std::collections::PriorityQueue;
258     ///
259     /// let mut pq = PriorityQueue::new();
260     /// assert_eq!(pq.top(), None);
261     ///
262     /// pq.push(1i);
263     /// pq.push(5i);
264     /// pq.push(2i);
265     /// assert_eq!(pq.top(), Some(&5i));
266     ///
267     /// ```
268     pub fn top<'a>(&'a self) -> Option<&'a T> {
269         if self.is_empty() { None } else { Some(&self.data[0]) }
270     }
271
272     #[deprecated="renamed to `top`"]
273     pub fn maybe_top<'a>(&'a self) -> Option<&'a T> { self.top() }
274
275     /// Returns the number of elements the queue can hold without reallocating.
276     ///
277     /// # Example
278     ///
279     /// ```
280     /// use std::collections::PriorityQueue;
281     ///
282     /// let pq: PriorityQueue<uint> = PriorityQueue::with_capacity(100u);
283     /// assert!(pq.capacity() >= 100u);
284     /// ```
285     pub fn capacity(&self) -> uint { self.data.capacity() }
286
287     /// Reserves capacity for exactly `n` elements in the `PriorityQueue`.
288     /// Do nothing if the capacity is already sufficient.
289     ///
290     /// # Example
291     ///
292     /// ```
293     /// use std::collections::PriorityQueue;
294     ///
295     /// let mut pq: PriorityQueue<uint> = PriorityQueue::new();
296     /// pq.reserve_exact(100u);
297     /// assert!(pq.capacity() == 100u);
298     /// ```
299     pub fn reserve_exact(&mut self, n: uint) { self.data.reserve_exact(n) }
300
301     /// Reserves capacity for at least `n` elements in the `PriorityQueue`.
302     /// Do nothing if the capacity is already sufficient.
303     ///
304     /// # Example
305     ///
306     /// ```
307     /// use std::collections::PriorityQueue;
308     ///
309     /// let mut pq: PriorityQueue<uint> = PriorityQueue::new();
310     /// pq.reserve(100u);
311     /// assert!(pq.capacity() >= 100u);
312     /// ```
313     pub fn reserve(&mut self, n: uint) {
314         self.data.reserve(n)
315     }
316
317     /// Removes the greatest item from a queue and returns it, or `None` if it
318     /// is empty.
319     ///
320     /// # Example
321     ///
322     /// ```
323     /// use std::collections::PriorityQueue;
324     ///
325     /// let mut pq = PriorityQueue::from_vec(vec![1i, 3]);
326     ///
327     /// assert_eq!(pq.pop(), Some(3i));
328     /// assert_eq!(pq.pop(), Some(1i));
329     /// assert_eq!(pq.pop(), None);
330     /// ```
331     pub fn pop(&mut self) -> Option<T> {
332         match self.data.pop() {
333             None           => { None }
334             Some(mut item) => {
335                 if !self.is_empty() {
336                     swap(&mut item, self.data.get_mut(0));
337                     self.siftdown(0);
338                 }
339                 Some(item)
340             }
341         }
342     }
343
344     #[deprecated="renamed to `pop`"]
345     pub fn maybe_pop(&mut self) -> Option<T> { self.pop() }
346
347     /// Pushes an item onto the queue.
348     ///
349     /// # Example
350     ///
351     /// ```
352     /// use std::collections::PriorityQueue;
353     ///
354     /// let mut pq = PriorityQueue::new();
355     /// pq.push(3i);
356     /// pq.push(5i);
357     /// pq.push(1i);
358     ///
359     /// assert_eq!(pq.len(), 3);
360     /// assert_eq!(pq.top(), Some(&5i));
361     /// ```
362     pub fn push(&mut self, item: T) {
363         self.data.push(item);
364         let new_len = self.len() - 1;
365         self.siftup(0, new_len);
366     }
367
368     /// Pushes an item onto a queue then pops the greatest item off the queue in
369     /// an optimized fashion.
370     ///
371     /// # Example
372     ///
373     /// ```
374     /// use std::collections::PriorityQueue;
375     ///
376     /// let mut pq = PriorityQueue::new();
377     /// pq.push(1i);
378     /// pq.push(5i);
379     ///
380     /// assert_eq!(pq.push_pop(3i), 5);
381     /// assert_eq!(pq.push_pop(9i), 9);
382     /// assert_eq!(pq.len(), 2);
383     /// assert_eq!(pq.top(), Some(&3i));
384     /// ```
385     pub fn push_pop(&mut self, mut item: T) -> T {
386         if !self.is_empty() && *self.top().unwrap() > item {
387             swap(&mut item, self.data.get_mut(0));
388             self.siftdown(0);
389         }
390         item
391     }
392
393     /// Pops the greatest item off a queue then pushes an item onto the queue in
394     /// an optimized fashion. The push is done regardless of whether the queue
395     /// was empty.
396     ///
397     /// # Example
398     ///
399     /// ```
400     /// use std::collections::PriorityQueue;
401     ///
402     /// let mut pq = PriorityQueue::new();
403     ///
404     /// assert_eq!(pq.replace(1i), None);
405     /// assert_eq!(pq.replace(3i), Some(1i));
406     /// assert_eq!(pq.len(), 1);
407     /// assert_eq!(pq.top(), Some(&3i));
408     /// ```
409     pub fn replace(&mut self, mut item: T) -> Option<T> {
410         if !self.is_empty() {
411             swap(&mut item, self.data.get_mut(0));
412             self.siftdown(0);
413             Some(item)
414         } else {
415             self.push(item);
416             None
417         }
418     }
419
420     #[allow(dead_code)]
421     #[deprecated="renamed to `into_vec`"]
422     fn to_vec(self) -> Vec<T> { self.into_vec() }
423
424     #[allow(dead_code)]
425     #[deprecated="renamed to `into_sorted_vec`"]
426     fn to_sorted_vec(self) -> Vec<T> { self.into_sorted_vec() }
427
428     /// Consumes the `PriorityQueue` and returns the underlying vector
429     /// in arbitrary order.
430     ///
431     /// # Example
432     ///
433     /// ```
434     /// use std::collections::PriorityQueue;
435     ///
436     /// let pq = PriorityQueue::from_vec(vec![1i, 2, 3, 4, 5, 6, 7]);
437     /// let vec = pq.into_vec();
438     ///
439     /// // Will print in some order
440     /// for x in vec.iter() {
441     ///     println!("{}", x);
442     /// }
443     /// ```
444     pub fn into_vec(self) -> Vec<T> { let PriorityQueue{data: v} = self; v }
445
446     /// Consumes the `PriorityQueue` and returns a vector in sorted
447     /// (ascending) order.
448     ///
449     /// # Example
450     ///
451     /// ```
452     /// use std::collections::PriorityQueue;
453     ///
454     /// let mut pq = PriorityQueue::from_vec(vec![1i, 2, 4, 5, 7]);
455     /// pq.push(6);
456     /// pq.push(3);
457     ///
458     /// let vec = pq.into_sorted_vec();
459     /// assert_eq!(vec, vec![1i, 2, 3, 4, 5, 6, 7]);
460     /// ```
461     pub fn into_sorted_vec(self) -> Vec<T> {
462         let mut q = self;
463         let mut end = q.len();
464         while end > 1 {
465             end -= 1;
466             q.data.as_mut_slice().swap(0, end);
467             q.siftdown_range(0, end)
468         }
469         q.into_vec()
470     }
471
472     // The implementations of siftup and siftdown use unsafe blocks in
473     // order to move an element out of the vector (leaving behind a
474     // zeroed element), shift along the others and move it back into the
475     // vector over the junk element.  This reduces the constant factor
476     // compared to using swaps, which involves twice as many moves.
477     fn siftup(&mut self, start: uint, mut pos: uint) {
478         unsafe {
479             let new = replace(self.data.get_mut(pos), zeroed());
480
481             while pos > start {
482                 let parent = (pos - 1) >> 1;
483                 if new > self.data[parent] {
484                     let x = replace(self.data.get_mut(parent), zeroed());
485                     ptr::write(self.data.get_mut(pos), x);
486                     pos = parent;
487                     continue
488                 }
489                 break
490             }
491             ptr::write(self.data.get_mut(pos), new);
492         }
493     }
494
495     fn siftdown_range(&mut self, mut pos: uint, end: uint) {
496         unsafe {
497             let start = pos;
498             let new = replace(self.data.get_mut(pos), zeroed());
499
500             let mut child = 2 * pos + 1;
501             while child < end {
502                 let right = child + 1;
503                 if right < end && !(self.data[child] > self.data[right]) {
504                     child = right;
505                 }
506                 let x = replace(self.data.get_mut(child), zeroed());
507                 ptr::write(self.data.get_mut(pos), x);
508                 pos = child;
509                 child = 2 * pos + 1;
510             }
511
512             ptr::write(self.data.get_mut(pos), new);
513             self.siftup(start, pos);
514         }
515     }
516
517     fn siftdown(&mut self, pos: uint) {
518         let len = self.len();
519         self.siftdown_range(pos, len);
520     }
521 }
522
523 /// `PriorityQueue` iterator.
524 pub struct Items <'a, T:'a> {
525     iter: slice::Items<'a, T>,
526 }
527
528 impl<'a, T> Iterator<&'a T> for Items<'a, T> {
529     #[inline]
530     fn next(&mut self) -> Option<(&'a T)> { self.iter.next() }
531
532     #[inline]
533     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
534 }
535
536 impl<T: Ord> FromIterator<T> for PriorityQueue<T> {
537     fn from_iter<Iter: Iterator<T>>(mut iter: Iter) -> PriorityQueue<T> {
538         let vec: Vec<T> = iter.collect();
539         PriorityQueue::from_vec(vec)
540     }
541 }
542
543 impl<T: Ord> Extendable<T> for PriorityQueue<T> {
544     fn extend<Iter: Iterator<T>>(&mut self, mut iter: Iter) {
545         let (lower, _) = iter.size_hint();
546
547         let len = self.capacity();
548         self.reserve(len + lower);
549
550         for elem in iter {
551             self.push(elem);
552         }
553     }
554 }
555
556 #[cfg(test)]
557 mod tests {
558     use std::prelude::*;
559
560     use priority_queue::PriorityQueue;
561     use vec::Vec;
562     use MutableSeq;
563
564     #[test]
565     fn test_iterator() {
566         let data = vec!(5i, 9, 3);
567         let iterout = [9i, 5, 3];
568         let pq = PriorityQueue::from_vec(data);
569         let mut i = 0;
570         for el in pq.iter() {
571             assert_eq!(*el, iterout[i]);
572             i += 1;
573         }
574     }
575
576     #[test]
577     fn test_top_and_pop() {
578         let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1);
579         let mut sorted = data.clone();
580         sorted.sort();
581         let mut heap = PriorityQueue::from_vec(data);
582         while !heap.is_empty() {
583             assert_eq!(heap.top().unwrap(), sorted.last().unwrap());
584             assert_eq!(heap.pop().unwrap(), sorted.pop().unwrap());
585         }
586     }
587
588     #[test]
589     fn test_push() {
590         let mut heap = PriorityQueue::from_vec(vec!(2i, 4, 9));
591         assert_eq!(heap.len(), 3);
592         assert!(*heap.top().unwrap() == 9);
593         heap.push(11);
594         assert_eq!(heap.len(), 4);
595         assert!(*heap.top().unwrap() == 11);
596         heap.push(5);
597         assert_eq!(heap.len(), 5);
598         assert!(*heap.top().unwrap() == 11);
599         heap.push(27);
600         assert_eq!(heap.len(), 6);
601         assert!(*heap.top().unwrap() == 27);
602         heap.push(3);
603         assert_eq!(heap.len(), 7);
604         assert!(*heap.top().unwrap() == 27);
605         heap.push(103);
606         assert_eq!(heap.len(), 8);
607         assert!(*heap.top().unwrap() == 103);
608     }
609
610     #[test]
611     fn test_push_unique() {
612         let mut heap = PriorityQueue::from_vec(vec!(box 2i, box 4, box 9));
613         assert_eq!(heap.len(), 3);
614         assert!(*heap.top().unwrap() == box 9);
615         heap.push(box 11);
616         assert_eq!(heap.len(), 4);
617         assert!(*heap.top().unwrap() == box 11);
618         heap.push(box 5);
619         assert_eq!(heap.len(), 5);
620         assert!(*heap.top().unwrap() == box 11);
621         heap.push(box 27);
622         assert_eq!(heap.len(), 6);
623         assert!(*heap.top().unwrap() == box 27);
624         heap.push(box 3);
625         assert_eq!(heap.len(), 7);
626         assert!(*heap.top().unwrap() == box 27);
627         heap.push(box 103);
628         assert_eq!(heap.len(), 8);
629         assert!(*heap.top().unwrap() == box 103);
630     }
631
632     #[test]
633     fn test_push_pop() {
634         let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
635         assert_eq!(heap.len(), 5);
636         assert_eq!(heap.push_pop(6), 6);
637         assert_eq!(heap.len(), 5);
638         assert_eq!(heap.push_pop(0), 5);
639         assert_eq!(heap.len(), 5);
640         assert_eq!(heap.push_pop(4), 5);
641         assert_eq!(heap.len(), 5);
642         assert_eq!(heap.push_pop(1), 4);
643         assert_eq!(heap.len(), 5);
644     }
645
646     #[test]
647     fn test_replace() {
648         let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
649         assert_eq!(heap.len(), 5);
650         assert_eq!(heap.replace(6).unwrap(), 5);
651         assert_eq!(heap.len(), 5);
652         assert_eq!(heap.replace(0).unwrap(), 6);
653         assert_eq!(heap.len(), 5);
654         assert_eq!(heap.replace(4).unwrap(), 5);
655         assert_eq!(heap.len(), 5);
656         assert_eq!(heap.replace(1).unwrap(), 4);
657         assert_eq!(heap.len(), 5);
658     }
659
660     fn check_to_vec(mut data: Vec<int>) {
661         let heap = PriorityQueue::from_vec(data.clone());
662         let mut v = heap.clone().into_vec();
663         v.sort();
664         data.sort();
665
666         assert_eq!(v.as_slice(), data.as_slice());
667         assert_eq!(heap.into_sorted_vec().as_slice(), data.as_slice());
668     }
669
670     #[test]
671     fn test_to_vec() {
672         check_to_vec(vec!());
673         check_to_vec(vec!(5i));
674         check_to_vec(vec!(3i, 2));
675         check_to_vec(vec!(2i, 3));
676         check_to_vec(vec!(5i, 1, 2));
677         check_to_vec(vec!(1i, 100, 2, 3));
678         check_to_vec(vec!(1i, 3, 5, 7, 9, 2, 4, 6, 8, 0));
679         check_to_vec(vec!(2i, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
680         check_to_vec(vec!(9i, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
681         check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
682         check_to_vec(vec!(10i, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
683         check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
684         check_to_vec(vec!(5i, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
685     }
686
687     #[test]
688     fn test_empty_pop() {
689         let mut heap: PriorityQueue<int> = PriorityQueue::new();
690         assert!(heap.pop().is_none());
691     }
692
693     #[test]
694     fn test_empty_top() {
695         let empty: PriorityQueue<int> = PriorityQueue::new();
696         assert!(empty.top().is_none());
697     }
698
699     #[test]
700     fn test_empty_replace() {
701         let mut heap: PriorityQueue<int> = PriorityQueue::new();
702         heap.replace(5).is_none();
703     }
704
705     #[test]
706     fn test_from_iter() {
707         let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1);
708
709         let mut q: PriorityQueue<uint> = xs.as_slice().iter().rev().map(|&x| x).collect();
710
711         for &x in xs.iter() {
712             assert_eq!(q.pop().unwrap(), x);
713         }
714     }
715 }