]> git.lizzy.rs Git - rust.git/blob - src/libcollections/priority_queue.rs
rollup merge of #16832 : SebastianZaha/fix-inconsistent-version-numbering
[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 /// `PriorityQueue` iterator.
519 pub struct Items <'a, T:'a> {
520     iter: slice::Items<'a, T>,
521 }
522
523 impl<'a, T> Iterator<&'a T> for Items<'a, T> {
524     #[inline]
525     fn next(&mut self) -> Option<(&'a T)> { self.iter.next() }
526
527     #[inline]
528     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
529 }
530
531 impl<T: Ord> FromIterator<T> for PriorityQueue<T> {
532     fn from_iter<Iter: Iterator<T>>(mut iter: Iter) -> PriorityQueue<T> {
533         let vec: Vec<T> = iter.collect();
534         PriorityQueue::from_vec(vec)
535     }
536 }
537
538 impl<T: Ord> Extendable<T> for PriorityQueue<T> {
539     fn extend<Iter: Iterator<T>>(&mut self, mut iter: Iter) {
540         let (lower, _) = iter.size_hint();
541
542         let len = self.capacity();
543         self.reserve(len + lower);
544
545         for elem in iter {
546             self.push(elem);
547         }
548     }
549 }
550
551 #[cfg(test)]
552 mod tests {
553     use std::prelude::*;
554
555     use priority_queue::PriorityQueue;
556     use vec::Vec;
557     use MutableSeq;
558
559     #[test]
560     fn test_iterator() {
561         let data = vec!(5i, 9, 3);
562         let iterout = [9i, 5, 3];
563         let pq = PriorityQueue::from_vec(data);
564         let mut i = 0;
565         for el in pq.iter() {
566             assert_eq!(*el, iterout[i]);
567             i += 1;
568         }
569     }
570
571     #[test]
572     fn test_top_and_pop() {
573         let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1);
574         let mut sorted = data.clone();
575         sorted.sort();
576         let mut heap = PriorityQueue::from_vec(data);
577         while !heap.is_empty() {
578             assert_eq!(heap.top().unwrap(), sorted.last().unwrap());
579             assert_eq!(heap.pop().unwrap(), sorted.pop().unwrap());
580         }
581     }
582
583     #[test]
584     fn test_push() {
585         let mut heap = PriorityQueue::from_vec(vec!(2i, 4, 9));
586         assert_eq!(heap.len(), 3);
587         assert!(*heap.top().unwrap() == 9);
588         heap.push(11);
589         assert_eq!(heap.len(), 4);
590         assert!(*heap.top().unwrap() == 11);
591         heap.push(5);
592         assert_eq!(heap.len(), 5);
593         assert!(*heap.top().unwrap() == 11);
594         heap.push(27);
595         assert_eq!(heap.len(), 6);
596         assert!(*heap.top().unwrap() == 27);
597         heap.push(3);
598         assert_eq!(heap.len(), 7);
599         assert!(*heap.top().unwrap() == 27);
600         heap.push(103);
601         assert_eq!(heap.len(), 8);
602         assert!(*heap.top().unwrap() == 103);
603     }
604
605     #[test]
606     fn test_push_unique() {
607         let mut heap = PriorityQueue::from_vec(vec!(box 2i, box 4, box 9));
608         assert_eq!(heap.len(), 3);
609         assert!(*heap.top().unwrap() == box 9);
610         heap.push(box 11);
611         assert_eq!(heap.len(), 4);
612         assert!(*heap.top().unwrap() == box 11);
613         heap.push(box 5);
614         assert_eq!(heap.len(), 5);
615         assert!(*heap.top().unwrap() == box 11);
616         heap.push(box 27);
617         assert_eq!(heap.len(), 6);
618         assert!(*heap.top().unwrap() == box 27);
619         heap.push(box 3);
620         assert_eq!(heap.len(), 7);
621         assert!(*heap.top().unwrap() == box 27);
622         heap.push(box 103);
623         assert_eq!(heap.len(), 8);
624         assert!(*heap.top().unwrap() == box 103);
625     }
626
627     #[test]
628     fn test_push_pop() {
629         let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
630         assert_eq!(heap.len(), 5);
631         assert_eq!(heap.push_pop(6), 6);
632         assert_eq!(heap.len(), 5);
633         assert_eq!(heap.push_pop(0), 5);
634         assert_eq!(heap.len(), 5);
635         assert_eq!(heap.push_pop(4), 5);
636         assert_eq!(heap.len(), 5);
637         assert_eq!(heap.push_pop(1), 4);
638         assert_eq!(heap.len(), 5);
639     }
640
641     #[test]
642     fn test_replace() {
643         let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
644         assert_eq!(heap.len(), 5);
645         assert_eq!(heap.replace(6).unwrap(), 5);
646         assert_eq!(heap.len(), 5);
647         assert_eq!(heap.replace(0).unwrap(), 6);
648         assert_eq!(heap.len(), 5);
649         assert_eq!(heap.replace(4).unwrap(), 5);
650         assert_eq!(heap.len(), 5);
651         assert_eq!(heap.replace(1).unwrap(), 4);
652         assert_eq!(heap.len(), 5);
653     }
654
655     fn check_to_vec(mut data: Vec<int>) {
656         let heap = PriorityQueue::from_vec(data.clone());
657         let mut v = heap.clone().into_vec();
658         v.sort();
659         data.sort();
660
661         assert_eq!(v.as_slice(), data.as_slice());
662         assert_eq!(heap.into_sorted_vec().as_slice(), data.as_slice());
663     }
664
665     #[test]
666     fn test_to_vec() {
667         check_to_vec(vec!());
668         check_to_vec(vec!(5i));
669         check_to_vec(vec!(3i, 2));
670         check_to_vec(vec!(2i, 3));
671         check_to_vec(vec!(5i, 1, 2));
672         check_to_vec(vec!(1i, 100, 2, 3));
673         check_to_vec(vec!(1i, 3, 5, 7, 9, 2, 4, 6, 8, 0));
674         check_to_vec(vec!(2i, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
675         check_to_vec(vec!(9i, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
676         check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
677         check_to_vec(vec!(10i, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
678         check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
679         check_to_vec(vec!(5i, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
680     }
681
682     #[test]
683     fn test_empty_pop() {
684         let mut heap: PriorityQueue<int> = PriorityQueue::new();
685         assert!(heap.pop().is_none());
686     }
687
688     #[test]
689     fn test_empty_top() {
690         let empty: PriorityQueue<int> = PriorityQueue::new();
691         assert!(empty.top().is_none());
692     }
693
694     #[test]
695     fn test_empty_replace() {
696         let mut heap: PriorityQueue<int> = PriorityQueue::new();
697         heap.replace(5).is_none();
698     }
699
700     #[test]
701     fn test_from_iter() {
702         let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1);
703
704         let mut q: PriorityQueue<uint> = xs.as_slice().iter().rev().map(|&x| x).collect();
705
706         for &x in xs.iter() {
707             assert_eq!(q.pop().unwrap(), x);
708         }
709     }
710 }