alloc/collections/binary_heap/mod.rs
1//! A priority queue implemented with a binary heap.
2//!
3//! Insertion and popping the largest element have *O*(log(*n*)) time complexity.
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
6//! converted to a sorted vector in-place, allowing it to be used for an *O*(*n* * log(*n*))
7//! in-place heapsort.
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].
13//! It shows how to use [`BinaryHeap`] with custom types.
14//!
15//! [dijkstra]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
16//! [sssp]: https://en.wikipedia.org/wiki/Shortest_path_problem
17//! [dir_graph]: https://en.wikipedia.org/wiki/Directed_graph
18//!
19//! ```
20//! use std::cmp::Ordering;
21//! use std::collections::BinaryHeap;
22//!
23//! #[derive(Copy, Clone, Eq, PartialEq)]
24//! struct State {
25//! cost: usize,
26//! position: usize,
27//! }
28//!
29//! // The priority queue depends on `Ord`.
30//! // Explicitly implement the trait so the queue becomes a min-heap
31//! // instead of a max-heap.
32//! impl Ord for State {
33//! fn cmp(&self, other: &Self) -> Ordering {
34//! // Notice that we flip the ordering on costs.
35//! // In case of a tie we compare positions - this step is necessary
36//! // to make implementations of `PartialEq` and `Ord` consistent.
37//! other.cost.cmp(&self.cost)
38//! .then_with(|| self.position.cmp(&other.position))
39//! }
40//! }
41//!
42//! // `PartialOrd` needs to be implemented as well.
43//! impl PartialOrd for State {
44//! fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
45//! Some(self.cmp(other))
46//! }
47//! }
48//!
49//! // Each node is represented as a `usize`, for a shorter implementation.
50//! struct Edge {
51//! node: usize,
52//! cost: usize,
53//! }
54//!
55//! // Dijkstra's shortest path algorithm.
56//!
57//! // Start at `start` and use `dist` to track the current shortest distance
58//! // to each node. This implementation isn't memory-efficient as it may leave duplicate
59//! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
60//! // for a simpler implementation.
61//! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
62//! // dist[node] = current shortest distance from `start` to `node`
63//! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
64//!
65//! let mut heap = BinaryHeap::new();
66//!
67//! // We're at `start`, with a zero cost
68//! dist[start] = 0;
69//! heap.push(State { cost: 0, position: start });
70//!
71//! // Examine the frontier with lower cost nodes first (min-heap)
72//! while let Some(State { cost, position }) = heap.pop() {
73//! // Alternatively we could have continued to find all shortest paths
74//! if position == goal { return Some(cost); }
75//!
76//! // Important as we may have already found a better way
77//! if cost > dist[position] { continue; }
78//!
79//! // For each node we can reach, see if we can find a way with
80//! // a lower cost going through this node
81//! for edge in &adj_list[position] {
82//! let next = State { cost: cost + edge.cost, position: edge.node };
83//!
84//! // If so, add it to the frontier and continue
85//! if next.cost < dist[next.position] {
86//! heap.push(next);
87//! // Relaxation, we have now found a better way
88//! dist[next.position] = next.cost;
89//! }
90//! }
91//! }
92//!
93//! // Goal not reachable
94//! None
95//! }
96//!
97//! fn main() {
98//! // This is the directed graph we're going to use.
99//! // The node numbers correspond to the different states,
100//! // and the edge weights symbolize the cost of moving
101//! // from one node to another.
102//! // Note that the edges are one-way.
103//! //
104//! // 7
105//! // +-----------------+
106//! // | |
107//! // v 1 2 | 2
108//! // 0 -----> 1 -----> 3 ---> 4
109//! // | ^ ^ ^
110//! // | | 1 | |
111//! // | | | 3 | 1
112//! // +------> 2 -------+ |
113//! // 10 | |
114//! // +---------------+
115//! //
116//! // The graph is represented as an adjacency list where each index,
117//! // corresponding to a node value, has a list of outgoing edges.
118//! // Chosen for its efficiency.
119//! let graph = vec![
120//! // Node 0
121//! vec![Edge { node: 2, cost: 10 },
122//! Edge { node: 1, cost: 1 }],
123//! // Node 1
124//! vec![Edge { node: 3, cost: 2 }],
125//! // Node 2
126//! vec![Edge { node: 1, cost: 1 },
127//! Edge { node: 3, cost: 3 },
128//! Edge { node: 4, cost: 1 }],
129//! // Node 3
130//! vec![Edge { node: 0, cost: 7 },
131//! Edge { node: 4, cost: 2 }],
132//! // Node 4
133//! vec![]];
134//!
135//! assert_eq!(shortest_path(&graph, 0, 1), Some(1));
136//! assert_eq!(shortest_path(&graph, 0, 3), Some(3));
137//! assert_eq!(shortest_path(&graph, 3, 0), Some(7));
138//! assert_eq!(shortest_path(&graph, 0, 4), Some(5));
139//! assert_eq!(shortest_path(&graph, 4, 0), None);
140//! }
141//! ```
142
143#![allow(missing_docs)]
144#![stable(feature = "rust1", since = "1.0.0")]
145
146use core::alloc::Allocator;
147use core::iter::{FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen};
148use core::mem::{DropGuard, ManuallyDrop, swap};
149use core::num::NonZero;
150use core::ops::{Deref, DerefMut};
151use core::{fmt, ptr};
152
153use crate::alloc::Global;
154use crate::collections::TryReserveError;
155use crate::slice;
156#[cfg(not(test))]
157use crate::vec::AsVecIntoIter;
158use crate::vec::{self, Vec};
159
160/// A priority queue implemented with a binary heap.
161///
162/// This will be a max-heap.
163///
164/// It is a logic error for an item to be modified in such a way that the
165/// item's ordering relative to any other item, as determined by the [`Ord`]
166/// trait, changes while it is in the heap. This is normally only possible
167/// through interior mutability, global state, I/O, or unsafe code. The
168/// behavior resulting from such a logic error is not specified, but will
169/// be encapsulated to the `BinaryHeap` that observed the logic error and not
170/// result in undefined behavior. This could include panics, incorrect results,
171/// aborts, memory leaks, and non-termination.
172///
173/// As long as no elements change their relative order while being in the heap
174/// as described above, the API of `BinaryHeap` guarantees that the heap
175/// invariant remains intact i.e. its methods all behave as documented. For
176/// example if a method is documented as iterating in sorted order, that's
177/// guaranteed to work as long as elements in the heap have not changed order,
178/// even in the presence of closures getting unwinded out of, iterators getting
179/// leaked, and similar foolishness.
180///
181/// # Examples
182///
183/// ```
184/// use std::collections::BinaryHeap;
185///
186/// // Type inference lets us omit an explicit type signature (which
187/// // would be `BinaryHeap<i32>` in this example).
188/// let mut heap = BinaryHeap::new();
189///
190/// // We can use peek to look at the next item in the heap. In this case,
191/// // there's no items in there yet so we get None.
192/// assert_eq!(heap.peek(), None);
193///
194/// // Let's add some scores...
195/// heap.push(1);
196/// heap.push(5);
197/// heap.push(2);
198///
199/// // Now peek shows the most important item in the heap.
200/// assert_eq!(heap.peek(), Some(&5));
201///
202/// // We can check the length of a heap.
203/// assert_eq!(heap.len(), 3);
204///
205/// // We can iterate over the items in the heap, although they are returned in
206/// // a random order.
207/// for x in &heap {
208/// println!("{x}");
209/// }
210///
211/// // If we instead pop these scores, they should come back in order.
212/// assert_eq!(heap.pop(), Some(5));
213/// assert_eq!(heap.pop(), Some(2));
214/// assert_eq!(heap.pop(), Some(1));
215/// assert_eq!(heap.pop(), None);
216///
217/// // We can clear the heap of any remaining items.
218/// heap.clear();
219///
220/// // The heap should now be empty.
221/// assert!(heap.is_empty())
222/// ```
223///
224/// A `BinaryHeap` with a known list of items can be initialized from an array:
225///
226/// ```
227/// use std::collections::BinaryHeap;
228///
229/// let heap = BinaryHeap::from([1, 5, 2]);
230/// ```
231///
232/// ## Min-heap
233///
234/// Either [`core::cmp::Reverse`] or a custom [`Ord`] implementation can be used to
235/// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest
236/// value instead of the greatest one.
237///
238/// ```
239/// use std::collections::BinaryHeap;
240/// use std::cmp::Reverse;
241///
242/// let mut heap = BinaryHeap::new();
243///
244/// // Wrap values in `Reverse`
245/// heap.push(Reverse(1));
246/// heap.push(Reverse(5));
247/// heap.push(Reverse(2));
248///
249/// // If we pop these scores now, they should come back in the reverse order.
250/// assert_eq!(heap.pop(), Some(Reverse(1)));
251/// assert_eq!(heap.pop(), Some(Reverse(2)));
252/// assert_eq!(heap.pop(), Some(Reverse(5)));
253/// assert_eq!(heap.pop(), None);
254/// ```
255///
256/// # Time complexity
257///
258/// | [push] | [pop] | [peek]/[peek\_mut] |
259/// |---------|---------------|--------------------|
260/// | *O*(1)~ | *O*(log(*n*)) | *O*(1) |
261///
262/// The value for `push` is an expected cost; the method documentation gives a
263/// more detailed analysis.
264///
265/// [`core::cmp::Reverse`]: core::cmp::Reverse
266/// [`Cell`]: core::cell::Cell
267/// [`RefCell`]: core::cell::RefCell
268/// [push]: BinaryHeap::push
269/// [pop]: BinaryHeap::pop
270/// [peek]: BinaryHeap::peek
271/// [peek\_mut]: BinaryHeap::peek_mut
272#[stable(feature = "rust1", since = "1.0.0")]
273#[cfg_attr(not(test), rustc_diagnostic_item = "BinaryHeap")]
274pub struct BinaryHeap<
275 T,
276 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
277> {
278 data: Vec<T, A>,
279}
280
281/// Structure wrapping a mutable reference to the greatest item on a
282/// `BinaryHeap`.
283///
284/// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
285/// its documentation for more.
286///
287/// [`peek_mut`]: BinaryHeap::peek_mut
288#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
289pub struct PeekMut<
290 'a,
291 T: 'a + Ord,
292 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
293> {
294 heap: &'a mut BinaryHeap<T, A>,
295 // If a set_len + sift_down are required, this is Some. If a &mut T has not
296 // yet been exposed to peek_mut()'s caller, it's None.
297 original_len: Option<NonZero<usize>>,
298}
299
300#[stable(feature = "collection_debug", since = "1.17.0")]
301impl<T: Ord + fmt::Debug, A: Allocator> fmt::Debug for PeekMut<'_, T, A> {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish()
304 }
305}
306
307#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
308impl<T: Ord, A: Allocator> Drop for PeekMut<'_, T, A> {
309 fn drop(&mut self) {
310 if let Some(original_len) = self.original_len {
311 // SAFETY: That's how many elements were in the Vec at the time of
312 // the PeekMut::deref_mut call, and therefore also at the time of
313 // the BinaryHeap::peek_mut call. Since the PeekMut did not end up
314 // getting leaked, we are now undoing the leak amplification that
315 // the DerefMut prepared for.
316 unsafe { self.heap.data.set_len(original_len.get()) };
317
318 // SAFETY: PeekMut is only instantiated for non-empty heaps.
319 unsafe { self.heap.sift_down(0) };
320 }
321 }
322}
323
324#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
325impl<T: Ord, A: Allocator> Deref for PeekMut<'_, T, A> {
326 type Target = T;
327 fn deref(&self) -> &T {
328 debug_assert!(!self.heap.is_empty());
329 // SAFETY: PeekMut is only instantiated for non-empty heaps
330 unsafe { self.heap.data.get_unchecked(0) }
331 }
332}
333
334#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
335impl<T: Ord, A: Allocator> DerefMut for PeekMut<'_, T, A> {
336 fn deref_mut(&mut self) -> &mut T {
337 debug_assert!(!self.heap.is_empty());
338
339 let len = self.heap.len();
340 if len > 1 {
341 // Here we preemptively leak all the rest of the underlying vector
342 // after the currently max element. If the caller mutates the &mut T
343 // we're about to give them, and then leaks the PeekMut, all these
344 // elements will remain leaked. If they don't leak the PeekMut, then
345 // either Drop or PeekMut::pop will un-leak the vector elements.
346 //
347 // This is technique is described throughout several other places in
348 // the standard library as "leak amplification".
349 // SAFETY: len > 1 so len != 0.
350 self.original_len = Some(unsafe { NonZero::new_unchecked(len) });
351 // SAFETY: len > 1 so all this does for now is leak elements,
352 // which is safe.
353 unsafe { self.heap.data.set_len(1) };
354 }
355
356 // SAFETY: PeekMut is only instantiated for non-empty heaps
357 unsafe { self.heap.data.get_unchecked_mut(0) }
358 }
359}
360
361impl<'a, T: Ord, A: Allocator> PeekMut<'a, T, A> {
362 /// Sifts the current element to its new position.
363 ///
364 /// Afterwards refers to the new element. Returns if the element changed.
365 ///
366 /// ## Examples
367 ///
368 /// The condition can be used to upper bound all elements in the heap. When only few elements
369 /// are affected, the heap's sort ensures this is faster than a reconstruction from the raw
370 /// element list and requires no additional allocation.
371 ///
372 /// ```
373 /// #![feature(binary_heap_peek_mut_refresh)]
374 /// use std::collections::BinaryHeap;
375 ///
376 /// let mut heap: BinaryHeap<u32> = (0..128).collect();
377 /// let mut peek = heap.peek_mut().unwrap();
378 ///
379 /// loop {
380 /// *peek = 99;
381 ///
382 /// if !peek.refresh() {
383 /// break;
384 /// }
385 /// }
386 ///
387 /// // Post condition, this is now an upper bound.
388 /// assert!(*peek < 100);
389 /// ```
390 ///
391 /// When the element remains the maximum after modification, the peek remains unchanged:
392 ///
393 /// ```
394 /// #![feature(binary_heap_peek_mut_refresh)]
395 /// use std::collections::BinaryHeap;
396 ///
397 /// let mut heap: BinaryHeap<u32> = [1, 2, 3].into();
398 /// let mut peek = heap.peek_mut().unwrap();
399 ///
400 /// assert_eq!(*peek, 3);
401 /// *peek = 42;
402 ///
403 /// // When we refresh, the peek is updated to the new maximum.
404 /// assert!(!peek.refresh(), "42 is even larger than 3");
405 /// assert_eq!(*peek, 42);
406 /// ```
407 #[unstable(feature = "binary_heap_peek_mut_refresh", issue = "138355")]
408 #[must_use = "is equivalent to dropping and getting a new PeekMut except for return information"]
409 pub fn refresh(&mut self) -> bool {
410 // The length of the underlying heap is unchanged by sifting down. The value stored for leak
411 // amplification thus remains accurate. We erase the leak amplification firstly because the
412 // operation is then equivalent to constructing a new PeekMut and secondly this avoids any
413 // future complication where original_len being non-empty would be interpreted as the heap
414 // having been leak amplified instead of checking the heap itself.
415 if let Some(original_len) = self.original_len.take() {
416 // SAFETY: This is how many elements were in the Vec at the time of
417 // the BinaryHeap::peek_mut call.
418 unsafe { self.heap.data.set_len(original_len.get()) };
419
420 // The length of the heap did not change by sifting, upholding our own invariants.
421
422 // SAFETY: PeekMut is only instantiated for non-empty heaps.
423 (unsafe { self.heap.sift_down(0) }) != 0
424 } else {
425 // The element was not modified.
426 false
427 }
428 }
429
430 /// Removes the peeked value from the heap and returns it.
431 #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
432 pub fn pop(mut this: PeekMut<'a, T, A>) -> T {
433 if let Some(original_len) = this.original_len.take() {
434 // SAFETY: This is how many elements were in the Vec at the time of
435 // the BinaryHeap::peek_mut call.
436 unsafe { this.heap.data.set_len(original_len.get()) };
437
438 // Unlike in Drop, here we don't also need to do a sift_down even if
439 // the caller could've mutated the element. It is removed from the
440 // heap on the next line and pop() is not sensitive to its value.
441 }
442
443 // SAFETY: Have a `PeekMut` element proves that the associated binary heap being non-empty,
444 // so the `pop` operation will not fail.
445 unsafe { this.heap.pop().unwrap_unchecked() }
446 }
447}
448
449#[stable(feature = "rust1", since = "1.0.0")]
450impl<T: Clone, A: Allocator + Clone> Clone for BinaryHeap<T, A> {
451 fn clone(&self) -> Self {
452 BinaryHeap { data: self.data.clone() }
453 }
454
455 /// Overwrites the contents of `self` with a clone of the contents of `source`.
456 ///
457 /// This method is preferred over simply assigning `source.clone()` to `self`,
458 /// as it avoids reallocation if possible.
459 ///
460 /// See [`Vec::clone_from()`] for more details.
461 fn clone_from(&mut self, source: &Self) {
462 self.data.clone_from(&source.data);
463 }
464}
465
466#[stable(feature = "rust1", since = "1.0.0")]
467impl<T> Default for BinaryHeap<T> {
468 /// Creates an empty `BinaryHeap<T>`.
469 #[inline]
470 fn default() -> BinaryHeap<T> {
471 BinaryHeap::new()
472 }
473}
474
475#[stable(feature = "binaryheap_debug", since = "1.4.0")]
476impl<T: fmt::Debug, A: Allocator> fmt::Debug for BinaryHeap<T, A> {
477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478 f.debug_list().entries(self.iter()).finish()
479 }
480}
481
482struct RebuildOnDrop<
483 'a,
484 T: Ord,
485 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
486> {
487 heap: &'a mut BinaryHeap<T, A>,
488 rebuild_from: usize,
489}
490
491impl<T: Ord, A: Allocator> Drop for RebuildOnDrop<'_, T, A> {
492 fn drop(&mut self) {
493 self.heap.rebuild_tail(self.rebuild_from);
494 }
495}
496
497impl<T> BinaryHeap<T> {
498 /// Creates an empty `BinaryHeap` as a max-heap.
499 ///
500 /// # Examples
501 ///
502 /// Basic usage:
503 ///
504 /// ```
505 /// use std::collections::BinaryHeap;
506 /// let mut heap = BinaryHeap::new();
507 /// heap.push(4);
508 /// ```
509 #[stable(feature = "rust1", since = "1.0.0")]
510 #[rustc_const_stable(feature = "const_binary_heap_constructor", since = "1.80.0")]
511 #[must_use]
512 pub const fn new() -> BinaryHeap<T> {
513 BinaryHeap { data: vec![] }
514 }
515
516 /// Creates an empty `BinaryHeap` with at least the specified capacity.
517 ///
518 /// The binary heap will be able to hold at least `capacity` elements without
519 /// reallocating. This method is allowed to allocate for more elements than
520 /// `capacity`. If `capacity` is zero, the binary heap will not allocate.
521 ///
522 /// # Examples
523 ///
524 /// Basic usage:
525 ///
526 /// ```
527 /// use std::collections::BinaryHeap;
528 /// let mut heap = BinaryHeap::with_capacity(10);
529 /// heap.push(4);
530 /// ```
531 #[stable(feature = "rust1", since = "1.0.0")]
532 #[must_use]
533 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
534 BinaryHeap { data: Vec::with_capacity(capacity) }
535 }
536}
537
538impl<T, A: Allocator> BinaryHeap<T, A> {
539 /// Creates an empty `BinaryHeap` as a max-heap, using `A` as allocator.
540 ///
541 /// # Examples
542 ///
543 /// Basic usage:
544 ///
545 /// ```
546 /// #![feature(allocator_api)]
547 ///
548 /// use std::alloc::System;
549 /// use std::collections::BinaryHeap;
550 ///
551 /// let heap : BinaryHeap<i32, System> = BinaryHeap::new_in(System);
552 /// ```
553 #[unstable(feature = "allocator_api", issue = "32838")]
554 #[must_use]
555 pub const fn new_in(alloc: A) -> BinaryHeap<T, A> {
556 BinaryHeap { data: Vec::new_in(alloc) }
557 }
558
559 /// Creates an empty `BinaryHeap` with at least the specified capacity, using `A` as allocator.
560 ///
561 /// The binary heap will be able to hold at least `capacity` elements without
562 /// reallocating. This method is allowed to allocate for more elements than
563 /// `capacity`. If `capacity` is zero, the binary heap will not allocate.
564 ///
565 /// # Examples
566 ///
567 /// Basic usage:
568 ///
569 /// ```
570 /// #![feature(allocator_api)]
571 ///
572 /// use std::alloc::System;
573 /// use std::collections::BinaryHeap;
574 ///
575 /// let heap: BinaryHeap<i32, System> = BinaryHeap::with_capacity_in(10, System);
576 /// ```
577 #[unstable(feature = "allocator_api", issue = "32838")]
578 #[must_use]
579 pub fn with_capacity_in(capacity: usize, alloc: A) -> BinaryHeap<T, A> {
580 BinaryHeap { data: Vec::with_capacity_in(capacity, alloc) }
581 }
582
583 /// Creates a `BinaryHeap` using the supplied `vec`. This does not rebuild the heap,
584 /// so `vec` must already be a max-heap.
585 ///
586 /// # Safety
587 ///
588 /// The supplied `vec` must be a max-heap, i.e. for all indices `0 < i < vec.len()`,
589 /// `vec[(i - 1) / 2] >= vec[i]`.
590 ///
591 /// # Examples
592 ///
593 /// Basic usage:
594 ///
595 /// ```
596 /// #![feature(binary_heap_from_raw_vec)]
597 ///
598 /// use std::collections::BinaryHeap;
599 /// let heap = BinaryHeap::from([1, 2, 3]);
600 /// let vec = heap.into_vec();
601 ///
602 /// // Safety: vec is the output of heap.from_vec(), so is a max-heap.
603 /// let mut new_heap = unsafe {
604 /// BinaryHeap::from_raw_vec(vec)
605 /// };
606 /// assert_eq!(new_heap.pop(), Some(3));
607 /// assert_eq!(new_heap.pop(), Some(2));
608 /// assert_eq!(new_heap.pop(), Some(1));
609 /// assert_eq!(new_heap.pop(), None);
610 /// ```
611 #[unstable(feature = "binary_heap_from_raw_vec", issue = "152500")]
612 #[must_use]
613 pub unsafe fn from_raw_vec(vec: Vec<T, A>) -> BinaryHeap<T, A> {
614 BinaryHeap { data: vec }
615 }
616}
617
618impl<T: Ord, A: Allocator> BinaryHeap<T, A> {
619 /// Returns a mutable reference to the greatest item in the binary heap, or
620 /// `None` if it is empty.
621 ///
622 /// Note: If the `PeekMut` value is leaked, some heap elements might get
623 /// leaked along with it, but the remaining elements will remain a valid
624 /// heap.
625 ///
626 /// # Examples
627 ///
628 /// Basic usage:
629 ///
630 /// ```
631 /// use std::collections::BinaryHeap;
632 /// let mut heap = BinaryHeap::new();
633 /// assert!(heap.peek_mut().is_none());
634 ///
635 /// heap.push(1);
636 /// heap.push(5);
637 /// heap.push(2);
638 /// if let Some(mut val) = heap.peek_mut() {
639 /// *val = 0;
640 /// }
641 /// assert_eq!(heap.peek(), Some(&2));
642 /// ```
643 ///
644 /// # Time complexity
645 ///
646 /// If the item is modified then the worst case time complexity is *O*(log(*n*)),
647 /// otherwise it's *O*(1).
648 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
649 pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, A>> {
650 if self.is_empty() { None } else { Some(PeekMut { heap: self, original_len: None }) }
651 }
652
653 /// Removes the greatest item from the binary heap and returns it, or `None` if it
654 /// is empty.
655 ///
656 /// # Examples
657 ///
658 /// Basic usage:
659 ///
660 /// ```
661 /// use std::collections::BinaryHeap;
662 /// let mut heap = BinaryHeap::from([1, 3]);
663 ///
664 /// assert_eq!(heap.pop(), Some(3));
665 /// assert_eq!(heap.pop(), Some(1));
666 /// assert_eq!(heap.pop(), None);
667 /// ```
668 ///
669 /// # Time complexity
670 ///
671 /// The worst case cost of `pop` on a heap containing *n* elements is *O*(log(*n*)).
672 #[stable(feature = "rust1", since = "1.0.0")]
673 pub fn pop(&mut self) -> Option<T> {
674 self.data.pop().map(|mut item| {
675 if !self.is_empty() {
676 swap(&mut item, &mut self.data[0]);
677 // SAFETY: !self.is_empty() means that self.len() > 0
678 unsafe { self.sift_down_to_bottom(0) };
679 }
680 item
681 })
682 }
683
684 /// Removes and returns the greatest item from the binary heap if the predicate
685 /// returns `true`, or [`None`] if the predicate returns false or the heap
686 /// is empty (the predicate will not be called in that case).
687 ///
688 /// # Examples
689 ///
690 /// ```
691 /// #![feature(binary_heap_pop_if)]
692 /// use std::collections::BinaryHeap;
693 /// let mut heap = BinaryHeap::from([1, 2]);
694 /// let pred = |x: &i32| *x % 2 == 0;
695 ///
696 /// assert_eq!(heap.pop_if(pred), Some(2));
697 /// assert_eq!(heap.as_slice(), [1]);
698 /// assert_eq!(heap.pop_if(pred), None);
699 /// assert_eq!(heap.as_slice(), [1]);
700 /// ```
701 ///
702 /// # Time complexity
703 ///
704 /// The worst case cost of `pop_if` on a heap containing *n* elements is *O*(log(*n*)).
705 #[unstable(feature = "binary_heap_pop_if", issue = "151828")]
706 pub fn pop_if(&mut self, predicate: impl FnOnce(&T) -> bool) -> Option<T> {
707 let first = self.peek()?;
708 if predicate(first) { self.pop() } else { None }
709 }
710
711 /// Pushes an item onto the binary heap.
712 ///
713 /// # Examples
714 ///
715 /// Basic usage:
716 ///
717 /// ```
718 /// use std::collections::BinaryHeap;
719 /// let mut heap = BinaryHeap::new();
720 /// heap.push(3);
721 /// heap.push(5);
722 /// heap.push(1);
723 ///
724 /// assert_eq!(heap.len(), 3);
725 /// assert_eq!(heap.peek(), Some(&5));
726 /// ```
727 ///
728 /// # Time complexity
729 ///
730 /// The expected cost of `push`, averaged over every possible ordering of
731 /// the elements being pushed, and over a sufficiently large number of
732 /// pushes, is *O*(1). This is the most meaningful cost metric when pushing
733 /// elements that are *not* already in any sorted pattern.
734 ///
735 /// The time complexity degrades if elements are pushed in predominantly
736 /// ascending order. In the worst case, elements are pushed in ascending
737 /// sorted order and the amortized cost per push is *O*(log(*n*)) against a heap
738 /// containing *n* elements.
739 ///
740 /// The worst case cost of a *single* call to `push` is *O*(*n*). The worst case
741 /// occurs when capacity is exhausted and needs a resize. The resize cost
742 /// has been amortized in the previous figures.
743 #[stable(feature = "rust1", since = "1.0.0")]
744 #[rustc_confusables("append", "put")]
745 pub fn push(&mut self, item: T) {
746 let old_len = self.len();
747 self.data.push(item);
748 // SAFETY: Since we pushed a new item it means that
749 // old_len = self.len() - 1 < self.len()
750 unsafe { self.sift_up(0, old_len) };
751 }
752
753 /// Consumes the `BinaryHeap` and returns a vector in sorted
754 /// (ascending) order.
755 ///
756 /// # Examples
757 ///
758 /// Basic usage:
759 ///
760 /// ```
761 /// use std::collections::BinaryHeap;
762 ///
763 /// let mut heap = BinaryHeap::from([1, 2, 4, 5, 7]);
764 /// heap.push(6);
765 /// heap.push(3);
766 ///
767 /// let vec = heap.into_sorted_vec();
768 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
769 /// ```
770 #[must_use = "`self` will be dropped if the result is not used"]
771 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
772 pub fn into_sorted_vec(mut self) -> Vec<T, A> {
773 let mut end = self.len();
774 while end > 1 {
775 end -= 1;
776 // SAFETY: `end` goes from `self.len() - 1` to 1 (both included),
777 // so it's always a valid index to access.
778 // It is safe to access index 0 (i.e. `ptr`), because
779 // 1 <= end < self.len(), which means self.len() >= 2.
780 unsafe {
781 let ptr = self.data.as_mut_ptr();
782 ptr::swap(ptr, ptr.add(end));
783 }
784 // SAFETY: `end` goes from `self.len() - 1` to 1 (both included) so:
785 // 0 < 1 <= end <= self.len() - 1 < self.len()
786 // Which means 0 < end and end < self.len().
787 unsafe { self.sift_down_range(0, end) };
788 }
789 self.into_vec()
790 }
791
792 // The implementations of sift_up and sift_down use unsafe blocks in
793 // order to move an element out of the vector (leaving behind a
794 // hole), shift along the others and move the removed element back into the
795 // vector at the final location of the hole.
796 // The `Hole` type is used to represent this, and make sure
797 // the hole is filled back at the end of its scope, even on panic.
798 // Using a hole reduces the constant factor compared to using swaps,
799 // which involves twice as many moves.
800
801 /// # Safety
802 ///
803 /// The caller must guarantee that `pos < self.len()`.
804 ///
805 /// Returns the new position of the element.
806 unsafe fn sift_up(&mut self, start: usize, pos: usize) -> usize {
807 // Take out the value at `pos` and create a hole.
808 // SAFETY: The caller guarantees that pos < self.len()
809 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
810
811 while hole.pos() > start {
812 let parent = (hole.pos() - 1) / 2;
813
814 // SAFETY: hole.pos() > start >= 0, which means hole.pos() > 0
815 // and so hole.pos() - 1 can't underflow.
816 // This guarantees that parent < hole.pos() so
817 // it's a valid index and also != hole.pos().
818 if hole.element() <= unsafe { hole.get(parent) } {
819 break;
820 }
821
822 // SAFETY: Same as above
823 unsafe { hole.move_to(parent) };
824 }
825
826 hole.pos()
827 }
828
829 /// Take an element at `pos` and move it down the heap,
830 /// while its children are larger.
831 ///
832 /// Returns the new position of the element.
833 ///
834 /// # Safety
835 ///
836 /// The caller must guarantee that `pos < end <= self.len()`.
837 unsafe fn sift_down_range(&mut self, pos: usize, end: usize) -> usize {
838 // SAFETY: The caller guarantees that pos < end <= self.len().
839 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
840 let mut child = 2 * hole.pos() + 1;
841
842 // Loop invariant: child == 2 * hole.pos() + 1.
843 while child <= end.saturating_sub(2) {
844 // compare with the greater of the two children
845 // SAFETY: child < end - 1 < self.len() and
846 // child + 1 < end <= self.len(), so they're valid indexes.
847 // child == 2 * hole.pos() + 1 != hole.pos() and
848 // child + 1 == 2 * hole.pos() + 2 != hole.pos().
849 // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
850 // if T is a ZST
851 child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
852
853 // if we are already in order, stop.
854 // SAFETY: child is now either the old child or the old child+1
855 // We already proven that both are < self.len() and != hole.pos()
856 if hole.element() >= unsafe { hole.get(child) } {
857 return hole.pos();
858 }
859
860 // SAFETY: same as above.
861 unsafe { hole.move_to(child) };
862 child = 2 * hole.pos() + 1;
863 }
864
865 // SAFETY: && short circuit, which means that in the
866 // second condition it's already true that child == end - 1 < self.len().
867 if child == end - 1 && hole.element() < unsafe { hole.get(child) } {
868 // SAFETY: child is already proven to be a valid index and
869 // child == 2 * hole.pos() + 1 != hole.pos().
870 unsafe { hole.move_to(child) };
871 }
872
873 hole.pos()
874 }
875
876 /// # Safety
877 ///
878 /// The caller must guarantee that `pos < self.len()`.
879 unsafe fn sift_down(&mut self, pos: usize) -> usize {
880 let len = self.len();
881 // SAFETY: pos < len is guaranteed by the caller and
882 // obviously len = self.len() <= self.len().
883 unsafe { self.sift_down_range(pos, len) }
884 }
885
886 /// Take an element at `pos` and move it all the way down the heap,
887 /// then sift it up to its position.
888 ///
889 /// Note: This is faster when the element is known to be large / should
890 /// be closer to the bottom.
891 ///
892 /// # Safety
893 ///
894 /// The caller must guarantee that `pos < self.len()`.
895 unsafe fn sift_down_to_bottom(&mut self, mut pos: usize) {
896 let end = self.len();
897 let start = pos;
898
899 // SAFETY: The caller guarantees that pos < self.len().
900 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
901 let mut child = 2 * hole.pos() + 1;
902
903 // Loop invariant: child == 2 * hole.pos() + 1.
904 while child <= end.saturating_sub(2) {
905 // SAFETY: child < end - 1 < self.len() and
906 // child + 1 < end <= self.len(), so they're valid indexes.
907 // child == 2 * hole.pos() + 1 != hole.pos() and
908 // child + 1 == 2 * hole.pos() + 2 != hole.pos().
909 // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
910 // if T is a ZST
911 child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
912
913 // SAFETY: Same as above
914 unsafe { hole.move_to(child) };
915 child = 2 * hole.pos() + 1;
916 }
917
918 if child == end - 1 {
919 // SAFETY: child == end - 1 < self.len(), so it's a valid index
920 // and child == 2 * hole.pos() + 1 != hole.pos().
921 unsafe { hole.move_to(child) };
922 }
923 pos = hole.pos();
924 drop(hole);
925
926 // SAFETY: pos is the position in the hole and was already proven
927 // to be a valid index.
928 unsafe { self.sift_up(start, pos) };
929 }
930
931 /// Rebuild assuming data[0..start] is still a proper heap.
932 fn rebuild_tail(&mut self, start: usize) {
933 if start == self.len() {
934 return;
935 }
936
937 let tail_len = self.len() - start;
938
939 #[inline(always)]
940 fn log2_fast(x: usize) -> usize {
941 (usize::BITS - x.leading_zeros() - 1) as usize
942 }
943
944 // `rebuild` takes O(self.len()) operations
945 // and about 2 * self.len() comparisons in the worst case
946 // while repeating `sift_up` takes O(tail_len * log(start)) operations
947 // and about 1 * tail_len * log_2(start) comparisons in the worst case,
948 // assuming start >= tail_len. For larger heaps, the crossover point
949 // no longer follows this reasoning and was determined empirically.
950 let better_to_rebuild = if start < tail_len {
951 true
952 } else if self.len() <= 2048 {
953 2 * self.len() < tail_len * log2_fast(start)
954 } else {
955 2 * self.len() < tail_len * 11
956 };
957
958 if better_to_rebuild {
959 self.rebuild();
960 } else {
961 for i in start..self.len() {
962 // SAFETY: The index `i` is always less than self.len().
963 unsafe { self.sift_up(0, i) };
964 }
965 }
966 }
967
968 fn rebuild(&mut self) {
969 let mut n = self.len() / 2;
970 while n > 0 {
971 n -= 1;
972 // SAFETY: n starts from self.len() / 2 and goes down to 0.
973 // The only case when !(n < self.len()) is if
974 // self.len() == 0, but it's ruled out by the loop condition.
975 unsafe { self.sift_down(n) };
976 }
977 }
978
979 /// Moves all the elements of `other` into `self`, leaving `other` empty.
980 ///
981 /// # Examples
982 ///
983 /// Basic usage:
984 ///
985 /// ```
986 /// use std::collections::BinaryHeap;
987 ///
988 /// let mut a = BinaryHeap::from([-10, 1, 2, 3, 3]);
989 /// let mut b = BinaryHeap::from([-20, 5, 43]);
990 ///
991 /// a.append(&mut b);
992 ///
993 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
994 /// assert!(b.is_empty());
995 /// ```
996 #[stable(feature = "binary_heap_append", since = "1.11.0")]
997 pub fn append(&mut self, other: &mut Self) {
998 if self.len() < other.len() {
999 swap(self, other);
1000 }
1001
1002 let start = self.data.len();
1003
1004 self.data.append(&mut other.data);
1005
1006 self.rebuild_tail(start);
1007 }
1008
1009 /// Clears the binary heap, returning an iterator over the removed elements
1010 /// in heap order. If the iterator is dropped before being fully consumed,
1011 /// it drops the remaining elements in heap order.
1012 ///
1013 /// The returned iterator keeps a mutable borrow on the heap to optimize
1014 /// its implementation.
1015 ///
1016 /// Note:
1017 /// * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`.
1018 /// You should use the latter for most cases.
1019 ///
1020 /// # Examples
1021 ///
1022 /// Basic usage:
1023 ///
1024 /// ```
1025 /// #![feature(binary_heap_drain_sorted)]
1026 /// use std::collections::BinaryHeap;
1027 ///
1028 /// let mut heap = BinaryHeap::from([1, 2, 3, 4, 5]);
1029 /// assert_eq!(heap.len(), 5);
1030 ///
1031 /// drop(heap.drain_sorted()); // removes all elements in heap order
1032 /// assert_eq!(heap.len(), 0);
1033 /// ```
1034 #[inline]
1035 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1036 pub fn drain_sorted(&mut self) -> DrainSorted<'_, T, A> {
1037 DrainSorted { inner: self }
1038 }
1039
1040 /// Retains only the elements specified by the predicate.
1041 ///
1042 /// In other words, remove all elements `e` for which `f(&e)` returns
1043 /// `false`. The elements are visited in unsorted (and unspecified) order.
1044 ///
1045 /// # Examples
1046 ///
1047 /// Basic usage:
1048 ///
1049 /// ```
1050 /// use std::collections::BinaryHeap;
1051 ///
1052 /// let mut heap = BinaryHeap::from([-10, -5, 1, 2, 4, 13]);
1053 ///
1054 /// heap.retain(|x| x % 2 == 0); // only keep even numbers
1055 ///
1056 /// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
1057 /// ```
1058 #[stable(feature = "binary_heap_retain", since = "1.70.0")]
1059 pub fn retain<F>(&mut self, mut f: F)
1060 where
1061 F: FnMut(&T) -> bool,
1062 {
1063 // rebuild_start will be updated to the first touched element below, and the rebuild will
1064 // only be done for the tail.
1065 let mut guard = RebuildOnDrop { rebuild_from: self.len(), heap: self };
1066 let mut i = 0;
1067
1068 guard.heap.data.retain(|e| {
1069 let keep = f(e);
1070 if !keep && i < guard.rebuild_from {
1071 guard.rebuild_from = i;
1072 }
1073 i += 1;
1074 keep
1075 });
1076 }
1077}
1078
1079impl<T, A: Allocator> BinaryHeap<T, A> {
1080 /// Returns an iterator visiting all values in the underlying vector, in
1081 /// arbitrary order.
1082 ///
1083 /// # Examples
1084 ///
1085 /// Basic usage:
1086 ///
1087 /// ```
1088 /// use std::collections::BinaryHeap;
1089 /// let heap = BinaryHeap::from([1, 2, 3, 4]);
1090 ///
1091 /// // Print 1, 2, 3, 4 in arbitrary order
1092 /// for x in heap.iter() {
1093 /// println!("{x}");
1094 /// }
1095 /// ```
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 #[cfg_attr(not(test), rustc_diagnostic_item = "binaryheap_iter")]
1098 pub fn iter(&self) -> Iter<'_, T> {
1099 Iter { iter: self.data.iter() }
1100 }
1101
1102 /// Returns an iterator which retrieves elements in heap order.
1103 ///
1104 /// This method consumes the original heap.
1105 ///
1106 /// # Examples
1107 ///
1108 /// Basic usage:
1109 ///
1110 /// ```
1111 /// #![feature(binary_heap_into_iter_sorted)]
1112 /// use std::collections::BinaryHeap;
1113 /// let heap = BinaryHeap::from([1, 2, 3, 4, 5]);
1114 ///
1115 /// assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), [5, 4]);
1116 /// ```
1117 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1118 pub fn into_iter_sorted(self) -> IntoIterSorted<T, A> {
1119 IntoIterSorted { inner: self }
1120 }
1121
1122 /// Returns the greatest item in the binary heap, or `None` if it is empty.
1123 ///
1124 /// # Examples
1125 ///
1126 /// Basic usage:
1127 ///
1128 /// ```
1129 /// use std::collections::BinaryHeap;
1130 /// let mut heap = BinaryHeap::new();
1131 /// assert_eq!(heap.peek(), None);
1132 ///
1133 /// heap.push(1);
1134 /// heap.push(5);
1135 /// heap.push(2);
1136 /// assert_eq!(heap.peek(), Some(&5));
1137 ///
1138 /// ```
1139 ///
1140 /// # Time complexity
1141 ///
1142 /// Cost is *O*(1) in the worst case.
1143 #[must_use]
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 pub fn peek(&self) -> Option<&T> {
1146 self.data.get(0)
1147 }
1148
1149 /// Returns the number of elements the binary heap can hold without reallocating.
1150 ///
1151 /// # Examples
1152 ///
1153 /// Basic usage:
1154 ///
1155 /// ```
1156 /// use std::collections::BinaryHeap;
1157 /// let mut heap = BinaryHeap::with_capacity(100);
1158 /// assert!(heap.capacity() >= 100);
1159 /// heap.push(4);
1160 /// ```
1161 #[must_use]
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 pub fn capacity(&self) -> usize {
1164 self.data.capacity()
1165 }
1166
1167 /// Reserves the minimum capacity for at least `additional` elements more than
1168 /// the current length. Unlike [`reserve`], this will not
1169 /// deliberately over-allocate to speculatively avoid frequent allocations.
1170 /// After calling `reserve_exact`, capacity will be greater than or equal to
1171 /// `self.len() + additional`. Does nothing if the capacity is already
1172 /// sufficient.
1173 ///
1174 /// [`reserve`]: BinaryHeap::reserve
1175 ///
1176 /// # Panics
1177 ///
1178 /// Panics if the new capacity overflows [`usize`].
1179 ///
1180 /// # Examples
1181 ///
1182 /// Basic usage:
1183 ///
1184 /// ```
1185 /// use std::collections::BinaryHeap;
1186 /// let mut heap = BinaryHeap::new();
1187 /// heap.reserve_exact(100);
1188 /// assert!(heap.capacity() >= 100);
1189 /// heap.push(4);
1190 /// ```
1191 ///
1192 /// [`reserve`]: BinaryHeap::reserve
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 pub fn reserve_exact(&mut self, additional: usize) {
1195 self.data.reserve_exact(additional);
1196 }
1197
1198 /// Reserves capacity for at least `additional` elements more than the
1199 /// current length. The allocator may reserve more space to speculatively
1200 /// avoid frequent allocations. After calling `reserve`,
1201 /// capacity will be greater than or equal to `self.len() + additional`.
1202 /// Does nothing if capacity is already sufficient.
1203 ///
1204 /// # Panics
1205 ///
1206 /// Panics if the new capacity overflows [`usize`].
1207 ///
1208 /// # Examples
1209 ///
1210 /// Basic usage:
1211 ///
1212 /// ```
1213 /// use std::collections::BinaryHeap;
1214 /// let mut heap = BinaryHeap::new();
1215 /// heap.reserve(100);
1216 /// assert!(heap.capacity() >= 100);
1217 /// heap.push(4);
1218 /// ```
1219 #[stable(feature = "rust1", since = "1.0.0")]
1220 pub fn reserve(&mut self, additional: usize) {
1221 self.data.reserve(additional);
1222 }
1223
1224 /// Tries to reserve the minimum capacity for at least `additional` elements
1225 /// more than the current length. Unlike [`try_reserve`], this will not
1226 /// deliberately over-allocate to speculatively avoid frequent allocations.
1227 /// After calling `try_reserve_exact`, capacity will be greater than or
1228 /// equal to `self.len() + additional` if it returns `Ok(())`.
1229 /// Does nothing if the capacity is already sufficient.
1230 ///
1231 /// Note that the allocator may give the collection more space than it
1232 /// requests. Therefore, capacity can not be relied upon to be precisely
1233 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1234 ///
1235 /// [`try_reserve`]: BinaryHeap::try_reserve
1236 ///
1237 /// # Errors
1238 ///
1239 /// If the capacity overflows, or the allocator reports a failure, then an error
1240 /// is returned.
1241 ///
1242 /// # Examples
1243 ///
1244 /// ```
1245 /// use std::collections::BinaryHeap;
1246 /// use std::collections::TryReserveError;
1247 ///
1248 /// fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
1249 /// let mut heap = BinaryHeap::new();
1250 ///
1251 /// // Pre-reserve the memory, exiting if we can't
1252 /// heap.try_reserve_exact(data.len())?;
1253 ///
1254 /// // Now we know this can't OOM in the middle of our complex work
1255 /// heap.extend(data.iter());
1256 ///
1257 /// Ok(heap.pop())
1258 /// }
1259 /// # find_max_slow(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1260 /// ```
1261 #[stable(feature = "try_reserve_2", since = "1.63.0")]
1262 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1263 self.data.try_reserve_exact(additional)
1264 }
1265
1266 /// Tries to reserve capacity for at least `additional` elements more than the
1267 /// current length. The allocator may reserve more space to speculatively
1268 /// avoid frequent allocations. After calling `try_reserve`, capacity will be
1269 /// greater than or equal to `self.len() + additional` if it returns
1270 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1271 /// preserves the contents even if an error occurs.
1272 ///
1273 /// # Errors
1274 ///
1275 /// If the capacity overflows, or the allocator reports a failure, then an error
1276 /// is returned.
1277 ///
1278 /// # Examples
1279 ///
1280 /// ```
1281 /// use std::collections::BinaryHeap;
1282 /// use std::collections::TryReserveError;
1283 ///
1284 /// fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
1285 /// let mut heap = BinaryHeap::new();
1286 ///
1287 /// // Pre-reserve the memory, exiting if we can't
1288 /// heap.try_reserve(data.len())?;
1289 ///
1290 /// // Now we know this can't OOM in the middle of our complex work
1291 /// heap.extend(data.iter());
1292 ///
1293 /// Ok(heap.pop())
1294 /// }
1295 /// # find_max_slow(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1296 /// ```
1297 #[stable(feature = "try_reserve_2", since = "1.63.0")]
1298 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1299 self.data.try_reserve(additional)
1300 }
1301
1302 /// Discards as much additional capacity as possible.
1303 ///
1304 /// # Examples
1305 ///
1306 /// Basic usage:
1307 ///
1308 /// ```
1309 /// use std::collections::BinaryHeap;
1310 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
1311 ///
1312 /// assert!(heap.capacity() >= 100);
1313 /// heap.shrink_to_fit();
1314 /// assert!(heap.capacity() == 0);
1315 /// ```
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 pub fn shrink_to_fit(&mut self) {
1318 self.data.shrink_to_fit();
1319 }
1320
1321 /// Discards capacity with a lower bound.
1322 ///
1323 /// The capacity will remain at least as large as both the length
1324 /// and the supplied value.
1325 ///
1326 /// If the current capacity is less than the lower limit, this is a no-op.
1327 ///
1328 /// # Examples
1329 ///
1330 /// ```
1331 /// use std::collections::BinaryHeap;
1332 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
1333 ///
1334 /// assert!(heap.capacity() >= 100);
1335 /// heap.shrink_to(10);
1336 /// assert!(heap.capacity() >= 10);
1337 /// ```
1338 #[inline]
1339 #[stable(feature = "shrink_to", since = "1.56.0")]
1340 pub fn shrink_to(&mut self, min_capacity: usize) {
1341 self.data.shrink_to(min_capacity)
1342 }
1343
1344 /// Returns a slice of all values in the underlying vector, in arbitrary
1345 /// order.
1346 ///
1347 /// # Examples
1348 ///
1349 /// Basic usage:
1350 ///
1351 /// ```
1352 /// use std::collections::BinaryHeap;
1353 /// use std::io::{self, Write};
1354 ///
1355 /// let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
1356 ///
1357 /// io::sink().write(heap.as_slice()).unwrap();
1358 /// ```
1359 #[must_use]
1360 #[stable(feature = "binary_heap_as_slice", since = "1.80.0")]
1361 pub fn as_slice(&self) -> &[T] {
1362 self.data.as_slice()
1363 }
1364
1365 /// Returns a mutable slice of all values in the underlying vector.
1366 ///
1367 /// # Safety
1368 ///
1369 /// The caller must ensure that the slice remains a max-heap, i.e. for all indices
1370 /// `0 < i < slice.len()`, `slice[(i - 1) / 2] >= slice[i]`, before the borrow ends
1371 /// and the binary heap is used.
1372 ///
1373 /// # Examples
1374 ///
1375 /// Basic usage:
1376 ///
1377 /// ```
1378 /// #![feature(binary_heap_as_mut_slice)]
1379 ///
1380 /// use std::collections::BinaryHeap;
1381 ///
1382 /// let mut heap = BinaryHeap::<u32>::from([1, 2, 3, 4, 5, 6, 7]);
1383 ///
1384 /// unsafe {
1385 /// for value in heap.as_mut_slice() {
1386 /// *value = (*value).saturating_mul(2);
1387 /// }
1388 /// }
1389 /// ```
1390 #[must_use]
1391 #[unstable(feature = "binary_heap_as_mut_slice", issue = "154009")]
1392 pub unsafe fn as_mut_slice(&mut self) -> &mut [T] {
1393 self.data.as_mut_slice()
1394 }
1395
1396 /// Consumes the `BinaryHeap` and returns the underlying vector
1397 /// in arbitrary order.
1398 ///
1399 /// # Examples
1400 ///
1401 /// Basic usage:
1402 ///
1403 /// ```
1404 /// use std::collections::BinaryHeap;
1405 /// let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
1406 /// let vec = heap.into_vec();
1407 ///
1408 /// // Will print in some order
1409 /// for x in vec {
1410 /// println!("{x}");
1411 /// }
1412 /// ```
1413 #[must_use = "`self` will be dropped if the result is not used"]
1414 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1415 pub fn into_vec(self) -> Vec<T, A> {
1416 self.into()
1417 }
1418
1419 /// Returns a reference to the underlying allocator.
1420 #[unstable(feature = "allocator_api", issue = "32838")]
1421 #[inline]
1422 pub fn allocator(&self) -> &A {
1423 self.data.allocator()
1424 }
1425
1426 /// Returns the length of the binary heap.
1427 ///
1428 /// # Examples
1429 ///
1430 /// Basic usage:
1431 ///
1432 /// ```
1433 /// use std::collections::BinaryHeap;
1434 /// let heap = BinaryHeap::from([1, 3]);
1435 ///
1436 /// assert_eq!(heap.len(), 2);
1437 /// ```
1438 #[must_use]
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 #[rustc_confusables("length", "size")]
1441 pub fn len(&self) -> usize {
1442 self.data.len()
1443 }
1444
1445 /// Checks if the binary heap is empty.
1446 ///
1447 /// # Examples
1448 ///
1449 /// Basic usage:
1450 ///
1451 /// ```
1452 /// use std::collections::BinaryHeap;
1453 /// let mut heap = BinaryHeap::new();
1454 ///
1455 /// assert!(heap.is_empty());
1456 ///
1457 /// heap.push(3);
1458 /// heap.push(5);
1459 /// heap.push(1);
1460 ///
1461 /// assert!(!heap.is_empty());
1462 /// ```
1463 #[must_use]
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 pub fn is_empty(&self) -> bool {
1466 self.len() == 0
1467 }
1468
1469 /// Clears the binary heap, returning an iterator over the removed elements
1470 /// in arbitrary order. If the iterator is dropped before being fully
1471 /// consumed, it drops the remaining elements in arbitrary order.
1472 ///
1473 /// The returned iterator keeps a mutable borrow on the heap to optimize
1474 /// its implementation.
1475 ///
1476 /// # Examples
1477 ///
1478 /// Basic usage:
1479 ///
1480 /// ```
1481 /// use std::collections::BinaryHeap;
1482 /// let mut heap = BinaryHeap::from([1, 3]);
1483 ///
1484 /// assert!(!heap.is_empty());
1485 ///
1486 /// for x in heap.drain() {
1487 /// println!("{x}");
1488 /// }
1489 ///
1490 /// assert!(heap.is_empty());
1491 /// ```
1492 #[inline]
1493 #[stable(feature = "drain", since = "1.6.0")]
1494 pub fn drain(&mut self) -> Drain<'_, T, A> {
1495 Drain { iter: self.data.drain(..) }
1496 }
1497
1498 /// Drops all items from the binary heap.
1499 ///
1500 /// # Examples
1501 ///
1502 /// Basic usage:
1503 ///
1504 /// ```
1505 /// use std::collections::BinaryHeap;
1506 /// let mut heap = BinaryHeap::from([1, 3]);
1507 ///
1508 /// assert!(!heap.is_empty());
1509 ///
1510 /// heap.clear();
1511 ///
1512 /// assert!(heap.is_empty());
1513 /// ```
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 pub fn clear(&mut self) {
1516 self.drain();
1517 }
1518}
1519
1520/// Hole represents a hole in a slice i.e., an index without valid value
1521/// (because it was moved from or duplicated).
1522/// In drop, `Hole` will restore the slice by filling the hole
1523/// position with the value that was originally removed.
1524struct Hole<'a, T: 'a> {
1525 data: &'a mut [T],
1526 elt: ManuallyDrop<T>,
1527 pos: usize,
1528}
1529
1530impl<'a, T> Hole<'a, T> {
1531 /// Creates a new `Hole` at index `pos`.
1532 ///
1533 /// # Safety
1534 ///
1535 /// `pos` must be within the data slice.
1536 #[inline]
1537 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
1538 debug_assert!(pos < data.len());
1539 // SAFETY: Caller ensures pos is inside the slice.
1540 let elt = unsafe { ptr::read(data.get_unchecked(pos)) };
1541 Hole { data, elt: ManuallyDrop::new(elt), pos }
1542 }
1543
1544 #[inline]
1545 fn pos(&self) -> usize {
1546 self.pos
1547 }
1548
1549 /// Returns a reference to the element removed.
1550 #[inline]
1551 fn element(&self) -> &T {
1552 &self.elt
1553 }
1554
1555 /// Returns a reference to the element at `index`.
1556 ///
1557 /// # Safety
1558 ///
1559 /// `index` must be within the data slice and not equal to the current position.
1560 #[inline]
1561 unsafe fn get(&self, index: usize) -> &T {
1562 debug_assert!(index != self.pos);
1563 debug_assert!(index < self.data.len());
1564 // SAFETY: Upheld by caller.
1565 unsafe { self.data.get_unchecked(index) }
1566 }
1567
1568 /// Move hole to new location
1569 ///
1570 /// # Safety
1571 ///
1572 /// `index` must be within the data slice and not equal to the current position.
1573 #[inline]
1574 unsafe fn move_to(&mut self, index: usize) {
1575 debug_assert!(index != self.pos);
1576 debug_assert!(index < self.data.len());
1577 // ignore-tidy-undocumented-unsafe
1578 unsafe {
1579 let ptr = self.data.as_mut_ptr();
1580 let index_ptr: *const _ = ptr.add(index);
1581 let hole_ptr = ptr.add(self.pos);
1582 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1583 }
1584 self.pos = index;
1585 }
1586}
1587
1588impl<T> Drop for Hole<'_, T> {
1589 #[inline]
1590 fn drop(&mut self) {
1591 // fill the hole again
1592 // ignore-tidy-undocumented-unsafe
1593 unsafe {
1594 let pos = self.pos;
1595 ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
1596 }
1597 }
1598}
1599
1600/// An iterator over the elements of a `BinaryHeap`.
1601///
1602/// This `struct` is created by [`BinaryHeap::iter()`]. See its
1603/// documentation for more.
1604///
1605/// [`iter`]: BinaryHeap::iter
1606#[must_use = "iterators are lazy and do nothing unless consumed"]
1607#[stable(feature = "rust1", since = "1.0.0")]
1608pub struct Iter<'a, T: 'a> {
1609 iter: slice::Iter<'a, T>,
1610}
1611
1612#[stable(feature = "default_iters_sequel", since = "1.82.0")]
1613impl<T> Default for Iter<'_, T> {
1614 /// Creates an empty `binary_heap::Iter`.
1615 ///
1616 /// ```
1617 /// # use std::collections::binary_heap;
1618 /// let iter: binary_heap::Iter<'_, u8> = Default::default();
1619 /// assert_eq!(iter.len(), 0);
1620 /// ```
1621 fn default() -> Self {
1622 Iter { iter: Default::default() }
1623 }
1624}
1625
1626#[stable(feature = "collection_debug", since = "1.17.0")]
1627impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1629 f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
1630 }
1631}
1632
1633// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1634#[stable(feature = "rust1", since = "1.0.0")]
1635impl<T> Clone for Iter<'_, T> {
1636 fn clone(&self) -> Self {
1637 Iter { iter: self.iter.clone() }
1638 }
1639}
1640
1641#[stable(feature = "rust1", since = "1.0.0")]
1642impl<'a, T> Iterator for Iter<'a, T> {
1643 type Item = &'a T;
1644
1645 #[inline]
1646 fn next(&mut self) -> Option<&'a T> {
1647 self.iter.next()
1648 }
1649
1650 #[inline]
1651 fn size_hint(&self) -> (usize, Option<usize>) {
1652 self.iter.size_hint()
1653 }
1654
1655 #[inline]
1656 fn last(self) -> Option<&'a T> {
1657 self.iter.last()
1658 }
1659}
1660
1661#[stable(feature = "rust1", since = "1.0.0")]
1662impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1663 #[inline]
1664 fn next_back(&mut self) -> Option<&'a T> {
1665 self.iter.next_back()
1666 }
1667}
1668
1669#[stable(feature = "rust1", since = "1.0.0")]
1670impl<T> ExactSizeIterator for Iter<'_, T> {
1671 fn is_empty(&self) -> bool {
1672 self.iter.is_empty()
1673 }
1674}
1675
1676#[stable(feature = "fused", since = "1.26.0")]
1677impl<T> FusedIterator for Iter<'_, T> {}
1678
1679/// An owning iterator over the elements of a `BinaryHeap`.
1680///
1681/// This `struct` is created by [`BinaryHeap::into_iter()`]
1682/// (provided by the [`IntoIterator`] trait). See its documentation for more.
1683///
1684/// [`into_iter`]: BinaryHeap::into_iter
1685#[stable(feature = "rust1", since = "1.0.0")]
1686#[derive(Clone)]
1687pub struct IntoIter<
1688 T,
1689 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1690> {
1691 iter: vec::IntoIter<T, A>,
1692}
1693
1694impl<T, A: Allocator> IntoIter<T, A> {
1695 /// Returns a reference to the underlying allocator.
1696 #[unstable(feature = "allocator_api", issue = "32838")]
1697 pub fn allocator(&self) -> &A {
1698 self.iter.allocator()
1699 }
1700}
1701
1702#[stable(feature = "collection_debug", since = "1.17.0")]
1703impl<T: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<T, A> {
1704 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1705 f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
1706 }
1707}
1708
1709#[stable(feature = "rust1", since = "1.0.0")]
1710impl<T, A: Allocator> Iterator for IntoIter<T, A> {
1711 type Item = T;
1712
1713 #[inline]
1714 fn next(&mut self) -> Option<T> {
1715 self.iter.next()
1716 }
1717
1718 #[inline]
1719 fn size_hint(&self) -> (usize, Option<usize>) {
1720 self.iter.size_hint()
1721 }
1722}
1723
1724#[stable(feature = "rust1", since = "1.0.0")]
1725impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
1726 #[inline]
1727 fn next_back(&mut self) -> Option<T> {
1728 self.iter.next_back()
1729 }
1730}
1731
1732#[stable(feature = "rust1", since = "1.0.0")]
1733impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {
1734 fn is_empty(&self) -> bool {
1735 self.iter.is_empty()
1736 }
1737}
1738
1739#[stable(feature = "fused", since = "1.26.0")]
1740impl<T, A: Allocator> FusedIterator for IntoIter<T, A> {}
1741
1742#[doc(hidden)]
1743#[unstable(issue = "none", feature = "trusted_fused")]
1744unsafe impl<T, A: Allocator> TrustedFused for IntoIter<T, A> {}
1745
1746#[stable(feature = "default_iters", since = "1.70.0")]
1747impl<T> Default for IntoIter<T> {
1748 /// Creates an empty `binary_heap::IntoIter`.
1749 ///
1750 /// ```
1751 /// # use std::collections::binary_heap;
1752 /// let iter: binary_heap::IntoIter<u8> = Default::default();
1753 /// assert_eq!(iter.len(), 0);
1754 /// ```
1755 fn default() -> Self {
1756 IntoIter { iter: Default::default() }
1757 }
1758}
1759
1760// In addition to the SAFETY invariants of the following three unsafe traits
1761// also refer to the vec::in_place_collect module documentation to get an overview
1762#[unstable(issue = "none", feature = "inplace_iteration")]
1763#[doc(hidden)]
1764unsafe impl<T, A: Allocator> SourceIter for IntoIter<T, A> {
1765 type Source = IntoIter<T, A>;
1766
1767 #[inline]
1768 unsafe fn as_inner(&mut self) -> &mut Self::Source {
1769 self
1770 }
1771}
1772
1773#[unstable(issue = "none", feature = "inplace_iteration")]
1774#[doc(hidden)]
1775unsafe impl<I, A: Allocator> InPlaceIterable for IntoIter<I, A> {
1776 const EXPAND_BY: Option<NonZero<usize>> = NonZero::new(1);
1777 const MERGE_BY: Option<NonZero<usize>> = NonZero::new(1);
1778}
1779
1780#[cfg(not(test))]
1781unsafe impl<I> AsVecIntoIter for IntoIter<I> {
1782 type Item = I;
1783
1784 fn as_into_iter(&mut self) -> &mut vec::IntoIter<Self::Item> {
1785 &mut self.iter
1786 }
1787}
1788
1789#[must_use = "iterators are lazy and do nothing unless consumed"]
1790#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1791#[derive(Clone, Debug)]
1792pub struct IntoIterSorted<
1793 T,
1794 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1795> {
1796 inner: BinaryHeap<T, A>,
1797}
1798
1799impl<T, A: Allocator> IntoIterSorted<T, A> {
1800 /// Returns a reference to the underlying allocator.
1801 #[unstable(feature = "allocator_api", issue = "32838")]
1802 pub fn allocator(&self) -> &A {
1803 self.inner.allocator()
1804 }
1805}
1806
1807#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1808impl<T: Ord, A: Allocator> Iterator for IntoIterSorted<T, A> {
1809 type Item = T;
1810
1811 #[inline]
1812 fn next(&mut self) -> Option<T> {
1813 self.inner.pop()
1814 }
1815
1816 #[inline]
1817 fn size_hint(&self) -> (usize, Option<usize>) {
1818 let exact = self.inner.len();
1819 (exact, Some(exact))
1820 }
1821}
1822
1823#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1824impl<T: Ord, A: Allocator> ExactSizeIterator for IntoIterSorted<T, A> {}
1825
1826#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1827impl<T: Ord, A: Allocator> FusedIterator for IntoIterSorted<T, A> {}
1828
1829#[unstable(feature = "trusted_len", issue = "37572")]
1830unsafe impl<T: Ord, A: Allocator> TrustedLen for IntoIterSorted<T, A> {}
1831
1832/// A draining iterator over the elements of a `BinaryHeap`.
1833///
1834/// This `struct` is created by [`BinaryHeap::drain()`]. See its
1835/// documentation for more.
1836///
1837/// [`drain`]: BinaryHeap::drain
1838#[stable(feature = "drain", since = "1.6.0")]
1839#[derive(Debug)]
1840pub struct Drain<
1841 'a,
1842 T: 'a,
1843 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1844> {
1845 iter: vec::Drain<'a, T, A>,
1846}
1847
1848impl<T, A: Allocator> Drain<'_, T, A> {
1849 /// Returns a reference to the underlying allocator.
1850 #[unstable(feature = "allocator_api", issue = "32838")]
1851 pub fn allocator(&self) -> &A {
1852 self.iter.allocator()
1853 }
1854}
1855
1856#[stable(feature = "drain", since = "1.6.0")]
1857impl<T, A: Allocator> Iterator for Drain<'_, T, A> {
1858 type Item = T;
1859
1860 #[inline]
1861 fn next(&mut self) -> Option<T> {
1862 self.iter.next()
1863 }
1864
1865 #[inline]
1866 fn size_hint(&self) -> (usize, Option<usize>) {
1867 self.iter.size_hint()
1868 }
1869}
1870
1871#[stable(feature = "drain", since = "1.6.0")]
1872impl<T, A: Allocator> DoubleEndedIterator for Drain<'_, T, A> {
1873 #[inline]
1874 fn next_back(&mut self) -> Option<T> {
1875 self.iter.next_back()
1876 }
1877}
1878
1879#[stable(feature = "drain", since = "1.6.0")]
1880impl<T, A: Allocator> ExactSizeIterator for Drain<'_, T, A> {
1881 fn is_empty(&self) -> bool {
1882 self.iter.is_empty()
1883 }
1884}
1885
1886#[stable(feature = "fused", since = "1.26.0")]
1887impl<T, A: Allocator> FusedIterator for Drain<'_, T, A> {}
1888
1889/// A draining iterator over the elements of a `BinaryHeap`.
1890///
1891/// This `struct` is created by [`BinaryHeap::drain_sorted()`]. See its
1892/// documentation for more.
1893///
1894/// [`drain_sorted`]: BinaryHeap::drain_sorted
1895#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1896#[derive(Debug)]
1897pub struct DrainSorted<
1898 'a,
1899 T: Ord,
1900 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1901> {
1902 inner: &'a mut BinaryHeap<T, A>,
1903}
1904
1905impl<'a, T: Ord, A: Allocator> DrainSorted<'a, T, A> {
1906 /// Returns a reference to the underlying allocator.
1907 #[unstable(feature = "allocator_api", issue = "32838")]
1908 pub fn allocator(&self) -> &A {
1909 self.inner.allocator()
1910 }
1911}
1912
1913#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1914impl<'a, T: Ord, A: Allocator> Drop for DrainSorted<'a, T, A> {
1915 /// Removes heap elements in heap order.
1916 fn drop(&mut self) {
1917 while let Some(item) = self.inner.pop() {
1918 let guard = DropGuard::new(&mut *self, |this| while this.inner.pop().is_some() {});
1919 drop(item);
1920 DropGuard::dismiss(guard);
1921 }
1922 }
1923}
1924
1925#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1926impl<T: Ord, A: Allocator> Iterator for DrainSorted<'_, T, A> {
1927 type Item = T;
1928
1929 #[inline]
1930 fn next(&mut self) -> Option<T> {
1931 self.inner.pop()
1932 }
1933
1934 #[inline]
1935 fn size_hint(&self) -> (usize, Option<usize>) {
1936 let exact = self.inner.len();
1937 (exact, Some(exact))
1938 }
1939}
1940
1941#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1942impl<T: Ord, A: Allocator> ExactSizeIterator for DrainSorted<'_, T, A> {}
1943
1944#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1945impl<T: Ord, A: Allocator> FusedIterator for DrainSorted<'_, T, A> {}
1946
1947#[unstable(feature = "trusted_len", issue = "37572")]
1948unsafe impl<T: Ord, A: Allocator> TrustedLen for DrainSorted<'_, T, A> {}
1949
1950#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1951impl<T: Ord, A: Allocator> From<Vec<T, A>> for BinaryHeap<T, A> {
1952 /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1953 ///
1954 /// This conversion happens in-place, and has *O*(*n*) time complexity.
1955 fn from(vec: Vec<T, A>) -> BinaryHeap<T, A> {
1956 let mut heap = BinaryHeap { data: vec };
1957 heap.rebuild();
1958 heap
1959 }
1960}
1961
1962#[stable(feature = "std_collections_from_array", since = "1.56.0")]
1963impl<T: Ord, const N: usize> From<[T; N]> for BinaryHeap<T> {
1964 /// ```
1965 /// use std::collections::BinaryHeap;
1966 ///
1967 /// let mut h1 = BinaryHeap::from([1, 4, 2, 3]);
1968 /// let mut h2: BinaryHeap<_> = [1, 4, 2, 3].into();
1969 /// while let Some((a, b)) = h1.pop().zip(h2.pop()) {
1970 /// assert_eq!(a, b);
1971 /// }
1972 /// ```
1973 fn from(arr: [T; N]) -> Self {
1974 Self::from_iter(arr)
1975 }
1976}
1977
1978#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1979impl<T, A: Allocator> From<BinaryHeap<T, A>> for Vec<T, A> {
1980 /// Converts a `BinaryHeap<T>` into a `Vec<T>`.
1981 ///
1982 /// This conversion requires no data movement or allocation, and has
1983 /// constant time complexity.
1984 fn from(heap: BinaryHeap<T, A>) -> Vec<T, A> {
1985 heap.data
1986 }
1987}
1988
1989#[stable(feature = "rust1", since = "1.0.0")]
1990impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1991 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1992 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1993 }
1994}
1995
1996#[stable(feature = "rust1", since = "1.0.0")]
1997impl<T, A: Allocator> IntoIterator for BinaryHeap<T, A> {
1998 type Item = T;
1999 type IntoIter = IntoIter<T, A>;
2000
2001 /// Creates a consuming iterator, that is, one that moves each value out of
2002 /// the binary heap in arbitrary order. The binary heap cannot be used
2003 /// after calling this.
2004 ///
2005 /// # Examples
2006 ///
2007 /// Basic usage:
2008 ///
2009 /// ```
2010 /// use std::collections::BinaryHeap;
2011 /// let heap = BinaryHeap::from([1, 2, 3, 4]);
2012 ///
2013 /// // Print 1, 2, 3, 4 in arbitrary order
2014 /// for x in heap.into_iter() {
2015 /// // x has type i32, not &i32
2016 /// println!("{x}");
2017 /// }
2018 /// ```
2019 fn into_iter(self) -> IntoIter<T, A> {
2020 IntoIter { iter: self.data.into_iter() }
2021 }
2022}
2023
2024#[stable(feature = "rust1", since = "1.0.0")]
2025impl<'a, T, A: Allocator> IntoIterator for &'a BinaryHeap<T, A> {
2026 type Item = &'a T;
2027 type IntoIter = Iter<'a, T>;
2028
2029 fn into_iter(self) -> Iter<'a, T> {
2030 self.iter()
2031 }
2032}
2033
2034#[stable(feature = "rust1", since = "1.0.0")]
2035impl<T: Ord, A: Allocator> Extend<T> for BinaryHeap<T, A> {
2036 #[inline]
2037 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2038 let guard = RebuildOnDrop { rebuild_from: self.len(), heap: self };
2039 guard.heap.data.extend(iter);
2040 }
2041
2042 #[inline]
2043 fn extend_one(&mut self, item: T) {
2044 self.push(item);
2045 }
2046
2047 #[inline]
2048 fn extend_reserve(&mut self, additional: usize) {
2049 self.reserve(additional);
2050 }
2051}
2052
2053#[stable(feature = "extend_ref", since = "1.2.0")]
2054impl<'a, T: 'a + Ord + Copy, A: Allocator> Extend<&'a T> for BinaryHeap<T, A> {
2055 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2056 self.extend(iter.into_iter().cloned());
2057 }
2058
2059 #[inline]
2060 fn extend_one(&mut self, &item: &'a T) {
2061 self.push(item);
2062 }
2063
2064 #[inline]
2065 fn extend_reserve(&mut self, additional: usize) {
2066 self.reserve(additional);
2067 }
2068}