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