]> git.proxmox.com Git - rustc.git/blame - src/liballoc/collections/binary_heap.rs
New upstream version 1.44.1+dfsg1
[rustc.git] / src / liballoc / collections / binary_heap.rs
CommitLineData
1a4d82fc
JJ
1//! A priority queue implemented with a binary heap.
2//!
ba9703b0 3//! Insertion and popping the largest element have `O(log(n))` time complexity.
62682a34
SL
4//! Checking the largest element is `O(1)`. Converting a vector to a binary heap
5//! can be done in-place, and has `O(n)` complexity. A binary heap can also be
ba9703b0
XL
6//! converted to a sorted vector in-place, allowing it to be used for an `O(n * log(n))`
7//! in-place heapsort.
1a4d82fc
JJ
8//!
9//! # Examples
10//!
11//! This is a larger example that implements [Dijkstra's algorithm][dijkstra]
12//! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
cc61c64b 13//! It shows how to use [`BinaryHeap`] with custom types.
1a4d82fc
JJ
14//!
15//! [dijkstra]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
16//! [sssp]: http://en.wikipedia.org/wiki/Shortest_path_problem
17//! [dir_graph]: http://en.wikipedia.org/wiki/Directed_graph
cc61c64b 18//! [`BinaryHeap`]: struct.BinaryHeap.html
1a4d82fc
JJ
19//!
20//! ```
21//! use std::cmp::Ordering;
22//! use std::collections::BinaryHeap;
1a4d82fc 23//!
c34b1796 24//! #[derive(Copy, Clone, Eq, PartialEq)]
1a4d82fc 25//! struct State {
85aaf69f
SL
26//! cost: usize,
27//! position: usize,
1a4d82fc
JJ
28//! }
29//!
30//! // The priority queue depends on `Ord`.
31//! // Explicitly implement the trait so the queue becomes a min-heap
32//! // instead of a max-heap.
33//! impl Ord for State {
34//! fn cmp(&self, other: &State) -> Ordering {
7cac9316
XL
35//! // Notice that the we flip the ordering on costs.
36//! // In case of a tie we compare positions - this step is necessary
37//! // to make implementations of `PartialEq` and `Ord` consistent.
1a4d82fc 38//! other.cost.cmp(&self.cost)
7cac9316 39//! .then_with(|| self.position.cmp(&other.position))
1a4d82fc
JJ
40//! }
41//! }
42//!
43//! // `PartialOrd` needs to be implemented as well.
44//! impl PartialOrd for State {
45//! fn partial_cmp(&self, other: &State) -> Option<Ordering> {
46//! Some(self.cmp(other))
47//! }
48//! }
49//!
85aaf69f 50//! // Each node is represented as an `usize`, for a shorter implementation.
1a4d82fc 51//! struct Edge {
85aaf69f
SL
52//! node: usize,
53//! cost: usize,
1a4d82fc
JJ
54//! }
55//!
56//! // Dijkstra's shortest path algorithm.
57//!
58//! // Start at `start` and use `dist` to track the current shortest distance
59//! // to each node. This implementation isn't memory-efficient as it may leave duplicate
85aaf69f 60//! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
1a4d82fc 61//! // for a simpler implementation.
9cc50fc6 62//! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
1a4d82fc 63//! // dist[node] = current shortest distance from `start` to `node`
85aaf69f 64//! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
1a4d82fc
JJ
65//!
66//! let mut heap = BinaryHeap::new();
67//!
68//! // We're at `start`, with a zero cost
69//! dist[start] = 0;
70//! heap.push(State { cost: 0, position: start });
71//!
72//! // Examine the frontier with lower cost nodes first (min-heap)
73//! while let Some(State { cost, position }) = heap.pop() {
74//! // Alternatively we could have continued to find all shortest paths
9cc50fc6 75//! if position == goal { return Some(cost); }
1a4d82fc
JJ
76//!
77//! // Important as we may have already found a better way
78//! if cost > dist[position] { continue; }
79//!
80//! // For each node we can reach, see if we can find a way with
81//! // a lower cost going through this node
62682a34 82//! for edge in &adj_list[position] {
1a4d82fc
JJ
83//! let next = State { cost: cost + edge.cost, position: edge.node };
84//!
85//! // If so, add it to the frontier and continue
86//! if next.cost < dist[next.position] {
87//! heap.push(next);
88//! // Relaxation, we have now found a better way
89//! dist[next.position] = next.cost;
90//! }
91//! }
92//! }
93//!
94//! // Goal not reachable
9cc50fc6 95//! None
1a4d82fc
JJ
96//! }
97//!
98//! fn main() {
99//! // This is the directed graph we're going to use.
100//! // The node numbers correspond to the different states,
101//! // and the edge weights symbolize the cost of moving
102//! // from one node to another.
103//! // Note that the edges are one-way.
104//! //
105//! // 7
106//! // +-----------------+
107//! // | |
e9174d1e 108//! // v 1 2 | 2
1a4d82fc
JJ
109//! // 0 -----> 1 -----> 3 ---> 4
110//! // | ^ ^ ^
111//! // | | 1 | |
112//! // | | | 3 | 1
113//! // +------> 2 -------+ |
114//! // 10 | |
115//! // +---------------+
116//! //
117//! // The graph is represented as an adjacency list where each index,
118//! // corresponding to a node value, has a list of outgoing edges.
119//! // Chosen for its efficiency.
120//! let graph = vec![
121//! // Node 0
122//! vec![Edge { node: 2, cost: 10 },
123//! Edge { node: 1, cost: 1 }],
124//! // Node 1
125//! vec![Edge { node: 3, cost: 2 }],
126//! // Node 2
127//! vec![Edge { node: 1, cost: 1 },
128//! Edge { node: 3, cost: 3 },
129//! Edge { node: 4, cost: 1 }],
130//! // Node 3
131//! vec![Edge { node: 0, cost: 7 },
132//! Edge { node: 4, cost: 2 }],
133//! // Node 4
134//! vec![]];
135//!
9cc50fc6
SL
136//! assert_eq!(shortest_path(&graph, 0, 1), Some(1));
137//! assert_eq!(shortest_path(&graph, 0, 3), Some(3));
138//! assert_eq!(shortest_path(&graph, 3, 0), Some(7));
139//! assert_eq!(shortest_path(&graph, 0, 4), Some(5));
140//! assert_eq!(shortest_path(&graph, 4, 0), None);
1a4d82fc
JJ
141//! }
142//! ```
143
144#![allow(missing_docs)]
85aaf69f 145#![stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 146
dfeec247 147use core::fmt;
e74abb32 148use core::iter::{FromIterator, FusedIterator, TrustedLen};
74b04a01 149use core::mem::{self, size_of, swap, ManuallyDrop};
dfeec247 150use core::ops::{Deref, DerefMut};
1a4d82fc
JJ
151use core::ptr;
152
9fa01778
XL
153use crate::slice;
154use crate::vec::{self, Vec};
1a4d82fc 155
a7813a04
XL
156use super::SpecExtend;
157
1a4d82fc
JJ
158/// A priority queue implemented with a binary heap.
159///
160/// This will be a max-heap.
c34b1796
AL
161///
162/// It is a logic error for an item to be modified in such a way that the
163/// item's ordering relative to any other item, as determined by the `Ord`
164/// trait, changes while it is in the heap. This is normally only possible
165/// through `Cell`, `RefCell`, global state, I/O, or unsafe code.
54a0048b
SL
166///
167/// # Examples
168///
169/// ```
170/// use std::collections::BinaryHeap;
171///
172/// // Type inference lets us omit an explicit type signature (which
173/// // would be `BinaryHeap<i32>` in this example).
174/// let mut heap = BinaryHeap::new();
175///
176/// // We can use peek to look at the next item in the heap. In this case,
177/// // there's no items in there yet so we get None.
178/// assert_eq!(heap.peek(), None);
179///
180/// // Let's add some scores...
181/// heap.push(1);
182/// heap.push(5);
183/// heap.push(2);
184///
185/// // Now peek shows the most important item in the heap.
186/// assert_eq!(heap.peek(), Some(&5));
187///
188/// // We can check the length of a heap.
189/// assert_eq!(heap.len(), 3);
190///
191/// // We can iterate over the items in the heap, although they are returned in
192/// // a random order.
193/// for x in &heap {
194/// println!("{}", x);
195/// }
196///
197/// // If we instead pop these scores, they should come back in order.
198/// assert_eq!(heap.pop(), Some(5));
199/// assert_eq!(heap.pop(), Some(2));
200/// assert_eq!(heap.pop(), Some(1));
201/// assert_eq!(heap.pop(), None);
202///
203/// // We can clear the heap of any remaining items.
204/// heap.clear();
205///
206/// // The heap should now be empty.
207/// assert!(heap.is_empty())
208/// ```
48663c56
XL
209///
210/// ## Min-heap
211///
212/// Either `std::cmp::Reverse` or a custom `Ord` implementation can be used to
213/// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest
214/// value instead of the greatest one.
215///
216/// ```
217/// use std::collections::BinaryHeap;
218/// use std::cmp::Reverse;
219///
220/// let mut heap = BinaryHeap::new();
221///
222/// // Wrap values in `Reverse`
223/// heap.push(Reverse(1));
224/// heap.push(Reverse(5));
225/// heap.push(Reverse(2));
226///
227/// // If we pop these scores now, they should come back in the reverse order.
228/// assert_eq!(heap.pop(), Some(Reverse(1)));
229/// assert_eq!(heap.pop(), Some(Reverse(2)));
230/// assert_eq!(heap.pop(), Some(Reverse(5)));
231/// assert_eq!(heap.pop(), None);
232/// ```
233///
234/// # Time complexity
235///
ba9703b0
XL
236/// | [push] | [pop] | [peek]/[peek\_mut] |
237/// |--------|-----------|--------------------|
238/// | O(1)~ | O(log(n)) | O(1) |
48663c56
XL
239///
240/// The value for `push` is an expected cost; the method documentation gives a
241/// more detailed analysis.
242///
243/// [push]: #method.push
244/// [pop]: #method.pop
245/// [peek]: #method.peek
246/// [peek\_mut]: #method.peek_mut
85aaf69f 247#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
248pub struct BinaryHeap<T> {
249 data: Vec<T>,
250}
251
cc61c64b
XL
252/// Structure wrapping a mutable reference to the greatest item on a
253/// `BinaryHeap`.
3157f602 254///
cc61c64b
XL
255/// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
256/// its documentation for more.
257///
258/// [`peek_mut`]: struct.BinaryHeap.html#method.peek_mut
259/// [`BinaryHeap`]: struct.BinaryHeap.html
5bcae85e 260#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
3157f602 261pub struct PeekMut<'a, T: 'a + Ord> {
32a655c1
SL
262 heap: &'a mut BinaryHeap<T>,
263 sift: bool,
3157f602
XL
264}
265
8bb4bdeb 266#[stable(feature = "collection_debug", since = "1.17.0")]
9fa01778
XL
267impl<T: Ord + fmt::Debug> fmt::Debug for PeekMut<'_, T> {
268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
dfeec247 269 f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish()
8bb4bdeb
XL
270 }
271}
272
5bcae85e 273#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
9fa01778 274impl<T: Ord> Drop for PeekMut<'_, T> {
3157f602 275 fn drop(&mut self) {
32a655c1
SL
276 if self.sift {
277 self.heap.sift_down(0);
278 }
3157f602
XL
279 }
280}
281
5bcae85e 282#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
9fa01778 283impl<T: Ord> Deref for PeekMut<'_, T> {
3157f602
XL
284 type Target = T;
285 fn deref(&self) -> &T {
9fa01778
XL
286 debug_assert!(!self.heap.is_empty());
287 // SAFE: PeekMut is only instantiated for non-empty heaps
288 unsafe { self.heap.data.get_unchecked(0) }
3157f602
XL
289 }
290}
291
5bcae85e 292#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
9fa01778 293impl<T: Ord> DerefMut for PeekMut<'_, T> {
3157f602 294 fn deref_mut(&mut self) -> &mut T {
9fa01778
XL
295 debug_assert!(!self.heap.is_empty());
296 // SAFE: PeekMut is only instantiated for non-empty heaps
297 unsafe { self.heap.data.get_unchecked_mut(0) }
3157f602
XL
298 }
299}
300
32a655c1
SL
301impl<'a, T: Ord> PeekMut<'a, T> {
302 /// Removes the peeked value from the heap and returns it.
cc61c64b 303 #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
32a655c1
SL
304 pub fn pop(mut this: PeekMut<'a, T>) -> T {
305 let value = this.heap.pop().unwrap();
306 this.sift = false;
307 value
308 }
309}
310
b039eaaf
SL
311#[stable(feature = "rust1", since = "1.0.0")]
312impl<T: Clone> Clone for BinaryHeap<T> {
313 fn clone(&self) -> Self {
314 BinaryHeap { data: self.data.clone() }
315 }
316
317 fn clone_from(&mut self, source: &Self) {
318 self.data.clone_from(&source.data);
319 }
320}
321
85aaf69f 322#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 323impl<T: Ord> Default for BinaryHeap<T> {
9e0c209e 324 /// Creates an empty `BinaryHeap<T>`.
1a4d82fc 325 #[inline]
92a42be0
SL
326 fn default() -> BinaryHeap<T> {
327 BinaryHeap::new()
328 }
1a4d82fc
JJ
329}
330
e9174d1e 331#[stable(feature = "binaryheap_debug", since = "1.4.0")]
9fa01778
XL
332impl<T: fmt::Debug> fmt::Debug for BinaryHeap<T> {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
e9174d1e
SL
334 f.debug_list().entries(self.iter()).finish()
335 }
336}
337
1a4d82fc
JJ
338impl<T: Ord> BinaryHeap<T> {
339 /// Creates an empty `BinaryHeap` as a max-heap.
340 ///
341 /// # Examples
342 ///
54a0048b
SL
343 /// Basic usage:
344 ///
1a4d82fc
JJ
345 /// ```
346 /// use std::collections::BinaryHeap;
347 /// let mut heap = BinaryHeap::new();
85aaf69f 348 /// heap.push(4);
1a4d82fc 349 /// ```
85aaf69f 350 #[stable(feature = "rust1", since = "1.0.0")]
92a42be0
SL
351 pub fn new() -> BinaryHeap<T> {
352 BinaryHeap { data: vec![] }
353 }
1a4d82fc
JJ
354
355 /// Creates an empty `BinaryHeap` with a specific capacity.
356 /// This preallocates enough memory for `capacity` elements,
357 /// so that the `BinaryHeap` does not have to be reallocated
358 /// until it contains at least that many values.
359 ///
360 /// # Examples
361 ///
54a0048b
SL
362 /// Basic usage:
363 ///
1a4d82fc
JJ
364 /// ```
365 /// use std::collections::BinaryHeap;
366 /// let mut heap = BinaryHeap::with_capacity(10);
85aaf69f 367 /// heap.push(4);
1a4d82fc 368 /// ```
85aaf69f
SL
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
1a4d82fc
JJ
371 BinaryHeap { data: Vec::with_capacity(capacity) }
372 }
373
3157f602
XL
374 /// Returns a mutable reference to the greatest item in the binary heap, or
375 /// `None` if it is empty.
376 ///
377 /// Note: If the `PeekMut` value is leaked, the heap may be in an
378 /// inconsistent state.
379 ///
380 /// # Examples
381 ///
382 /// Basic usage:
383 ///
384 /// ```
3157f602
XL
385 /// use std::collections::BinaryHeap;
386 /// let mut heap = BinaryHeap::new();
387 /// assert!(heap.peek_mut().is_none());
388 ///
389 /// heap.push(1);
390 /// heap.push(5);
391 /// heap.push(2);
392 /// {
393 /// let mut val = heap.peek_mut().unwrap();
394 /// *val = 0;
395 /// }
396 /// assert_eq!(heap.peek(), Some(&2));
397 /// ```
48663c56
XL
398 ///
399 /// # Time complexity
400 ///
ba9703b0 401 /// Cost is `O(1)` in the worst case.
5bcae85e 402 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
9fa01778 403 pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T>> {
dfeec247 404 if self.is_empty() { None } else { Some(PeekMut { heap: self, sift: true }) }
3157f602
XL
405 }
406
1a4d82fc
JJ
407 /// Removes the greatest item from the binary heap and returns it, or `None` if it
408 /// is empty.
409 ///
410 /// # Examples
411 ///
54a0048b
SL
412 /// Basic usage:
413 ///
1a4d82fc
JJ
414 /// ```
415 /// use std::collections::BinaryHeap;
b039eaaf 416 /// let mut heap = BinaryHeap::from(vec![1, 3]);
1a4d82fc
JJ
417 ///
418 /// assert_eq!(heap.pop(), Some(3));
419 /// assert_eq!(heap.pop(), Some(1));
420 /// assert_eq!(heap.pop(), None);
421 /// ```
48663c56
XL
422 ///
423 /// # Time complexity
424 ///
ba9703b0 425 /// The worst case cost of `pop` on a heap containing *n* elements is `O(log(n))`.
85aaf69f 426 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
427 pub fn pop(&mut self) -> Option<T> {
428 self.data.pop().map(|mut item| {
429 if !self.is_empty() {
430 swap(&mut item, &mut self.data[0]);
9cc50fc6 431 self.sift_down_to_bottom(0);
1a4d82fc
JJ
432 }
433 item
434 })
435 }
436
437 /// Pushes an item onto the binary heap.
438 ///
439 /// # Examples
440 ///
54a0048b
SL
441 /// Basic usage:
442 ///
1a4d82fc
JJ
443 /// ```
444 /// use std::collections::BinaryHeap;
445 /// let mut heap = BinaryHeap::new();
85aaf69f 446 /// heap.push(3);
1a4d82fc
JJ
447 /// heap.push(5);
448 /// heap.push(1);
449 ///
450 /// assert_eq!(heap.len(), 3);
451 /// assert_eq!(heap.peek(), Some(&5));
452 /// ```
48663c56
XL
453 ///
454 /// # Time complexity
455 ///
456 /// The expected cost of `push`, averaged over every possible ordering of
457 /// the elements being pushed, and over a sufficiently large number of
ba9703b0 458 /// pushes, is `O(1)`. This is the most meaningful cost metric when pushing
48663c56
XL
459 /// elements that are *not* already in any sorted pattern.
460 ///
461 /// The time complexity degrades if elements are pushed in predominantly
462 /// ascending order. In the worst case, elements are pushed in ascending
ba9703b0 463 /// sorted order and the amortized cost per push is `O(log(n))` against a heap
48663c56
XL
464 /// containing *n* elements.
465 ///
ba9703b0 466 /// The worst case cost of a *single* call to `push` is `O(n)`. The worst case
48663c56
XL
467 /// occurs when capacity is exhausted and needs a resize. The resize cost
468 /// has been amortized in the previous figures.
85aaf69f 469 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
470 pub fn push(&mut self, item: T) {
471 let old_len = self.len();
472 self.data.push(item);
473 self.sift_up(0, old_len);
474 }
475
1a4d82fc
JJ
476 /// Consumes the `BinaryHeap` and returns a vector in sorted
477 /// (ascending) order.
478 ///
479 /// # Examples
480 ///
54a0048b
SL
481 /// Basic usage:
482 ///
1a4d82fc
JJ
483 /// ```
484 /// use std::collections::BinaryHeap;
485 ///
b039eaaf 486 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
1a4d82fc
JJ
487 /// heap.push(6);
488 /// heap.push(3);
489 ///
490 /// let vec = heap.into_sorted_vec();
c34b1796 491 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
1a4d82fc 492 /// ```
b039eaaf 493 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1a4d82fc
JJ
494 pub fn into_sorted_vec(mut self) -> Vec<T> {
495 let mut end = self.len();
496 while end > 1 {
497 end -= 1;
498 self.data.swap(0, end);
499 self.sift_down_range(0, end);
500 }
501 self.into_vec()
502 }
503
504 // The implementations of sift_up and sift_down use unsafe blocks in
505 // order to move an element out of the vector (leaving behind a
d9579d0f
AL
506 // hole), shift along the others and move the removed element back into the
507 // vector at the final location of the hole.
508 // The `Hole` type is used to represent this, and make sure
509 // the hole is filled back at the end of its scope, even on panic.
510 // Using a hole reduces the constant factor compared to using swaps,
511 // which involves twice as many moves.
32a655c1 512 fn sift_up(&mut self, start: usize, pos: usize) -> usize {
1a4d82fc 513 unsafe {
d9579d0f
AL
514 // Take out the value at `pos` and create a hole.
515 let mut hole = Hole::new(&mut self.data, pos);
1a4d82fc 516
d9579d0f
AL
517 while hole.pos() > start {
518 let parent = (hole.pos() - 1) / 2;
92a42be0
SL
519 if hole.element() <= hole.get(parent) {
520 break;
521 }
d9579d0f 522 hole.move_to(parent);
1a4d82fc 523 }
32a655c1 524 hole.pos()
1a4d82fc
JJ
525 }
526 }
527
92a42be0
SL
528 /// Take an element at `pos` and move it down the heap,
529 /// while its children are larger.
530 fn sift_down_range(&mut self, pos: usize, end: usize) {
1a4d82fc 531 unsafe {
d9579d0f 532 let mut hole = Hole::new(&mut self.data, pos);
1a4d82fc
JJ
533 let mut child = 2 * pos + 1;
534 while child < end {
535 let right = child + 1;
92a42be0 536 // compare with the greater of the two children
74b04a01 537 if right < end && hole.get(child) <= hole.get(right) {
1a4d82fc
JJ
538 child = right;
539 }
92a42be0
SL
540 // if we are already in order, stop.
541 if hole.element() >= hole.get(child) {
542 break;
543 }
d9579d0f
AL
544 hole.move_to(child);
545 child = 2 * hole.pos() + 1;
1a4d82fc 546 }
1a4d82fc
JJ
547 }
548 }
549
85aaf69f 550 fn sift_down(&mut self, pos: usize) {
1a4d82fc
JJ
551 let len = self.len();
552 self.sift_down_range(pos, len);
553 }
554
9cc50fc6
SL
555 /// Take an element at `pos` and move it all the way down the heap,
556 /// then sift it up to its position.
557 ///
558 /// Note: This is faster when the element is known to be large / should
559 /// be closer to the bottom.
560 fn sift_down_to_bottom(&mut self, mut pos: usize) {
561 let end = self.len();
562 let start = pos;
563 unsafe {
564 let mut hole = Hole::new(&mut self.data, pos);
565 let mut child = 2 * pos + 1;
566 while child < end {
567 let right = child + 1;
568 // compare with the greater of the two children
74b04a01 569 if right < end && hole.get(child) <= hole.get(right) {
9cc50fc6
SL
570 child = right;
571 }
572 hole.move_to(child);
573 child = 2 * hole.pos() + 1;
574 }
575 pos = hole.pos;
576 }
577 self.sift_up(start, pos);
578 }
579
9fa01778
XL
580 fn rebuild(&mut self) {
581 let mut n = self.len() / 2;
582 while n > 0 {
583 n -= 1;
584 self.sift_down(n);
585 }
586 }
587
588 /// Moves all the elements of `other` into `self`, leaving `other` empty.
589 ///
590 /// # Examples
591 ///
592 /// Basic usage:
593 ///
594 /// ```
595 /// use std::collections::BinaryHeap;
596 ///
597 /// let v = vec![-10, 1, 2, 3, 3];
598 /// let mut a = BinaryHeap::from(v);
599 ///
600 /// let v = vec![-20, 5, 43];
601 /// let mut b = BinaryHeap::from(v);
602 ///
603 /// a.append(&mut b);
604 ///
605 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
606 /// assert!(b.is_empty());
607 /// ```
608 #[stable(feature = "binary_heap_append", since = "1.11.0")]
609 pub fn append(&mut self, other: &mut Self) {
610 if self.len() < other.len() {
611 swap(self, other);
612 }
613
614 if other.is_empty() {
615 return;
616 }
617
618 #[inline(always)]
619 fn log2_fast(x: usize) -> usize {
620 8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
621 }
622
623 // `rebuild` takes O(len1 + len2) operations
624 // and about 2 * (len1 + len2) comparisons in the worst case
ba9703b0 625 // while `extend` takes O(len2 * log(len1)) operations
9fa01778
XL
626 // and about 1 * len2 * log_2(len1) comparisons in the worst case,
627 // assuming len1 >= len2.
628 #[inline]
629 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
630 2 * (len1 + len2) < len2 * log2_fast(len1)
631 }
632
633 if better_to_rebuild(self.len(), other.len()) {
634 self.data.append(&mut other.data);
635 self.rebuild();
636 } else {
637 self.extend(other.drain());
638 }
639 }
e74abb32
XL
640
641 /// Returns an iterator which retrieves elements in heap order.
642 /// The retrieved elements are removed from the original heap.
643 /// The remaining elements will be removed on drop in heap order.
644 ///
645 /// Note:
ba9703b0 646 /// * `.drain_sorted()` is `O(n * log(n))`; much slower than `.drain()`.
e74abb32
XL
647 /// You should use the latter for most cases.
648 ///
649 /// # Examples
650 ///
651 /// Basic usage:
652 ///
653 /// ```
654 /// #![feature(binary_heap_drain_sorted)]
655 /// use std::collections::BinaryHeap;
656 ///
657 /// let mut heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]);
658 /// assert_eq!(heap.len(), 5);
659 ///
660 /// drop(heap.drain_sorted()); // removes all elements in heap order
661 /// assert_eq!(heap.len(), 0);
662 /// ```
663 #[inline]
664 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
665 pub fn drain_sorted(&mut self) -> DrainSorted<'_, T> {
dfeec247 666 DrainSorted { inner: self }
e74abb32 667 }
9fa01778
XL
668}
669
670impl<T> BinaryHeap<T> {
671 /// Returns an iterator visiting all values in the underlying vector, in
672 /// arbitrary order.
673 ///
674 /// # Examples
675 ///
676 /// Basic usage:
677 ///
678 /// ```
679 /// use std::collections::BinaryHeap;
680 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
681 ///
682 /// // Print 1, 2, 3, 4 in arbitrary order
683 /// for x in heap.iter() {
684 /// println!("{}", x);
685 /// }
686 /// ```
687 #[stable(feature = "rust1", since = "1.0.0")]
688 pub fn iter(&self) -> Iter<'_, T> {
689 Iter { iter: self.data.iter() }
690 }
691
e74abb32
XL
692 /// Returns an iterator which retrieves elements in heap order.
693 /// This method consumes the original heap.
694 ///
695 /// # Examples
696 ///
697 /// Basic usage:
698 ///
699 /// ```
700 /// #![feature(binary_heap_into_iter_sorted)]
701 /// use std::collections::BinaryHeap;
702 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]);
703 ///
704 /// assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), vec![5, 4]);
705 /// ```
706 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
707 pub fn into_iter_sorted(self) -> IntoIterSorted<T> {
dfeec247 708 IntoIterSorted { inner: self }
e74abb32
XL
709 }
710
9fa01778
XL
711 /// Returns the greatest item in the binary heap, or `None` if it is empty.
712 ///
713 /// # Examples
714 ///
715 /// Basic usage:
716 ///
717 /// ```
718 /// use std::collections::BinaryHeap;
719 /// let mut heap = BinaryHeap::new();
720 /// assert_eq!(heap.peek(), None);
721 ///
722 /// heap.push(1);
723 /// heap.push(5);
724 /// heap.push(2);
725 /// assert_eq!(heap.peek(), Some(&5));
726 ///
727 /// ```
48663c56
XL
728 ///
729 /// # Time complexity
730 ///
ba9703b0 731 /// Cost is `O(1)` in the worst case.
9fa01778
XL
732 #[stable(feature = "rust1", since = "1.0.0")]
733 pub fn peek(&self) -> Option<&T> {
734 self.data.get(0)
735 }
736
737 /// Returns the number of elements the binary heap can hold without reallocating.
738 ///
739 /// # Examples
740 ///
741 /// Basic usage:
742 ///
743 /// ```
744 /// use std::collections::BinaryHeap;
745 /// let mut heap = BinaryHeap::with_capacity(100);
746 /// assert!(heap.capacity() >= 100);
747 /// heap.push(4);
748 /// ```
749 #[stable(feature = "rust1", since = "1.0.0")]
750 pub fn capacity(&self) -> usize {
751 self.data.capacity()
752 }
753
754 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
755 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
756 ///
757 /// Note that the allocator may give the collection more space than it requests. Therefore
758 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
759 /// insertions are expected.
760 ///
761 /// # Panics
762 ///
763 /// Panics if the new capacity overflows `usize`.
764 ///
765 /// # Examples
766 ///
767 /// Basic usage:
768 ///
769 /// ```
770 /// use std::collections::BinaryHeap;
771 /// let mut heap = BinaryHeap::new();
772 /// heap.reserve_exact(100);
773 /// assert!(heap.capacity() >= 100);
774 /// heap.push(4);
775 /// ```
776 ///
777 /// [`reserve`]: #method.reserve
778 #[stable(feature = "rust1", since = "1.0.0")]
779 pub fn reserve_exact(&mut self, additional: usize) {
780 self.data.reserve_exact(additional);
781 }
782
783 /// Reserves capacity for at least `additional` more elements to be inserted in the
784 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
785 ///
786 /// # Panics
787 ///
788 /// Panics if the new capacity overflows `usize`.
789 ///
790 /// # Examples
791 ///
792 /// Basic usage:
793 ///
794 /// ```
795 /// use std::collections::BinaryHeap;
796 /// let mut heap = BinaryHeap::new();
797 /// heap.reserve(100);
798 /// assert!(heap.capacity() >= 100);
799 /// heap.push(4);
800 /// ```
801 #[stable(feature = "rust1", since = "1.0.0")]
802 pub fn reserve(&mut self, additional: usize) {
803 self.data.reserve(additional);
804 }
805
806 /// Discards as much additional capacity as possible.
807 ///
808 /// # Examples
809 ///
810 /// Basic usage:
811 ///
812 /// ```
813 /// use std::collections::BinaryHeap;
814 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
815 ///
816 /// assert!(heap.capacity() >= 100);
817 /// heap.shrink_to_fit();
818 /// assert!(heap.capacity() == 0);
819 /// ```
820 #[stable(feature = "rust1", since = "1.0.0")]
821 pub fn shrink_to_fit(&mut self) {
822 self.data.shrink_to_fit();
823 }
824
825 /// Discards capacity with a lower bound.
826 ///
827 /// The capacity will remain at least as large as both the length
828 /// and the supplied value.
829 ///
830 /// Panics if the current capacity is smaller than the supplied
831 /// minimum capacity.
832 ///
833 /// # Examples
834 ///
835 /// ```
836 /// #![feature(shrink_to)]
837 /// use std::collections::BinaryHeap;
838 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
839 ///
840 /// assert!(heap.capacity() >= 100);
841 /// heap.shrink_to(10);
842 /// assert!(heap.capacity() >= 10);
843 /// ```
844 #[inline]
dfeec247 845 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
9fa01778
XL
846 pub fn shrink_to(&mut self, min_capacity: usize) {
847 self.data.shrink_to(min_capacity)
848 }
849
850 /// Consumes the `BinaryHeap` and returns the underlying vector
851 /// in arbitrary order.
852 ///
853 /// # Examples
854 ///
855 /// Basic usage:
856 ///
857 /// ```
858 /// use std::collections::BinaryHeap;
859 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
860 /// let vec = heap.into_vec();
861 ///
862 /// // Will print in some order
863 /// for x in vec {
864 /// println!("{}", x);
865 /// }
866 /// ```
867 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
868 pub fn into_vec(self) -> Vec<T> {
869 self.into()
870 }
871
1a4d82fc 872 /// Returns the length of the binary heap.
54a0048b
SL
873 ///
874 /// # Examples
875 ///
876 /// Basic usage:
877 ///
878 /// ```
879 /// use std::collections::BinaryHeap;
880 /// let heap = BinaryHeap::from(vec![1, 3]);
881 ///
882 /// assert_eq!(heap.len(), 2);
883 /// ```
85aaf69f 884 #[stable(feature = "rust1", since = "1.0.0")]
92a42be0
SL
885 pub fn len(&self) -> usize {
886 self.data.len()
887 }
1a4d82fc
JJ
888
889 /// Checks if the binary heap is empty.
54a0048b
SL
890 ///
891 /// # Examples
892 ///
893 /// Basic usage:
894 ///
895 /// ```
896 /// use std::collections::BinaryHeap;
897 /// let mut heap = BinaryHeap::new();
898 ///
899 /// assert!(heap.is_empty());
900 ///
901 /// heap.push(3);
902 /// heap.push(5);
903 /// heap.push(1);
904 ///
905 /// assert!(!heap.is_empty());
906 /// ```
85aaf69f 907 #[stable(feature = "rust1", since = "1.0.0")]
92a42be0
SL
908 pub fn is_empty(&self) -> bool {
909 self.len() == 0
910 }
1a4d82fc
JJ
911
912 /// Clears the binary heap, returning an iterator over the removed elements.
c34b1796
AL
913 ///
914 /// The elements are removed in arbitrary order.
54a0048b
SL
915 ///
916 /// # Examples
917 ///
918 /// Basic usage:
919 ///
920 /// ```
921 /// use std::collections::BinaryHeap;
922 /// let mut heap = BinaryHeap::from(vec![1, 3]);
923 ///
924 /// assert!(!heap.is_empty());
925 ///
926 /// for x in heap.drain() {
927 /// println!("{}", x);
928 /// }
929 ///
930 /// assert!(heap.is_empty());
931 /// ```
1a4d82fc 932 #[inline]
92a42be0 933 #[stable(feature = "drain", since = "1.6.0")]
9fa01778 934 pub fn drain(&mut self) -> Drain<'_, T> {
d9579d0f 935 Drain { iter: self.data.drain(..) }
1a4d82fc
JJ
936 }
937
938 /// Drops all items from the binary heap.
54a0048b
SL
939 ///
940 /// # Examples
941 ///
942 /// Basic usage:
943 ///
944 /// ```
945 /// use std::collections::BinaryHeap;
946 /// let mut heap = BinaryHeap::from(vec![1, 3]);
947 ///
948 /// assert!(!heap.is_empty());
949 ///
950 /// heap.clear();
951 ///
952 /// assert!(heap.is_empty());
953 /// ```
85aaf69f 954 #[stable(feature = "rust1", since = "1.0.0")]
92a42be0
SL
955 pub fn clear(&mut self) {
956 self.drain();
957 }
1a4d82fc
JJ
958}
959
0731742a 960/// Hole represents a hole in a slice i.e., an index without valid value
d9579d0f
AL
961/// (because it was moved from or duplicated).
962/// In drop, `Hole` will restore the slice by filling the hole
963/// position with the value that was originally removed.
964struct Hole<'a, T: 'a> {
965 data: &'a mut [T],
83c7162d 966 elt: ManuallyDrop<T>,
d9579d0f
AL
967 pos: usize,
968}
969
970impl<'a, T> Hole<'a, T> {
9fa01778 971 /// Create a new `Hole` at index `pos`.
9e0c209e
SL
972 ///
973 /// Unsafe because pos must be within the data slice.
974 #[inline]
975 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
976 debug_assert!(pos < data.len());
9fa01778
XL
977 // SAFE: pos should be inside the slice
978 let elt = ptr::read(data.get_unchecked(pos));
dfeec247 979 Hole { data, elt: ManuallyDrop::new(elt), pos }
d9579d0f
AL
980 }
981
9e0c209e 982 #[inline]
92a42be0
SL
983 fn pos(&self) -> usize {
984 self.pos
985 }
d9579d0f 986
cc61c64b 987 /// Returns a reference to the element removed.
9e0c209e 988 #[inline]
92a42be0 989 fn element(&self) -> &T {
83c7162d 990 &self.elt
d9579d0f
AL
991 }
992
cc61c64b 993 /// Returns a reference to the element at `index`.
d9579d0f 994 ///
9e0c209e
SL
995 /// Unsafe because index must be within the data slice and not equal to pos.
996 #[inline]
d9579d0f
AL
997 unsafe fn get(&self, index: usize) -> &T {
998 debug_assert!(index != self.pos);
9e0c209e
SL
999 debug_assert!(index < self.data.len());
1000 self.data.get_unchecked(index)
d9579d0f
AL
1001 }
1002
1003 /// Move hole to new location
1004 ///
9e0c209e
SL
1005 /// Unsafe because index must be within the data slice and not equal to pos.
1006 #[inline]
d9579d0f
AL
1007 unsafe fn move_to(&mut self, index: usize) {
1008 debug_assert!(index != self.pos);
9e0c209e
SL
1009 debug_assert!(index < self.data.len());
1010 let index_ptr: *const _ = self.data.get_unchecked(index);
1011 let hole_ptr = self.data.get_unchecked_mut(self.pos);
d9579d0f
AL
1012 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1013 self.pos = index;
1014 }
1015}
1016
9fa01778 1017impl<T> Drop for Hole<'_, T> {
9e0c209e 1018 #[inline]
d9579d0f
AL
1019 fn drop(&mut self) {
1020 // fill the hole again
1021 unsafe {
1022 let pos = self.pos;
83c7162d 1023 ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
d9579d0f
AL
1024 }
1025 }
1026}
1027
cc61c64b
XL
1028/// An iterator over the elements of a `BinaryHeap`.
1029///
1030/// This `struct` is created by the [`iter`] method on [`BinaryHeap`]. See its
1031/// documentation for more.
1032///
1033/// [`iter`]: struct.BinaryHeap.html#method.iter
1034/// [`BinaryHeap`]: struct.BinaryHeap.html
85aaf69f 1035#[stable(feature = "rust1", since = "1.0.0")]
92a42be0 1036pub struct Iter<'a, T: 'a> {
1a4d82fc
JJ
1037 iter: slice::Iter<'a, T>,
1038}
1039
8bb4bdeb 1040#[stable(feature = "collection_debug", since = "1.17.0")]
9fa01778
XL
1041impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1042 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
dfeec247 1043 f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
8bb4bdeb
XL
1044 }
1045}
1046
ea8adc8c 1047// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
85aaf69f 1048#[stable(feature = "rust1", since = "1.0.0")]
9fa01778
XL
1049impl<T> Clone for Iter<'_, T> {
1050 fn clone(&self) -> Self {
1a4d82fc
JJ
1051 Iter { iter: self.iter.clone() }
1052 }
1053}
1054
85aaf69f 1055#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1056impl<'a, T> Iterator for Iter<'a, T> {
1057 type Item = &'a T;
1058
1059 #[inline]
92a42be0
SL
1060 fn next(&mut self) -> Option<&'a T> {
1061 self.iter.next()
1062 }
1a4d82fc
JJ
1063
1064 #[inline]
92a42be0
SL
1065 fn size_hint(&self) -> (usize, Option<usize>) {
1066 self.iter.size_hint()
1067 }
416331ca
XL
1068
1069 #[inline]
1070 fn last(self) -> Option<&'a T> {
1071 self.iter.last()
1072 }
1a4d82fc
JJ
1073}
1074
85aaf69f 1075#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1076impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1077 #[inline]
92a42be0
SL
1078 fn next_back(&mut self) -> Option<&'a T> {
1079 self.iter.next_back()
1080 }
1a4d82fc
JJ
1081}
1082
85aaf69f 1083#[stable(feature = "rust1", since = "1.0.0")]
9fa01778 1084impl<T> ExactSizeIterator for Iter<'_, T> {
476ff2be
SL
1085 fn is_empty(&self) -> bool {
1086 self.iter.is_empty()
1087 }
1088}
1a4d82fc 1089
0531ce1d 1090#[stable(feature = "fused", since = "1.26.0")]
9fa01778 1091impl<T> FusedIterator for Iter<'_, T> {}
9e0c209e 1092
cc61c64b
XL
1093/// An owning iterator over the elements of a `BinaryHeap`.
1094///
dfeec247 1095/// This `struct` is created by the [`into_iter`] method on [`BinaryHeap`]
cc61c64b
XL
1096/// (provided by the `IntoIterator` trait). See its documentation for more.
1097///
1098/// [`into_iter`]: struct.BinaryHeap.html#method.into_iter
1099/// [`BinaryHeap`]: struct.BinaryHeap.html
85aaf69f 1100#[stable(feature = "rust1", since = "1.0.0")]
a7813a04 1101#[derive(Clone)]
1a4d82fc
JJ
1102pub struct IntoIter<T> {
1103 iter: vec::IntoIter<T>,
1104}
1105
8bb4bdeb
XL
1106#[stable(feature = "collection_debug", since = "1.17.0")]
1107impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
9fa01778 1108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
dfeec247 1109 f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
8bb4bdeb
XL
1110 }
1111}
1112
85aaf69f 1113#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1114impl<T> Iterator for IntoIter<T> {
1115 type Item = T;
1116
1117 #[inline]
92a42be0
SL
1118 fn next(&mut self) -> Option<T> {
1119 self.iter.next()
1120 }
1a4d82fc
JJ
1121
1122 #[inline]
92a42be0
SL
1123 fn size_hint(&self) -> (usize, Option<usize>) {
1124 self.iter.size_hint()
1125 }
1a4d82fc
JJ
1126}
1127
85aaf69f 1128#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1129impl<T> DoubleEndedIterator for IntoIter<T> {
1130 #[inline]
92a42be0
SL
1131 fn next_back(&mut self) -> Option<T> {
1132 self.iter.next_back()
1133 }
1a4d82fc
JJ
1134}
1135
85aaf69f 1136#[stable(feature = "rust1", since = "1.0.0")]
476ff2be
SL
1137impl<T> ExactSizeIterator for IntoIter<T> {
1138 fn is_empty(&self) -> bool {
1139 self.iter.is_empty()
1140 }
1141}
1a4d82fc 1142
0531ce1d 1143#[stable(feature = "fused", since = "1.26.0")]
9e0c209e
SL
1144impl<T> FusedIterator for IntoIter<T> {}
1145
e74abb32
XL
1146#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1147#[derive(Clone, Debug)]
1148pub struct IntoIterSorted<T> {
1149 inner: BinaryHeap<T>,
1150}
1151
1152#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1153impl<T: Ord> Iterator for IntoIterSorted<T> {
1154 type Item = T;
1155
1156 #[inline]
1157 fn next(&mut self) -> Option<T> {
1158 self.inner.pop()
1159 }
1160
1161 #[inline]
1162 fn size_hint(&self) -> (usize, Option<usize>) {
1163 let exact = self.inner.len();
1164 (exact, Some(exact))
1165 }
1166}
1167
1168#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1169impl<T: Ord> ExactSizeIterator for IntoIterSorted<T> {}
1170
1171#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1172impl<T: Ord> FusedIterator for IntoIterSorted<T> {}
1173
1174#[unstable(feature = "trusted_len", issue = "37572")]
1175unsafe impl<T: Ord> TrustedLen for IntoIterSorted<T> {}
1176
cc61c64b
XL
1177/// A draining iterator over the elements of a `BinaryHeap`.
1178///
1179/// This `struct` is created by the [`drain`] method on [`BinaryHeap`]. See its
1180/// documentation for more.
1181///
1182/// [`drain`]: struct.BinaryHeap.html#method.drain
1183/// [`BinaryHeap`]: struct.BinaryHeap.html
92a42be0 1184#[stable(feature = "drain", since = "1.6.0")]
8bb4bdeb 1185#[derive(Debug)]
1a4d82fc
JJ
1186pub struct Drain<'a, T: 'a> {
1187 iter: vec::Drain<'a, T>,
1188}
1189
c30ab7b3 1190#[stable(feature = "drain", since = "1.6.0")]
9fa01778 1191impl<T> Iterator for Drain<'_, T> {
1a4d82fc
JJ
1192 type Item = T;
1193
1194 #[inline]
92a42be0
SL
1195 fn next(&mut self) -> Option<T> {
1196 self.iter.next()
1197 }
1a4d82fc
JJ
1198
1199 #[inline]
92a42be0
SL
1200 fn size_hint(&self) -> (usize, Option<usize>) {
1201 self.iter.size_hint()
1202 }
1a4d82fc
JJ
1203}
1204
c30ab7b3 1205#[stable(feature = "drain", since = "1.6.0")]
9fa01778 1206impl<T> DoubleEndedIterator for Drain<'_, T> {
1a4d82fc 1207 #[inline]
92a42be0
SL
1208 fn next_back(&mut self) -> Option<T> {
1209 self.iter.next_back()
1210 }
1a4d82fc
JJ
1211}
1212
c30ab7b3 1213#[stable(feature = "drain", since = "1.6.0")]
9fa01778 1214impl<T> ExactSizeIterator for Drain<'_, T> {
476ff2be
SL
1215 fn is_empty(&self) -> bool {
1216 self.iter.is_empty()
1217 }
1218}
1a4d82fc 1219
0531ce1d 1220#[stable(feature = "fused", since = "1.26.0")]
9fa01778 1221impl<T> FusedIterator for Drain<'_, T> {}
9e0c209e 1222
e74abb32
XL
1223/// A draining iterator over the elements of a `BinaryHeap`.
1224///
1225/// This `struct` is created by the [`drain_sorted`] method on [`BinaryHeap`]. See its
1226/// documentation for more.
1227///
1228/// [`drain_sorted`]: struct.BinaryHeap.html#method.drain_sorted
1229/// [`BinaryHeap`]: struct.BinaryHeap.html
1230#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1231#[derive(Debug)]
1232pub struct DrainSorted<'a, T: Ord> {
1233 inner: &'a mut BinaryHeap<T>,
1234}
1235
1236#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1237impl<'a, T: Ord> Drop for DrainSorted<'a, T> {
1238 /// Removes heap elements in heap order.
1239 fn drop(&mut self) {
74b04a01
XL
1240 struct DropGuard<'r, 'a, T: Ord>(&'r mut DrainSorted<'a, T>);
1241
1242 impl<'r, 'a, T: Ord> Drop for DropGuard<'r, 'a, T> {
1243 fn drop(&mut self) {
1244 while let Some(_) = self.0.inner.pop() {}
1245 }
1246 }
1247
1248 while let Some(item) = self.inner.pop() {
1249 let guard = DropGuard(self);
1250 drop(item);
1251 mem::forget(guard);
1252 }
e74abb32
XL
1253 }
1254}
1255
1256#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1257impl<T: Ord> Iterator for DrainSorted<'_, T> {
1258 type Item = T;
1259
1260 #[inline]
1261 fn next(&mut self) -> Option<T> {
1262 self.inner.pop()
1263 }
1264
1265 #[inline]
1266 fn size_hint(&self) -> (usize, Option<usize>) {
1267 let exact = self.inner.len();
1268 (exact, Some(exact))
1269 }
1270}
1271
1272#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
dfeec247 1273impl<T: Ord> ExactSizeIterator for DrainSorted<'_, T> {}
e74abb32
XL
1274
1275#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1276impl<T: Ord> FusedIterator for DrainSorted<'_, T> {}
1277
1278#[unstable(feature = "trusted_len", issue = "37572")]
1279unsafe impl<T: Ord> TrustedLen for DrainSorted<'_, T> {}
1280
8bb4bdeb 1281#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
b039eaaf 1282impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
e1599b0c
XL
1283 /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1284 ///
1285 /// This conversion happens in-place, and has `O(n)` time complexity.
b039eaaf
SL
1286 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1287 let mut heap = BinaryHeap { data: vec };
a7813a04 1288 heap.rebuild();
b039eaaf
SL
1289 heap
1290 }
1291}
1292
8bb4bdeb 1293#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
b039eaaf
SL
1294impl<T> From<BinaryHeap<T>> for Vec<T> {
1295 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1296 heap.data
1297 }
1298}
1299
85aaf69f 1300#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 1301impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
92a42be0 1302 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
b039eaaf 1303 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
85aaf69f
SL
1304 }
1305}
1306
1307#[stable(feature = "rust1", since = "1.0.0")]
9fa01778 1308impl<T> IntoIterator for BinaryHeap<T> {
85aaf69f
SL
1309 type Item = T;
1310 type IntoIter = IntoIter<T>;
1311
9346a6ac
AL
1312 /// Creates a consuming iterator, that is, one that moves each value out of
1313 /// the binary heap in arbitrary order. The binary heap cannot be used
1314 /// after calling this.
1315 ///
1316 /// # Examples
1317 ///
54a0048b
SL
1318 /// Basic usage:
1319 ///
9346a6ac 1320 /// ```
9346a6ac 1321 /// use std::collections::BinaryHeap;
b039eaaf 1322 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
9346a6ac
AL
1323 ///
1324 /// // Print 1, 2, 3, 4 in arbitrary order
1325 /// for x in heap.into_iter() {
1326 /// // x has type i32, not &i32
1327 /// println!("{}", x);
1328 /// }
1329 /// ```
85aaf69f 1330 fn into_iter(self) -> IntoIter<T> {
9346a6ac 1331 IntoIter { iter: self.data.into_iter() }
85aaf69f
SL
1332 }
1333}
1334
1335#[stable(feature = "rust1", since = "1.0.0")]
9fa01778 1336impl<'a, T> IntoIterator for &'a BinaryHeap<T> {
85aaf69f
SL
1337 type Item = &'a T;
1338 type IntoIter = Iter<'a, T>;
1339
1340 fn into_iter(self) -> Iter<'a, T> {
1341 self.iter()
1a4d82fc
JJ
1342 }
1343}
1344
85aaf69f 1345#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 1346impl<T: Ord> Extend<T> for BinaryHeap<T> {
a7813a04 1347 #[inline]
54a0048b 1348 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
a7813a04
XL
1349 <Self as SpecExtend<I>>::spec_extend(self, iter);
1350 }
1351}
1352
1353impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1354 default fn spec_extend(&mut self, iter: I) {
1355 self.extend_desugared(iter.into_iter());
1356 }
1357}
1358
1359impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1360 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1361 self.append(other);
1362 }
1363}
1364
1365impl<T: Ord> BinaryHeap<T> {
1366 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
54a0048b
SL
1367 let iterator = iter.into_iter();
1368 let (lower, _) = iterator.size_hint();
1a4d82fc
JJ
1369
1370 self.reserve(lower);
1371
532ac7d7 1372 iterator.for_each(move |elem| self.push(elem));
1a4d82fc
JJ
1373 }
1374}
62682a34
SL
1375
1376#[stable(feature = "extend_ref", since = "1.2.0")]
1377impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
92a42be0 1378 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
62682a34
SL
1379 self.extend(iter.into_iter().cloned());
1380 }
1381}