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