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