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