]> git.lizzy.rs Git - rust.git/blob - src/libcollections/binary_heap.rs
Auto merge of #27630 - sylvestre:master, r=dotdash
[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.
14 //! Checking the largest element is `O(1)`. Converting a vector to a binary heap
15 //! can be done in-place, and has `O(n)` complexity. A binary heap can also be
16 //! converted to a sorted vector in-place, allowing it to be used for an `O(n
17 //! log n)` in-place heapsort.
18 //!
19 //! # Examples
20 //!
21 //! This is a larger example that implements [Dijkstra's algorithm][dijkstra]
22 //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
23 //! It shows how to use `BinaryHeap` with custom types.
24 //!
25 //! [dijkstra]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
26 //! [sssp]: http://en.wikipedia.org/wiki/Shortest_path_problem
27 //! [dir_graph]: http://en.wikipedia.org/wiki/Directed_graph
28 //!
29 //! ```
30 //! use std::cmp::Ordering;
31 //! use std::collections::BinaryHeap;
32 //! use std::usize;
33 //!
34 //! #[derive(Copy, Clone, Eq, PartialEq)]
35 //! struct State {
36 //!     cost: usize,
37 //!     position: usize,
38 //! }
39 //!
40 //! // The priority queue depends on `Ord`.
41 //! // Explicitly implement the trait so the queue becomes a min-heap
42 //! // instead of a max-heap.
43 //! impl Ord for State {
44 //!     fn cmp(&self, other: &State) -> Ordering {
45 //!         // Notice that the we flip the ordering here
46 //!         other.cost.cmp(&self.cost)
47 //!     }
48 //! }
49 //!
50 //! // `PartialOrd` needs to be implemented as well.
51 //! impl PartialOrd for State {
52 //!     fn partial_cmp(&self, other: &State) -> Option<Ordering> {
53 //!         Some(self.cmp(other))
54 //!     }
55 //! }
56 //!
57 //! // Each node is represented as an `usize`, for a shorter implementation.
58 //! struct Edge {
59 //!     node: usize,
60 //!     cost: usize,
61 //! }
62 //!
63 //! // Dijkstra's shortest path algorithm.
64 //!
65 //! // Start at `start` and use `dist` to track the current shortest distance
66 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
67 //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
68 //! // for a simpler implementation.
69 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> usize {
70 //!     // dist[node] = current shortest distance from `start` to `node`
71 //!     let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
72 //!
73 //!     let mut heap = BinaryHeap::new();
74 //!
75 //!     // We're at `start`, with a zero cost
76 //!     dist[start] = 0;
77 //!     heap.push(State { cost: 0, position: start });
78 //!
79 //!     // Examine the frontier with lower cost nodes first (min-heap)
80 //!     while let Some(State { cost, position }) = heap.pop() {
81 //!         // Alternatively we could have continued to find all shortest paths
82 //!         if position == goal { return cost; }
83 //!
84 //!         // Important as we may have already found a better way
85 //!         if cost > dist[position] { continue; }
86 //!
87 //!         // For each node we can reach, see if we can find a way with
88 //!         // a lower cost going through this node
89 //!         for edge in &adj_list[position] {
90 //!             let next = State { cost: cost + edge.cost, position: edge.node };
91 //!
92 //!             // If so, add it to the frontier and continue
93 //!             if next.cost < dist[next.position] {
94 //!                 heap.push(next);
95 //!                 // Relaxation, we have now found a better way
96 //!                 dist[next.position] = next.cost;
97 //!             }
98 //!         }
99 //!     }
100 //!
101 //!     // Goal not reachable
102 //!     usize::MAX
103 //! }
104 //!
105 //! fn main() {
106 //!     // This is the directed graph we're going to use.
107 //!     // The node numbers correspond to the different states,
108 //!     // and the edge weights symbolize the cost of moving
109 //!     // from one node to another.
110 //!     // Note that the edges are one-way.
111 //!     //
112 //!     //                  7
113 //!     //          +-----------------+
114 //!     //          |                 |
115 //!     //          v   1        2    |
116 //!     //          0 -----> 1 -----> 3 ---> 4
117 //!     //          |        ^        ^      ^
118 //!     //          |        | 1      |      |
119 //!     //          |        |        | 3    | 1
120 //!     //          +------> 2 -------+      |
121 //!     //           10      |               |
122 //!     //                   +---------------+
123 //!     //
124 //!     // The graph is represented as an adjacency list where each index,
125 //!     // corresponding to a node value, has a list of outgoing edges.
126 //!     // Chosen for its efficiency.
127 //!     let graph = vec![
128 //!         // Node 0
129 //!         vec![Edge { node: 2, cost: 10 },
130 //!              Edge { node: 1, cost: 1 }],
131 //!         // Node 1
132 //!         vec![Edge { node: 3, cost: 2 }],
133 //!         // Node 2
134 //!         vec![Edge { node: 1, cost: 1 },
135 //!              Edge { node: 3, cost: 3 },
136 //!              Edge { node: 4, cost: 1 }],
137 //!         // Node 3
138 //!         vec![Edge { node: 0, cost: 7 },
139 //!              Edge { node: 4, cost: 2 }],
140 //!         // Node 4
141 //!         vec![]];
142 //!
143 //!     assert_eq!(shortest_path(&graph, 0, 1), 1);
144 //!     assert_eq!(shortest_path(&graph, 0, 3), 3);
145 //!     assert_eq!(shortest_path(&graph, 3, 0), 7);
146 //!     assert_eq!(shortest_path(&graph, 0, 4), 5);
147 //!     assert_eq!(shortest_path(&graph, 4, 0), usize::MAX);
148 //! }
149 //! ```
150
151 #![allow(missing_docs)]
152 #![stable(feature = "rust1", since = "1.0.0")]
153
154 #[cfg(stage0)]
155 use core::prelude::v1::*;
156
157 use core::iter::{FromIterator};
158 use core::mem::swap;
159 use core::ptr;
160
161 use slice;
162 use vec::{self, Vec};
163
164 /// A priority queue implemented with a binary heap.
165 ///
166 /// This will be a max-heap.
167 ///
168 /// It is a logic error for an item to be modified in such a way that the
169 /// item's ordering relative to any other item, as determined by the `Ord`
170 /// trait, changes while it is in the heap. This is normally only possible
171 /// through `Cell`, `RefCell`, global state, I/O, or unsafe code.
172 #[derive(Clone)]
173 #[stable(feature = "rust1", since = "1.0.0")]
174 pub struct BinaryHeap<T> {
175     data: Vec<T>,
176 }
177
178 #[stable(feature = "rust1", since = "1.0.0")]
179 impl<T: Ord> Default for BinaryHeap<T> {
180     #[inline]
181     fn default() -> BinaryHeap<T> { BinaryHeap::new() }
182 }
183
184 impl<T: Ord> BinaryHeap<T> {
185     /// Creates an empty `BinaryHeap` as a max-heap.
186     ///
187     /// # Examples
188     ///
189     /// ```
190     /// use std::collections::BinaryHeap;
191     /// let mut heap = BinaryHeap::new();
192     /// heap.push(4);
193     /// ```
194     #[stable(feature = "rust1", since = "1.0.0")]
195     pub fn new() -> BinaryHeap<T> { BinaryHeap { data: vec![] } }
196
197     /// Creates an empty `BinaryHeap` with a specific capacity.
198     /// This preallocates enough memory for `capacity` elements,
199     /// so that the `BinaryHeap` does not have to be reallocated
200     /// until it contains at least that many values.
201     ///
202     /// # Examples
203     ///
204     /// ```
205     /// use std::collections::BinaryHeap;
206     /// let mut heap = BinaryHeap::with_capacity(10);
207     /// heap.push(4);
208     /// ```
209     #[stable(feature = "rust1", since = "1.0.0")]
210     pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
211         BinaryHeap { data: Vec::with_capacity(capacity) }
212     }
213
214     /// Creates a `BinaryHeap` from a vector. This is sometimes called
215     /// `heapifying` the vector.
216     ///
217     /// # Examples
218     ///
219     /// ```
220     /// #![feature(collections)]
221     ///
222     /// use std::collections::BinaryHeap;
223     /// let heap = BinaryHeap::from_vec(vec![9, 1, 2, 7, 3, 2]);
224     /// ```
225     pub fn from_vec(vec: Vec<T>) -> BinaryHeap<T> {
226         let mut heap = BinaryHeap { data: vec };
227         let mut n = heap.len() / 2;
228         while n > 0 {
229             n -= 1;
230             heap.sift_down(n);
231         }
232         heap
233     }
234
235     /// Returns an iterator visiting all values in the underlying vector, in
236     /// arbitrary order.
237     ///
238     /// # Examples
239     ///
240     /// ```
241     /// #![feature(collections)]
242     ///
243     /// use std::collections::BinaryHeap;
244     /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
245     ///
246     /// // Print 1, 2, 3, 4 in arbitrary order
247     /// for x in heap.iter() {
248     ///     println!("{}", x);
249     /// }
250     /// ```
251     #[stable(feature = "rust1", since = "1.0.0")]
252     pub fn iter(&self) -> Iter<T> {
253         Iter { iter: self.data.iter() }
254     }
255
256     /// Returns the greatest item in the binary heap, or `None` if it is empty.
257     ///
258     /// # Examples
259     ///
260     /// ```
261     /// use std::collections::BinaryHeap;
262     /// let mut heap = BinaryHeap::new();
263     /// assert_eq!(heap.peek(), None);
264     ///
265     /// heap.push(1);
266     /// heap.push(5);
267     /// heap.push(2);
268     /// assert_eq!(heap.peek(), Some(&5));
269     ///
270     /// ```
271     #[stable(feature = "rust1", since = "1.0.0")]
272     pub fn peek(&self) -> Option<&T> {
273         self.data.get(0)
274     }
275
276     /// Returns the number of elements the binary heap can hold without reallocating.
277     ///
278     /// # Examples
279     ///
280     /// ```
281     /// use std::collections::BinaryHeap;
282     /// let mut heap = BinaryHeap::with_capacity(100);
283     /// assert!(heap.capacity() >= 100);
284     /// heap.push(4);
285     /// ```
286     #[stable(feature = "rust1", since = "1.0.0")]
287     pub fn capacity(&self) -> usize { self.data.capacity() }
288
289     /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
290     /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
291     ///
292     /// Note that the allocator may give the collection more space than it requests. Therefore
293     /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
294     /// insertions are expected.
295     ///
296     /// # Panics
297     ///
298     /// Panics if the new capacity overflows `usize`.
299     ///
300     /// # Examples
301     ///
302     /// ```
303     /// use std::collections::BinaryHeap;
304     /// let mut heap = BinaryHeap::new();
305     /// heap.reserve_exact(100);
306     /// assert!(heap.capacity() >= 100);
307     /// heap.push(4);
308     /// ```
309     #[stable(feature = "rust1", since = "1.0.0")]
310     pub fn reserve_exact(&mut self, additional: usize) {
311         self.data.reserve_exact(additional);
312     }
313
314     /// Reserves capacity for at least `additional` more elements to be inserted in the
315     /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
316     ///
317     /// # Panics
318     ///
319     /// Panics if the new capacity overflows `usize`.
320     ///
321     /// # Examples
322     ///
323     /// ```
324     /// use std::collections::BinaryHeap;
325     /// let mut heap = BinaryHeap::new();
326     /// heap.reserve(100);
327     /// assert!(heap.capacity() >= 100);
328     /// heap.push(4);
329     /// ```
330     #[stable(feature = "rust1", since = "1.0.0")]
331     pub fn reserve(&mut self, additional: usize) {
332         self.data.reserve(additional);
333     }
334
335     /// Discards as much additional capacity as possible.
336     #[stable(feature = "rust1", since = "1.0.0")]
337     pub fn shrink_to_fit(&mut self) {
338         self.data.shrink_to_fit();
339     }
340
341     /// Removes the greatest item from the binary heap and returns it, or `None` if it
342     /// is empty.
343     ///
344     /// # Examples
345     ///
346     /// ```
347     /// #![feature(collections)]
348     ///
349     /// use std::collections::BinaryHeap;
350     /// let mut heap = BinaryHeap::from_vec(vec![1, 3]);
351     ///
352     /// assert_eq!(heap.pop(), Some(3));
353     /// assert_eq!(heap.pop(), Some(1));
354     /// assert_eq!(heap.pop(), None);
355     /// ```
356     #[stable(feature = "rust1", since = "1.0.0")]
357     pub fn pop(&mut self) -> Option<T> {
358         self.data.pop().map(|mut item| {
359             if !self.is_empty() {
360                 swap(&mut item, &mut self.data[0]);
361                 self.sift_down(0);
362             }
363             item
364         })
365     }
366
367     /// Pushes an item onto the binary heap.
368     ///
369     /// # Examples
370     ///
371     /// ```
372     /// use std::collections::BinaryHeap;
373     /// let mut heap = BinaryHeap::new();
374     /// heap.push(3);
375     /// heap.push(5);
376     /// heap.push(1);
377     ///
378     /// assert_eq!(heap.len(), 3);
379     /// assert_eq!(heap.peek(), Some(&5));
380     /// ```
381     #[stable(feature = "rust1", since = "1.0.0")]
382     pub fn push(&mut self, item: T) {
383         let old_len = self.len();
384         self.data.push(item);
385         self.sift_up(0, old_len);
386     }
387
388     /// Pushes an item onto the binary heap, then pops the greatest item off the queue in
389     /// an optimized fashion.
390     ///
391     /// # Examples
392     ///
393     /// ```
394     /// #![feature(collections)]
395     ///
396     /// use std::collections::BinaryHeap;
397     /// let mut heap = BinaryHeap::new();
398     /// heap.push(1);
399     /// heap.push(5);
400     ///
401     /// assert_eq!(heap.push_pop(3), 5);
402     /// assert_eq!(heap.push_pop(9), 9);
403     /// assert_eq!(heap.len(), 2);
404     /// assert_eq!(heap.peek(), Some(&3));
405     /// ```
406     pub fn push_pop(&mut self, mut item: T) -> T {
407         match self.data.get_mut(0) {
408             None => return item,
409             Some(top) => if *top > item {
410                 swap(&mut item, top);
411             } else {
412                 return item;
413             },
414         }
415
416         self.sift_down(0);
417         item
418     }
419
420     /// Pops the greatest item off the binary heap, then pushes an item onto the queue in
421     /// an optimized fashion. The push is done regardless of whether the binary heap
422     /// was empty.
423     ///
424     /// # Examples
425     ///
426     /// ```
427     /// #![feature(collections)]
428     ///
429     /// use std::collections::BinaryHeap;
430     /// let mut heap = BinaryHeap::new();
431     ///
432     /// assert_eq!(heap.replace(1), None);
433     /// assert_eq!(heap.replace(3), Some(1));
434     /// assert_eq!(heap.len(), 1);
435     /// assert_eq!(heap.peek(), Some(&3));
436     /// ```
437     pub fn replace(&mut self, mut item: T) -> Option<T> {
438         if !self.is_empty() {
439             swap(&mut item, &mut self.data[0]);
440             self.sift_down(0);
441             Some(item)
442         } else {
443             self.push(item);
444             None
445         }
446     }
447
448     /// Consumes the `BinaryHeap` and returns the underlying vector
449     /// in arbitrary order.
450     ///
451     /// # Examples
452     ///
453     /// ```
454     /// #![feature(collections)]
455     ///
456     /// use std::collections::BinaryHeap;
457     /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4, 5, 6, 7]);
458     /// let vec = heap.into_vec();
459     ///
460     /// // Will print in some order
461     /// for x in vec {
462     ///     println!("{}", x);
463     /// }
464     /// ```
465     pub fn into_vec(self) -> Vec<T> { self.data }
466
467     /// Consumes the `BinaryHeap` and returns a vector in sorted
468     /// (ascending) order.
469     ///
470     /// # Examples
471     ///
472     /// ```
473     /// #![feature(collections)]
474     ///
475     /// use std::collections::BinaryHeap;
476     ///
477     /// let mut heap = BinaryHeap::from_vec(vec![1, 2, 4, 5, 7]);
478     /// heap.push(6);
479     /// heap.push(3);
480     ///
481     /// let vec = heap.into_sorted_vec();
482     /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
483     /// ```
484     pub fn into_sorted_vec(mut self) -> Vec<T> {
485         let mut end = self.len();
486         while end > 1 {
487             end -= 1;
488             self.data.swap(0, end);
489             self.sift_down_range(0, end);
490         }
491         self.into_vec()
492     }
493
494     // The implementations of sift_up and sift_down use unsafe blocks in
495     // order to move an element out of the vector (leaving behind a
496     // hole), shift along the others and move the removed element back into the
497     // vector at the final location of the hole.
498     // The `Hole` type is used to represent this, and make sure
499     // the hole is filled back at the end of its scope, even on panic.
500     // Using a hole reduces the constant factor compared to using swaps,
501     // which involves twice as many moves.
502     fn sift_up(&mut self, start: usize, pos: usize) {
503         unsafe {
504             // Take out the value at `pos` and create a hole.
505             let mut hole = Hole::new(&mut self.data, pos);
506
507             while hole.pos() > start {
508                 let parent = (hole.pos() - 1) / 2;
509                 if hole.removed() <= hole.get(parent) { break }
510                 hole.move_to(parent);
511             }
512         }
513     }
514
515     fn sift_down_range(&mut self, mut pos: usize, end: usize) {
516         let start = pos;
517         unsafe {
518             let mut hole = Hole::new(&mut self.data, pos);
519             let mut child = 2 * pos + 1;
520             while child < end {
521                 let right = child + 1;
522                 if right < end && !(hole.get(child) > hole.get(right)) {
523                     child = right;
524                 }
525                 hole.move_to(child);
526                 child = 2 * hole.pos() + 1;
527             }
528
529             pos = hole.pos;
530         }
531         self.sift_up(start, pos);
532     }
533
534     fn sift_down(&mut self, pos: usize) {
535         let len = self.len();
536         self.sift_down_range(pos, len);
537     }
538
539     /// Returns the length of the binary heap.
540     #[stable(feature = "rust1", since = "1.0.0")]
541     pub fn len(&self) -> usize { self.data.len() }
542
543     /// Checks if the binary heap is empty.
544     #[stable(feature = "rust1", since = "1.0.0")]
545     pub fn is_empty(&self) -> bool { self.len() == 0 }
546
547     /// Clears the binary heap, returning an iterator over the removed elements.
548     ///
549     /// The elements are removed in arbitrary order.
550     #[inline]
551     #[unstable(feature = "drain",
552                reason = "matches collection reform specification, \
553                          waiting for dust to settle")]
554     pub fn drain(&mut self) -> Drain<T> {
555         Drain { iter: self.data.drain(..) }
556     }
557
558     /// Drops all items from the binary heap.
559     #[stable(feature = "rust1", since = "1.0.0")]
560     pub fn clear(&mut self) { self.drain(); }
561 }
562
563 /// Hole represents a hole in a slice i.e. an index without valid value
564 /// (because it was moved from or duplicated).
565 /// In drop, `Hole` will restore the slice by filling the hole
566 /// position with the value that was originally removed.
567 struct Hole<'a, T: 'a> {
568     data: &'a mut [T],
569     /// `elt` is always `Some` from new until drop.
570     elt: Option<T>,
571     pos: usize,
572 }
573
574 impl<'a, T> Hole<'a, T> {
575     /// Create a new Hole at index `pos`.
576     fn new(data: &'a mut [T], pos: usize) -> Self {
577         unsafe {
578             let elt = ptr::read(&data[pos]);
579             Hole {
580                 data: data,
581                 elt: Some(elt),
582                 pos: pos,
583             }
584         }
585     }
586
587     #[inline(always)]
588     fn pos(&self) -> usize { self.pos }
589
590     /// Return a reference to the element removed
591     #[inline(always)]
592     fn removed(&self) -> &T {
593         self.elt.as_ref().unwrap()
594     }
595
596     /// Return a reference to the element at `index`.
597     ///
598     /// Panics if the index is out of bounds.
599     ///
600     /// Unsafe because index must not equal pos.
601     #[inline(always)]
602     unsafe fn get(&self, index: usize) -> &T {
603         debug_assert!(index != self.pos);
604         &self.data[index]
605     }
606
607     /// Move hole to new location
608     ///
609     /// Unsafe because index must not equal pos.
610     #[inline(always)]
611     unsafe fn move_to(&mut self, index: usize) {
612         debug_assert!(index != self.pos);
613         let index_ptr: *const _ = &self.data[index];
614         let hole_ptr = &mut self.data[self.pos];
615         ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
616         self.pos = index;
617     }
618 }
619
620 impl<'a, T> Drop for Hole<'a, T> {
621     fn drop(&mut self) {
622         // fill the hole again
623         unsafe {
624             let pos = self.pos;
625             ptr::write(&mut self.data[pos], self.elt.take().unwrap());
626         }
627     }
628 }
629
630 /// `BinaryHeap` iterator.
631 #[stable(feature = "rust1", since = "1.0.0")]
632 pub struct Iter <'a, T: 'a> {
633     iter: slice::Iter<'a, T>,
634 }
635
636 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
637 #[stable(feature = "rust1", since = "1.0.0")]
638 impl<'a, T> Clone for Iter<'a, T> {
639     fn clone(&self) -> Iter<'a, T> {
640         Iter { iter: self.iter.clone() }
641     }
642 }
643
644 #[stable(feature = "rust1", since = "1.0.0")]
645 impl<'a, T> Iterator for Iter<'a, T> {
646     type Item = &'a T;
647
648     #[inline]
649     fn next(&mut self) -> Option<&'a T> { self.iter.next() }
650
651     #[inline]
652     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
653 }
654
655 #[stable(feature = "rust1", since = "1.0.0")]
656 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
657     #[inline]
658     fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
659 }
660
661 #[stable(feature = "rust1", since = "1.0.0")]
662 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
663
664 /// An iterator that moves out of a `BinaryHeap`.
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub struct IntoIter<T> {
667     iter: vec::IntoIter<T>,
668 }
669
670 #[stable(feature = "rust1", since = "1.0.0")]
671 impl<T> Iterator for IntoIter<T> {
672     type Item = T;
673
674     #[inline]
675     fn next(&mut self) -> Option<T> { self.iter.next() }
676
677     #[inline]
678     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
679 }
680
681 #[stable(feature = "rust1", since = "1.0.0")]
682 impl<T> DoubleEndedIterator for IntoIter<T> {
683     #[inline]
684     fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
685 }
686
687 #[stable(feature = "rust1", since = "1.0.0")]
688 impl<T> ExactSizeIterator for IntoIter<T> {}
689
690 /// An iterator that drains a `BinaryHeap`.
691 #[unstable(feature = "drain", reason = "recent addition")]
692 pub struct Drain<'a, T: 'a> {
693     iter: vec::Drain<'a, T>,
694 }
695
696 #[stable(feature = "rust1", since = "1.0.0")]
697 impl<'a, T: 'a> Iterator for Drain<'a, T> {
698     type Item = T;
699
700     #[inline]
701     fn next(&mut self) -> Option<T> { self.iter.next() }
702
703     #[inline]
704     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
705 }
706
707 #[stable(feature = "rust1", since = "1.0.0")]
708 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
709     #[inline]
710     fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
711 }
712
713 #[stable(feature = "rust1", since = "1.0.0")]
714 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
715
716 #[stable(feature = "rust1", since = "1.0.0")]
717 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
718     fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> BinaryHeap<T> {
719         BinaryHeap::from_vec(iter.into_iter().collect())
720     }
721 }
722
723 #[stable(feature = "rust1", since = "1.0.0")]
724 impl<T: Ord> IntoIterator for BinaryHeap<T> {
725     type Item = T;
726     type IntoIter = IntoIter<T>;
727
728     /// Creates a consuming iterator, that is, one that moves each value out of
729     /// the binary heap in arbitrary order. The binary heap cannot be used
730     /// after calling this.
731     ///
732     /// # Examples
733     ///
734     /// ```
735     /// #![feature(collections)]
736     ///
737     /// use std::collections::BinaryHeap;
738     /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
739     ///
740     /// // Print 1, 2, 3, 4 in arbitrary order
741     /// for x in heap.into_iter() {
742     ///     // x has type i32, not &i32
743     ///     println!("{}", x);
744     /// }
745     /// ```
746     fn into_iter(self) -> IntoIter<T> {
747         IntoIter { iter: self.data.into_iter() }
748     }
749 }
750
751 #[stable(feature = "rust1", since = "1.0.0")]
752 impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord {
753     type Item = &'a T;
754     type IntoIter = Iter<'a, T>;
755
756     fn into_iter(self) -> Iter<'a, T> {
757         self.iter()
758     }
759 }
760
761 #[stable(feature = "rust1", since = "1.0.0")]
762 impl<T: Ord> Extend<T> for BinaryHeap<T> {
763     fn extend<I: IntoIterator<Item=T>>(&mut self, iterable: I) {
764         let iter = iterable.into_iter();
765         let (lower, _) = iter.size_hint();
766
767         self.reserve(lower);
768
769         for elem in iter {
770             self.push(elem);
771         }
772     }
773 }
774
775 #[stable(feature = "extend_ref", since = "1.2.0")]
776 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
777     fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) {
778         self.extend(iter.into_iter().cloned());
779     }
780 }