]> git.proxmox.com Git - rustc.git/blame - src/libcollections/binary_heap.rs
New upstream version 1.12.0+dfsg1
[rustc.git] / src / libcollections / binary_heap.rs
CommitLineData
1a4d82fc
JJ
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//!
62682a34
SL
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.
1a4d82fc
JJ
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;
85aaf69f 32//! use std::usize;
1a4d82fc 33//!
c34b1796 34//! #[derive(Copy, Clone, Eq, PartialEq)]
1a4d82fc 35//! struct State {
85aaf69f
SL
36//! cost: usize,
37//! position: usize,
1a4d82fc
JJ
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//!
85aaf69f 57//! // Each node is represented as an `usize`, for a shorter implementation.
1a4d82fc 58//! struct Edge {
85aaf69f
SL
59//! node: usize,
60//! cost: usize,
1a4d82fc
JJ
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
85aaf69f 67//! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
1a4d82fc 68//! // for a simpler implementation.
9cc50fc6 69//! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
1a4d82fc 70//! // dist[node] = current shortest distance from `start` to `node`
85aaf69f 71//! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
1a4d82fc
JJ
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
9cc50fc6 82//! if position == goal { return Some(cost); }
1a4d82fc
JJ
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
62682a34 89//! for edge in &adj_list[position] {
1a4d82fc
JJ
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
9cc50fc6 102//! None
1a4d82fc
JJ
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//! // | |
e9174d1e 115//! // v 1 2 | 2
1a4d82fc
JJ
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//!
9cc50fc6
SL
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);
1a4d82fc
JJ
148//! }
149//! ```
150
151#![allow(missing_docs)]
85aaf69f 152#![stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 153
3157f602 154use core::ops::{Drop, Deref, DerefMut};
92a42be0 155use core::iter::FromIterator;
d9579d0f 156use core::mem::swap;
a7813a04 157use core::mem::size_of;
1a4d82fc 158use core::ptr;
e9174d1e 159use core::fmt;
1a4d82fc
JJ
160
161use slice;
162use vec::{self, Vec};
163
a7813a04
XL
164use super::SpecExtend;
165
1a4d82fc
JJ
166/// A priority queue implemented with a binary heap.
167///
168/// This will be a max-heap.
c34b1796
AL
169///
170/// It is a logic error for an item to be modified in such a way that the
171/// item's ordering relative to any other item, as determined by the `Ord`
172/// trait, changes while it is in the heap. This is normally only possible
173/// through `Cell`, `RefCell`, global state, I/O, or unsafe code.
54a0048b
SL
174///
175/// # Examples
176///
177/// ```
178/// use std::collections::BinaryHeap;
179///
180/// // Type inference lets us omit an explicit type signature (which
181/// // would be `BinaryHeap<i32>` in this example).
182/// let mut heap = BinaryHeap::new();
183///
184/// // We can use peek to look at the next item in the heap. In this case,
185/// // there's no items in there yet so we get None.
186/// assert_eq!(heap.peek(), None);
187///
188/// // Let's add some scores...
189/// heap.push(1);
190/// heap.push(5);
191/// heap.push(2);
192///
193/// // Now peek shows the most important item in the heap.
194/// assert_eq!(heap.peek(), Some(&5));
195///
196/// // We can check the length of a heap.
197/// assert_eq!(heap.len(), 3);
198///
199/// // We can iterate over the items in the heap, although they are returned in
200/// // a random order.
201/// for x in &heap {
202/// println!("{}", x);
203/// }
204///
205/// // If we instead pop these scores, they should come back in order.
206/// assert_eq!(heap.pop(), Some(5));
207/// assert_eq!(heap.pop(), Some(2));
208/// assert_eq!(heap.pop(), Some(1));
209/// assert_eq!(heap.pop(), None);
210///
211/// // We can clear the heap of any remaining items.
212/// heap.clear();
213///
214/// // The heap should now be empty.
215/// assert!(heap.is_empty())
216/// ```
85aaf69f 217#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
218pub struct BinaryHeap<T> {
219 data: Vec<T>,
220}
221
3157f602
XL
222/// A container object that represents the result of the [`peek_mut()`] method
223/// on `BinaryHeap`. See its documentation for details.
224///
225/// [`peek_mut()`]: struct.BinaryHeap.html#method.peek_mut
5bcae85e 226#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
3157f602
XL
227pub struct PeekMut<'a, T: 'a + Ord> {
228 heap: &'a mut BinaryHeap<T>
229}
230
5bcae85e 231#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
3157f602
XL
232impl<'a, T: Ord> Drop for PeekMut<'a, T> {
233 fn drop(&mut self) {
234 self.heap.sift_down(0);
235 }
236}
237
5bcae85e 238#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
3157f602
XL
239impl<'a, T: Ord> Deref for PeekMut<'a, T> {
240 type Target = T;
241 fn deref(&self) -> &T {
242 &self.heap.data[0]
243 }
244}
245
5bcae85e 246#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
3157f602
XL
247impl<'a, T: Ord> DerefMut for PeekMut<'a, T> {
248 fn deref_mut(&mut self) -> &mut T {
249 &mut self.heap.data[0]
250 }
251}
252
b039eaaf
SL
253#[stable(feature = "rust1", since = "1.0.0")]
254impl<T: Clone> Clone for BinaryHeap<T> {
255 fn clone(&self) -> Self {
256 BinaryHeap { data: self.data.clone() }
257 }
258
259 fn clone_from(&mut self, source: &Self) {
260 self.data.clone_from(&source.data);
261 }
262}
263
85aaf69f 264#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
265impl<T: Ord> Default for BinaryHeap<T> {
266 #[inline]
92a42be0
SL
267 fn default() -> BinaryHeap<T> {
268 BinaryHeap::new()
269 }
1a4d82fc
JJ
270}
271
e9174d1e
SL
272#[stable(feature = "binaryheap_debug", since = "1.4.0")]
273impl<T: fmt::Debug + Ord> fmt::Debug for BinaryHeap<T> {
274 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
275 f.debug_list().entries(self.iter()).finish()
276 }
277}
278
1a4d82fc
JJ
279impl<T: Ord> BinaryHeap<T> {
280 /// Creates an empty `BinaryHeap` as a max-heap.
281 ///
282 /// # Examples
283 ///
54a0048b
SL
284 /// Basic usage:
285 ///
1a4d82fc
JJ
286 /// ```
287 /// use std::collections::BinaryHeap;
288 /// let mut heap = BinaryHeap::new();
85aaf69f 289 /// heap.push(4);
1a4d82fc 290 /// ```
85aaf69f 291 #[stable(feature = "rust1", since = "1.0.0")]
92a42be0
SL
292 pub fn new() -> BinaryHeap<T> {
293 BinaryHeap { data: vec![] }
294 }
1a4d82fc
JJ
295
296 /// Creates an empty `BinaryHeap` with a specific capacity.
297 /// This preallocates enough memory for `capacity` elements,
298 /// so that the `BinaryHeap` does not have to be reallocated
299 /// until it contains at least that many values.
300 ///
301 /// # Examples
302 ///
54a0048b
SL
303 /// Basic usage:
304 ///
1a4d82fc
JJ
305 /// ```
306 /// use std::collections::BinaryHeap;
307 /// let mut heap = BinaryHeap::with_capacity(10);
85aaf69f 308 /// heap.push(4);
1a4d82fc 309 /// ```
85aaf69f
SL
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
1a4d82fc
JJ
312 BinaryHeap { data: Vec::with_capacity(capacity) }
313 }
314
1a4d82fc
JJ
315 /// Returns an iterator visiting all values in the underlying vector, in
316 /// arbitrary order.
317 ///
318 /// # Examples
319 ///
54a0048b
SL
320 /// Basic usage:
321 ///
1a4d82fc
JJ
322 /// ```
323 /// use std::collections::BinaryHeap;
b039eaaf 324 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1a4d82fc
JJ
325 ///
326 /// // Print 1, 2, 3, 4 in arbitrary order
327 /// for x in heap.iter() {
328 /// println!("{}", x);
329 /// }
330 /// ```
85aaf69f 331 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
332 pub fn iter(&self) -> Iter<T> {
333 Iter { iter: self.data.iter() }
334 }
335
1a4d82fc
JJ
336 /// Returns the greatest item in the binary heap, or `None` if it is empty.
337 ///
338 /// # Examples
339 ///
54a0048b
SL
340 /// Basic usage:
341 ///
1a4d82fc
JJ
342 /// ```
343 /// use std::collections::BinaryHeap;
344 /// let mut heap = BinaryHeap::new();
345 /// assert_eq!(heap.peek(), None);
346 ///
85aaf69f 347 /// heap.push(1);
1a4d82fc
JJ
348 /// heap.push(5);
349 /// heap.push(2);
350 /// assert_eq!(heap.peek(), Some(&5));
351 ///
352 /// ```
85aaf69f 353 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
354 pub fn peek(&self) -> Option<&T> {
355 self.data.get(0)
356 }
357
3157f602
XL
358 /// Returns a mutable reference to the greatest item in the binary heap, or
359 /// `None` if it is empty.
360 ///
361 /// Note: If the `PeekMut` value is leaked, the heap may be in an
362 /// inconsistent state.
363 ///
364 /// # Examples
365 ///
366 /// Basic usage:
367 ///
368 /// ```
3157f602
XL
369 /// use std::collections::BinaryHeap;
370 /// let mut heap = BinaryHeap::new();
371 /// assert!(heap.peek_mut().is_none());
372 ///
373 /// heap.push(1);
374 /// heap.push(5);
375 /// heap.push(2);
376 /// {
377 /// let mut val = heap.peek_mut().unwrap();
378 /// *val = 0;
379 /// }
380 /// assert_eq!(heap.peek(), Some(&2));
381 /// ```
5bcae85e 382 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
3157f602
XL
383 pub fn peek_mut(&mut self) -> Option<PeekMut<T>> {
384 if self.is_empty() {
385 None
386 } else {
387 Some(PeekMut {
388 heap: self
389 })
390 }
391 }
392
1a4d82fc
JJ
393 /// Returns the number of elements the binary heap can hold without reallocating.
394 ///
395 /// # Examples
396 ///
54a0048b
SL
397 /// Basic usage:
398 ///
1a4d82fc
JJ
399 /// ```
400 /// use std::collections::BinaryHeap;
401 /// let mut heap = BinaryHeap::with_capacity(100);
402 /// assert!(heap.capacity() >= 100);
85aaf69f 403 /// heap.push(4);
1a4d82fc 404 /// ```
85aaf69f 405 #[stable(feature = "rust1", since = "1.0.0")]
92a42be0
SL
406 pub fn capacity(&self) -> usize {
407 self.data.capacity()
408 }
1a4d82fc
JJ
409
410 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
411 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
412 ///
413 /// Note that the allocator may give the collection more space than it requests. Therefore
414 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
415 /// insertions are expected.
416 ///
417 /// # Panics
418 ///
85aaf69f 419 /// Panics if the new capacity overflows `usize`.
1a4d82fc
JJ
420 ///
421 /// # Examples
422 ///
54a0048b
SL
423 /// Basic usage:
424 ///
1a4d82fc
JJ
425 /// ```
426 /// use std::collections::BinaryHeap;
427 /// let mut heap = BinaryHeap::new();
428 /// heap.reserve_exact(100);
429 /// assert!(heap.capacity() >= 100);
85aaf69f 430 /// heap.push(4);
1a4d82fc 431 /// ```
85aaf69f
SL
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn reserve_exact(&mut self, additional: usize) {
1a4d82fc
JJ
434 self.data.reserve_exact(additional);
435 }
436
437 /// Reserves capacity for at least `additional` more elements to be inserted in the
438 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
439 ///
440 /// # Panics
441 ///
85aaf69f 442 /// Panics if the new capacity overflows `usize`.
1a4d82fc
JJ
443 ///
444 /// # Examples
445 ///
54a0048b
SL
446 /// Basic usage:
447 ///
1a4d82fc
JJ
448 /// ```
449 /// use std::collections::BinaryHeap;
450 /// let mut heap = BinaryHeap::new();
451 /// heap.reserve(100);
452 /// assert!(heap.capacity() >= 100);
85aaf69f 453 /// heap.push(4);
1a4d82fc 454 /// ```
85aaf69f
SL
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn reserve(&mut self, additional: usize) {
1a4d82fc
JJ
457 self.data.reserve(additional);
458 }
459
460 /// Discards as much additional capacity as possible.
54a0048b
SL
461 ///
462 /// # Examples
463 ///
464 /// Basic usage:
465 ///
466 /// ```
467 /// use std::collections::BinaryHeap;
468 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
469 ///
470 /// assert!(heap.capacity() >= 100);
471 /// heap.shrink_to_fit();
472 /// assert!(heap.capacity() == 0);
473 /// ```
85aaf69f 474 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
475 pub fn shrink_to_fit(&mut self) {
476 self.data.shrink_to_fit();
477 }
478
479 /// Removes the greatest item from the binary heap and returns it, or `None` if it
480 /// is empty.
481 ///
482 /// # Examples
483 ///
54a0048b
SL
484 /// Basic usage:
485 ///
1a4d82fc
JJ
486 /// ```
487 /// use std::collections::BinaryHeap;
b039eaaf 488 /// let mut heap = BinaryHeap::from(vec![1, 3]);
1a4d82fc
JJ
489 ///
490 /// assert_eq!(heap.pop(), Some(3));
491 /// assert_eq!(heap.pop(), Some(1));
492 /// assert_eq!(heap.pop(), None);
493 /// ```
85aaf69f 494 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
495 pub fn pop(&mut self) -> Option<T> {
496 self.data.pop().map(|mut item| {
497 if !self.is_empty() {
498 swap(&mut item, &mut self.data[0]);
9cc50fc6 499 self.sift_down_to_bottom(0);
1a4d82fc
JJ
500 }
501 item
502 })
503 }
504
505 /// Pushes an item onto the binary heap.
506 ///
507 /// # Examples
508 ///
54a0048b
SL
509 /// Basic usage:
510 ///
1a4d82fc
JJ
511 /// ```
512 /// use std::collections::BinaryHeap;
513 /// let mut heap = BinaryHeap::new();
85aaf69f 514 /// heap.push(3);
1a4d82fc
JJ
515 /// heap.push(5);
516 /// heap.push(1);
517 ///
518 /// assert_eq!(heap.len(), 3);
519 /// assert_eq!(heap.peek(), Some(&5));
520 /// ```
85aaf69f 521 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
522 pub fn push(&mut self, item: T) {
523 let old_len = self.len();
524 self.data.push(item);
525 self.sift_up(0, old_len);
526 }
527
528 /// Pushes an item onto the binary heap, then pops the greatest item off the queue in
529 /// an optimized fashion.
530 ///
531 /// # Examples
532 ///
54a0048b
SL
533 /// Basic usage:
534 ///
1a4d82fc 535 /// ```
e9174d1e 536 /// #![feature(binary_heap_extras)]
c1a9b12d 537 ///
1a4d82fc
JJ
538 /// use std::collections::BinaryHeap;
539 /// let mut heap = BinaryHeap::new();
85aaf69f 540 /// heap.push(1);
1a4d82fc
JJ
541 /// heap.push(5);
542 ///
543 /// assert_eq!(heap.push_pop(3), 5);
544 /// assert_eq!(heap.push_pop(9), 9);
545 /// assert_eq!(heap.len(), 2);
546 /// assert_eq!(heap.peek(), Some(&3));
547 /// ```
e9174d1e
SL
548 #[unstable(feature = "binary_heap_extras",
549 reason = "needs to be audited",
550 issue = "28147")]
1a4d82fc
JJ
551 pub fn push_pop(&mut self, mut item: T) -> T {
552 match self.data.get_mut(0) {
553 None => return item,
92a42be0
SL
554 Some(top) => {
555 if *top > item {
556 swap(&mut item, top);
557 } else {
558 return item;
559 }
560 }
1a4d82fc
JJ
561 }
562
563 self.sift_down(0);
564 item
565 }
566
567 /// Pops the greatest item off the binary heap, then pushes an item onto the queue in
568 /// an optimized fashion. The push is done regardless of whether the binary heap
569 /// was empty.
570 ///
571 /// # Examples
572 ///
54a0048b
SL
573 /// Basic usage:
574 ///
1a4d82fc 575 /// ```
e9174d1e 576 /// #![feature(binary_heap_extras)]
c1a9b12d 577 ///
1a4d82fc
JJ
578 /// use std::collections::BinaryHeap;
579 /// let mut heap = BinaryHeap::new();
580 ///
85aaf69f 581 /// assert_eq!(heap.replace(1), None);
1a4d82fc
JJ
582 /// assert_eq!(heap.replace(3), Some(1));
583 /// assert_eq!(heap.len(), 1);
584 /// assert_eq!(heap.peek(), Some(&3));
585 /// ```
e9174d1e
SL
586 #[unstable(feature = "binary_heap_extras",
587 reason = "needs to be audited",
588 issue = "28147")]
1a4d82fc
JJ
589 pub fn replace(&mut self, mut item: T) -> Option<T> {
590 if !self.is_empty() {
591 swap(&mut item, &mut self.data[0]);
592 self.sift_down(0);
593 Some(item)
594 } else {
595 self.push(item);
596 None
597 }
598 }
599
600 /// Consumes the `BinaryHeap` and returns the underlying vector
601 /// in arbitrary order.
602 ///
603 /// # Examples
604 ///
54a0048b
SL
605 /// Basic usage:
606 ///
1a4d82fc
JJ
607 /// ```
608 /// use std::collections::BinaryHeap;
b039eaaf 609 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
1a4d82fc
JJ
610 /// let vec = heap.into_vec();
611 ///
612 /// // Will print in some order
62682a34 613 /// for x in vec {
1a4d82fc
JJ
614 /// println!("{}", x);
615 /// }
616 /// ```
b039eaaf
SL
617 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
618 pub fn into_vec(self) -> Vec<T> {
619 self.into()
620 }
1a4d82fc
JJ
621
622 /// Consumes the `BinaryHeap` and returns a vector in sorted
623 /// (ascending) order.
624 ///
625 /// # Examples
626 ///
54a0048b
SL
627 /// Basic usage:
628 ///
1a4d82fc
JJ
629 /// ```
630 /// use std::collections::BinaryHeap;
631 ///
b039eaaf 632 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
1a4d82fc
JJ
633 /// heap.push(6);
634 /// heap.push(3);
635 ///
636 /// let vec = heap.into_sorted_vec();
c34b1796 637 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
1a4d82fc 638 /// ```
b039eaaf 639 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1a4d82fc
JJ
640 pub fn into_sorted_vec(mut self) -> Vec<T> {
641 let mut end = self.len();
642 while end > 1 {
643 end -= 1;
644 self.data.swap(0, end);
645 self.sift_down_range(0, end);
646 }
647 self.into_vec()
648 }
649
650 // The implementations of sift_up and sift_down use unsafe blocks in
651 // order to move an element out of the vector (leaving behind a
d9579d0f
AL
652 // hole), shift along the others and move the removed element back into the
653 // vector at the final location of the hole.
654 // The `Hole` type is used to represent this, and make sure
655 // the hole is filled back at the end of its scope, even on panic.
656 // Using a hole reduces the constant factor compared to using swaps,
657 // which involves twice as many moves.
658 fn sift_up(&mut self, start: usize, pos: usize) {
1a4d82fc 659 unsafe {
d9579d0f
AL
660 // Take out the value at `pos` and create a hole.
661 let mut hole = Hole::new(&mut self.data, pos);
1a4d82fc 662
d9579d0f
AL
663 while hole.pos() > start {
664 let parent = (hole.pos() - 1) / 2;
92a42be0
SL
665 if hole.element() <= hole.get(parent) {
666 break;
667 }
d9579d0f 668 hole.move_to(parent);
1a4d82fc 669 }
1a4d82fc
JJ
670 }
671 }
672
92a42be0
SL
673 /// Take an element at `pos` and move it down the heap,
674 /// while its children are larger.
675 fn sift_down_range(&mut self, pos: usize, end: usize) {
1a4d82fc 676 unsafe {
d9579d0f 677 let mut hole = Hole::new(&mut self.data, pos);
1a4d82fc
JJ
678 let mut child = 2 * pos + 1;
679 while child < end {
680 let right = child + 1;
92a42be0 681 // compare with the greater of the two children
d9579d0f 682 if right < end && !(hole.get(child) > hole.get(right)) {
1a4d82fc
JJ
683 child = right;
684 }
92a42be0
SL
685 // if we are already in order, stop.
686 if hole.element() >= hole.get(child) {
687 break;
688 }
d9579d0f
AL
689 hole.move_to(child);
690 child = 2 * hole.pos() + 1;
1a4d82fc 691 }
1a4d82fc
JJ
692 }
693 }
694
85aaf69f 695 fn sift_down(&mut self, pos: usize) {
1a4d82fc
JJ
696 let len = self.len();
697 self.sift_down_range(pos, len);
698 }
699
9cc50fc6
SL
700 /// Take an element at `pos` and move it all the way down the heap,
701 /// then sift it up to its position.
702 ///
703 /// Note: This is faster when the element is known to be large / should
704 /// be closer to the bottom.
705 fn sift_down_to_bottom(&mut self, mut pos: usize) {
706 let end = self.len();
707 let start = pos;
708 unsafe {
709 let mut hole = Hole::new(&mut self.data, pos);
710 let mut child = 2 * pos + 1;
711 while child < end {
712 let right = child + 1;
713 // compare with the greater of the two children
714 if right < end && !(hole.get(child) > hole.get(right)) {
715 child = right;
716 }
717 hole.move_to(child);
718 child = 2 * hole.pos() + 1;
719 }
720 pos = hole.pos;
721 }
722 self.sift_up(start, pos);
723 }
724
1a4d82fc 725 /// Returns the length of the binary heap.
54a0048b
SL
726 ///
727 /// # Examples
728 ///
729 /// Basic usage:
730 ///
731 /// ```
732 /// use std::collections::BinaryHeap;
733 /// let heap = BinaryHeap::from(vec![1, 3]);
734 ///
735 /// assert_eq!(heap.len(), 2);
736 /// ```
85aaf69f 737 #[stable(feature = "rust1", since = "1.0.0")]
92a42be0
SL
738 pub fn len(&self) -> usize {
739 self.data.len()
740 }
1a4d82fc
JJ
741
742 /// Checks if the binary heap is empty.
54a0048b
SL
743 ///
744 /// # Examples
745 ///
746 /// Basic usage:
747 ///
748 /// ```
749 /// use std::collections::BinaryHeap;
750 /// let mut heap = BinaryHeap::new();
751 ///
752 /// assert!(heap.is_empty());
753 ///
754 /// heap.push(3);
755 /// heap.push(5);
756 /// heap.push(1);
757 ///
758 /// assert!(!heap.is_empty());
759 /// ```
85aaf69f 760 #[stable(feature = "rust1", since = "1.0.0")]
92a42be0
SL
761 pub fn is_empty(&self) -> bool {
762 self.len() == 0
763 }
1a4d82fc
JJ
764
765 /// Clears the binary heap, returning an iterator over the removed elements.
c34b1796
AL
766 ///
767 /// The elements are removed in arbitrary order.
54a0048b
SL
768 ///
769 /// # Examples
770 ///
771 /// Basic usage:
772 ///
773 /// ```
774 /// use std::collections::BinaryHeap;
775 /// let mut heap = BinaryHeap::from(vec![1, 3]);
776 ///
777 /// assert!(!heap.is_empty());
778 ///
779 /// for x in heap.drain() {
780 /// println!("{}", x);
781 /// }
782 ///
783 /// assert!(heap.is_empty());
784 /// ```
1a4d82fc 785 #[inline]
92a42be0 786 #[stable(feature = "drain", since = "1.6.0")]
1a4d82fc 787 pub fn drain(&mut self) -> Drain<T> {
d9579d0f 788 Drain { iter: self.data.drain(..) }
1a4d82fc
JJ
789 }
790
791 /// Drops all items from the binary heap.
54a0048b
SL
792 ///
793 /// # Examples
794 ///
795 /// Basic usage:
796 ///
797 /// ```
798 /// use std::collections::BinaryHeap;
799 /// let mut heap = BinaryHeap::from(vec![1, 3]);
800 ///
801 /// assert!(!heap.is_empty());
802 ///
803 /// heap.clear();
804 ///
805 /// assert!(heap.is_empty());
806 /// ```
85aaf69f 807 #[stable(feature = "rust1", since = "1.0.0")]
92a42be0
SL
808 pub fn clear(&mut self) {
809 self.drain();
810 }
a7813a04
XL
811
812 fn rebuild(&mut self) {
813 let mut n = self.len() / 2;
814 while n > 0 {
815 n -= 1;
816 self.sift_down(n);
817 }
818 }
819
820 /// Moves all the elements of `other` into `self`, leaving `other` empty.
821 ///
822 /// # Examples
823 ///
824 /// Basic usage:
825 ///
826 /// ```
a7813a04
XL
827 /// use std::collections::BinaryHeap;
828 ///
829 /// let v = vec![-10, 1, 2, 3, 3];
830 /// let mut a = BinaryHeap::from(v);
831 ///
832 /// let v = vec![-20, 5, 43];
833 /// let mut b = BinaryHeap::from(v);
834 ///
835 /// a.append(&mut b);
836 ///
837 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
838 /// assert!(b.is_empty());
839 /// ```
3157f602 840 #[stable(feature = "binary_heap_append", since = "1.11.0")]
a7813a04
XL
841 pub fn append(&mut self, other: &mut Self) {
842 if self.len() < other.len() {
843 swap(self, other);
844 }
845
846 if other.is_empty() {
847 return;
848 }
849
850 #[inline(always)]
851 fn log2_fast(x: usize) -> usize {
852 8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
853 }
854
855 // `rebuild` takes O(len1 + len2) operations
856 // and about 2 * (len1 + len2) comparisons in the worst case
857 // while `extend` takes O(len2 * log_2(len1)) operations
858 // and about 1 * len2 * log_2(len1) comparisons in the worst case,
859 // assuming len1 >= len2.
860 #[inline]
861 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
862 2 * (len1 + len2) < len2 * log2_fast(len1)
863 }
864
865 if better_to_rebuild(self.len(), other.len()) {
866 self.data.append(&mut other.data);
867 self.rebuild();
868 } else {
869 self.extend(other.drain());
870 }
871 }
1a4d82fc
JJ
872}
873
d9579d0f
AL
874/// Hole represents a hole in a slice i.e. an index without valid value
875/// (because it was moved from or duplicated).
876/// In drop, `Hole` will restore the slice by filling the hole
877/// position with the value that was originally removed.
878struct Hole<'a, T: 'a> {
879 data: &'a mut [T],
880 /// `elt` is always `Some` from new until drop.
881 elt: Option<T>,
882 pos: usize,
883}
884
885impl<'a, T> Hole<'a, T> {
886 /// Create a new Hole at index `pos`.
887 fn new(data: &'a mut [T], pos: usize) -> Self {
888 unsafe {
889 let elt = ptr::read(&data[pos]);
890 Hole {
891 data: data,
892 elt: Some(elt),
893 pos: pos,
894 }
895 }
896 }
897
898 #[inline(always)]
92a42be0
SL
899 fn pos(&self) -> usize {
900 self.pos
901 }
d9579d0f
AL
902
903 /// Return a reference to the element removed
904 #[inline(always)]
92a42be0 905 fn element(&self) -> &T {
d9579d0f
AL
906 self.elt.as_ref().unwrap()
907 }
908
909 /// Return a reference to the element at `index`.
910 ///
911 /// Panics if the index is out of bounds.
912 ///
913 /// Unsafe because index must not equal pos.
914 #[inline(always)]
915 unsafe fn get(&self, index: usize) -> &T {
916 debug_assert!(index != self.pos);
917 &self.data[index]
918 }
919
920 /// Move hole to new location
921 ///
922 /// Unsafe because index must not equal pos.
923 #[inline(always)]
924 unsafe fn move_to(&mut self, index: usize) {
925 debug_assert!(index != self.pos);
926 let index_ptr: *const _ = &self.data[index];
927 let hole_ptr = &mut self.data[self.pos];
928 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
929 self.pos = index;
930 }
931}
932
933impl<'a, T> Drop for Hole<'a, T> {
934 fn drop(&mut self) {
935 // fill the hole again
936 unsafe {
937 let pos = self.pos;
938 ptr::write(&mut self.data[pos], self.elt.take().unwrap());
939 }
940 }
941}
942
1a4d82fc 943/// `BinaryHeap` iterator.
85aaf69f 944#[stable(feature = "rust1", since = "1.0.0")]
92a42be0 945pub struct Iter<'a, T: 'a> {
1a4d82fc
JJ
946 iter: slice::Iter<'a, T>,
947}
948
949// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
85aaf69f 950#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
951impl<'a, T> Clone for Iter<'a, T> {
952 fn clone(&self) -> Iter<'a, T> {
953 Iter { iter: self.iter.clone() }
954 }
955}
956
85aaf69f 957#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
958impl<'a, T> Iterator for Iter<'a, T> {
959 type Item = &'a T;
960
961 #[inline]
92a42be0
SL
962 fn next(&mut self) -> Option<&'a T> {
963 self.iter.next()
964 }
1a4d82fc
JJ
965
966 #[inline]
92a42be0
SL
967 fn size_hint(&self) -> (usize, Option<usize>) {
968 self.iter.size_hint()
969 }
1a4d82fc
JJ
970}
971
85aaf69f 972#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
973impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
974 #[inline]
92a42be0
SL
975 fn next_back(&mut self) -> Option<&'a T> {
976 self.iter.next_back()
977 }
1a4d82fc
JJ
978}
979
85aaf69f 980#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
981impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
982
983/// An iterator that moves out of a `BinaryHeap`.
85aaf69f 984#[stable(feature = "rust1", since = "1.0.0")]
a7813a04 985#[derive(Clone)]
1a4d82fc
JJ
986pub struct IntoIter<T> {
987 iter: vec::IntoIter<T>,
988}
989
85aaf69f 990#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
991impl<T> Iterator for IntoIter<T> {
992 type Item = T;
993
994 #[inline]
92a42be0
SL
995 fn next(&mut self) -> Option<T> {
996 self.iter.next()
997 }
1a4d82fc
JJ
998
999 #[inline]
92a42be0
SL
1000 fn size_hint(&self) -> (usize, Option<usize>) {
1001 self.iter.size_hint()
1002 }
1a4d82fc
JJ
1003}
1004
85aaf69f 1005#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1006impl<T> DoubleEndedIterator for IntoIter<T> {
1007 #[inline]
92a42be0
SL
1008 fn next_back(&mut self) -> Option<T> {
1009 self.iter.next_back()
1010 }
1a4d82fc
JJ
1011}
1012
85aaf69f 1013#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1014impl<T> ExactSizeIterator for IntoIter<T> {}
1015
1016/// An iterator that drains a `BinaryHeap`.
92a42be0 1017#[stable(feature = "drain", since = "1.6.0")]
1a4d82fc
JJ
1018pub struct Drain<'a, T: 'a> {
1019 iter: vec::Drain<'a, T>,
1020}
1021
85aaf69f 1022#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1023impl<'a, T: 'a> Iterator for Drain<'a, T> {
1024 type Item = T;
1025
1026 #[inline]
92a42be0
SL
1027 fn next(&mut self) -> Option<T> {
1028 self.iter.next()
1029 }
1a4d82fc
JJ
1030
1031 #[inline]
92a42be0
SL
1032 fn size_hint(&self) -> (usize, Option<usize>) {
1033 self.iter.size_hint()
1034 }
1a4d82fc
JJ
1035}
1036
85aaf69f 1037#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1038impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1039 #[inline]
92a42be0
SL
1040 fn next_back(&mut self) -> Option<T> {
1041 self.iter.next_back()
1042 }
1a4d82fc
JJ
1043}
1044
85aaf69f 1045#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1046impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
1047
92a42be0 1048#[stable(feature = "rust1", since = "1.0.0")]
b039eaaf
SL
1049impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1050 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1051 let mut heap = BinaryHeap { data: vec };
a7813a04 1052 heap.rebuild();
b039eaaf
SL
1053 heap
1054 }
1055}
1056
92a42be0 1057#[stable(feature = "rust1", since = "1.0.0")]
b039eaaf
SL
1058impl<T> From<BinaryHeap<T>> for Vec<T> {
1059 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1060 heap.data
1061 }
1062}
1063
85aaf69f 1064#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 1065impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
92a42be0 1066 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
b039eaaf 1067 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
85aaf69f
SL
1068 }
1069}
1070
1071#[stable(feature = "rust1", since = "1.0.0")]
1072impl<T: Ord> IntoIterator for BinaryHeap<T> {
1073 type Item = T;
1074 type IntoIter = IntoIter<T>;
1075
9346a6ac
AL
1076 /// Creates a consuming iterator, that is, one that moves each value out of
1077 /// the binary heap in arbitrary order. The binary heap cannot be used
1078 /// after calling this.
1079 ///
1080 /// # Examples
1081 ///
54a0048b
SL
1082 /// Basic usage:
1083 ///
9346a6ac 1084 /// ```
9346a6ac 1085 /// use std::collections::BinaryHeap;
b039eaaf 1086 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
9346a6ac
AL
1087 ///
1088 /// // Print 1, 2, 3, 4 in arbitrary order
1089 /// for x in heap.into_iter() {
1090 /// // x has type i32, not &i32
1091 /// println!("{}", x);
1092 /// }
1093 /// ```
85aaf69f 1094 fn into_iter(self) -> IntoIter<T> {
9346a6ac 1095 IntoIter { iter: self.data.into_iter() }
85aaf69f
SL
1096 }
1097}
1098
1099#[stable(feature = "rust1", since = "1.0.0")]
1100impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord {
1101 type Item = &'a T;
1102 type IntoIter = Iter<'a, T>;
1103
1104 fn into_iter(self) -> Iter<'a, T> {
1105 self.iter()
1a4d82fc
JJ
1106 }
1107}
1108
85aaf69f 1109#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 1110impl<T: Ord> Extend<T> for BinaryHeap<T> {
a7813a04 1111 #[inline]
54a0048b 1112 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
a7813a04
XL
1113 <Self as SpecExtend<I>>::spec_extend(self, iter);
1114 }
1115}
1116
1117impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1118 default fn spec_extend(&mut self, iter: I) {
1119 self.extend_desugared(iter.into_iter());
1120 }
1121}
1122
1123impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1124 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1125 self.append(other);
1126 }
1127}
1128
1129impl<T: Ord> BinaryHeap<T> {
1130 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
54a0048b
SL
1131 let iterator = iter.into_iter();
1132 let (lower, _) = iterator.size_hint();
1a4d82fc
JJ
1133
1134 self.reserve(lower);
1135
54a0048b 1136 for elem in iterator {
1a4d82fc
JJ
1137 self.push(elem);
1138 }
1139 }
1140}
62682a34
SL
1141
1142#[stable(feature = "extend_ref", since = "1.2.0")]
1143impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
92a42be0 1144 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
62682a34
SL
1145 self.extend(iter.into_iter().cloned());
1146 }
1147}