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::{self, ManuallyDrop, swap};
149use core::num::NonZero;
150use core::ops::{Deref, DerefMut};
151use core::{fmt, ptr};
152
153use crate::alloc::{AllocatorNightly, 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_ext", issue = "163177", implied_by = "allocator_api")] 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_ext", issue = "163177", implied_by = "allocator_api")] 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_ext", issue = "163177", implied_by = "allocator_api")] 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_ext)]
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_ext", issue = "163177", implied_by = "allocator_api")]
554 #[rustc_const_unstable(feature = "allocator_ext", issue = "163177")]
555 #[must_use]
556 pub const fn new_in(alloc: A) -> BinaryHeap<T, A> {
557 BinaryHeap { data: Vec::new_in(alloc) }
558 }
559
560 /// Creates an empty `BinaryHeap` with at least the specified capacity, using `A` as allocator.
561 ///
562 /// The binary heap will be able to hold at least `capacity` elements without
563 /// reallocating. This method is allowed to allocate for more elements than
564 /// `capacity`. If `capacity` is zero, the binary heap will not allocate.
565 ///
566 /// # Examples
567 ///
568 /// Basic usage:
569 ///
570 /// ```
571 /// #![feature(allocator_ext)]
572 ///
573 /// use std::alloc::System;
574 /// use std::collections::BinaryHeap;
575 ///
576 /// let heap: BinaryHeap<i32, System> = BinaryHeap::with_capacity_in(10, System);
577 /// ```
578 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
579 #[must_use]
580 pub fn with_capacity_in(capacity: usize, alloc: A) -> BinaryHeap<T, A> {
581 BinaryHeap { data: Vec::with_capacity_in(capacity, alloc) }
582 }
583
584 /// Creates a `BinaryHeap` using the supplied `vec`. This does not rebuild the heap,
585 /// so `vec` must already be a max-heap.
586 ///
587 /// # Safety
588 ///
589 /// The supplied `vec` must be a max-heap, i.e. for all indices `0 < i < vec.len()`,
590 /// `vec[(i - 1) / 2] >= vec[i]`.
591 ///
592 /// # Examples
593 ///
594 /// Basic usage:
595 ///
596 /// ```
597 /// #![feature(binary_heap_from_raw_vec)]
598 ///
599 /// use std::collections::BinaryHeap;
600 /// let heap = BinaryHeap::from([1, 2, 3]);
601 /// let vec = heap.into_vec();
602 ///
603 /// // Safety: vec is the output of heap.from_vec(), so is a max-heap.
604 /// let mut new_heap = unsafe {
605 /// BinaryHeap::from_raw_vec(vec)
606 /// };
607 /// assert_eq!(new_heap.pop(), Some(3));
608 /// assert_eq!(new_heap.pop(), Some(2));
609 /// assert_eq!(new_heap.pop(), Some(1));
610 /// assert_eq!(new_heap.pop(), None);
611 /// ```
612 #[unstable(feature = "binary_heap_from_raw_vec", issue = "152500")]
613 #[must_use]
614 pub unsafe fn from_raw_vec(vec: Vec<T, A>) -> BinaryHeap<T, A> {
615 BinaryHeap { data: vec }
616 }
617}
618
619impl<T: Ord, A: Allocator> BinaryHeap<T, A> {
620 /// Returns a mutable reference to the greatest item in the binary heap, or
621 /// `None` if it is empty.
622 ///
623 /// Note: If the `PeekMut` value is leaked, some heap elements might get
624 /// leaked along with it, but the remaining elements will remain a valid
625 /// heap.
626 ///
627 /// # Examples
628 ///
629 /// Basic usage:
630 ///
631 /// ```
632 /// use std::collections::BinaryHeap;
633 /// let mut heap = BinaryHeap::new();
634 /// assert!(heap.peek_mut().is_none());
635 ///
636 /// heap.push(1);
637 /// heap.push(5);
638 /// heap.push(2);
639 /// if let Some(mut val) = heap.peek_mut() {
640 /// *val = 0;
641 /// }
642 /// assert_eq!(heap.peek(), Some(&2));
643 /// ```
644 ///
645 /// # Time complexity
646 ///
647 /// If the item is modified then the worst case time complexity is *O*(log(*n*)),
648 /// otherwise it's *O*(1).
649 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
650 pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, A>> {
651 if self.is_empty() { None } else { Some(PeekMut { heap: self, original_len: None }) }
652 }
653
654 /// Removes the greatest item from the binary heap and returns it, or `None` if it
655 /// is empty.
656 ///
657 /// # Examples
658 ///
659 /// Basic usage:
660 ///
661 /// ```
662 /// use std::collections::BinaryHeap;
663 /// let mut heap = BinaryHeap::from([1, 3]);
664 ///
665 /// assert_eq!(heap.pop(), Some(3));
666 /// assert_eq!(heap.pop(), Some(1));
667 /// assert_eq!(heap.pop(), None);
668 /// ```
669 ///
670 /// # Time complexity
671 ///
672 /// The worst case cost of `pop` on a heap containing *n* elements is *O*(log(*n*)).
673 #[stable(feature = "rust1", since = "1.0.0")]
674 pub fn pop(&mut self) -> Option<T> {
675 self.data.pop().map(|mut item| {
676 if !self.is_empty() {
677 swap(&mut item, &mut self.data[0]);
678 // SAFETY: !self.is_empty() means that self.len() > 0
679 unsafe { self.sift_down_to_bottom(0) };
680 }
681 item
682 })
683 }
684
685 /// Removes and returns the greatest item from the binary heap if the predicate
686 /// returns `true`, or [`None`] if the predicate returns false or the heap
687 /// is empty (the predicate will not be called in that case).
688 ///
689 /// # Examples
690 ///
691 /// ```
692 /// #![feature(binary_heap_pop_if)]
693 /// use std::collections::BinaryHeap;
694 /// let mut heap = BinaryHeap::from([1, 2]);
695 /// let pred = |x: &i32| *x % 2 == 0;
696 ///
697 /// assert_eq!(heap.pop_if(pred), Some(2));
698 /// assert_eq!(heap.as_slice(), [1]);
699 /// assert_eq!(heap.pop_if(pred), None);
700 /// assert_eq!(heap.as_slice(), [1]);
701 /// ```
702 ///
703 /// # Time complexity
704 ///
705 /// The worst case cost of `pop_if` on a heap containing *n* elements is *O*(log(*n*)).
706 #[unstable(feature = "binary_heap_pop_if", issue = "151828")]
707 pub fn pop_if(&mut self, predicate: impl FnOnce(&T) -> bool) -> Option<T> {
708 let first = self.peek()?;
709 if predicate(first) { self.pop() } else { None }
710 }
711
712 /// Pushes an item onto the binary heap.
713 ///
714 /// # Examples
715 ///
716 /// Basic usage:
717 ///
718 /// ```
719 /// use std::collections::BinaryHeap;
720 /// let mut heap = BinaryHeap::new();
721 /// heap.push(3);
722 /// heap.push(5);
723 /// heap.push(1);
724 ///
725 /// assert_eq!(heap.len(), 3);
726 /// assert_eq!(heap.peek(), Some(&5));
727 /// ```
728 ///
729 /// # Time complexity
730 ///
731 /// The expected cost of `push`, averaged over every possible ordering of
732 /// the elements being pushed, and over a sufficiently large number of
733 /// pushes, is *O*(1). This is the most meaningful cost metric when pushing
734 /// elements that are *not* already in any sorted pattern.
735 ///
736 /// The time complexity degrades if elements are pushed in predominantly
737 /// ascending order. In the worst case, elements are pushed in ascending
738 /// sorted order and the amortized cost per push is *O*(log(*n*)) against a heap
739 /// containing *n* elements.
740 ///
741 /// The worst case cost of a *single* call to `push` is *O*(*n*). The worst case
742 /// occurs when capacity is exhausted and needs a resize. The resize cost
743 /// has been amortized in the previous figures.
744 #[stable(feature = "rust1", since = "1.0.0")]
745 #[rustc_confusables("append", "put")]
746 pub fn push(&mut self, item: T) {
747 let old_len = self.len();
748 self.data.push(item);
749 // SAFETY: Since we pushed a new item it means that
750 // old_len = self.len() - 1 < self.len()
751 unsafe { self.sift_up(0, old_len) };
752 }
753
754 /// Consumes the `BinaryHeap` and returns a vector in sorted
755 /// (ascending) order.
756 ///
757 /// # Examples
758 ///
759 /// Basic usage:
760 ///
761 /// ```
762 /// use std::collections::BinaryHeap;
763 ///
764 /// let mut heap = BinaryHeap::from([1, 2, 4, 5, 7]);
765 /// heap.push(6);
766 /// heap.push(3);
767 ///
768 /// let vec = heap.into_sorted_vec();
769 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
770 /// ```
771 #[must_use = "`self` will be dropped if the result is not used"]
772 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
773 pub fn into_sorted_vec(mut self) -> Vec<T, A> {
774 let mut end = self.len();
775 while end > 1 {
776 end -= 1;
777 // SAFETY: `end` goes from `self.len() - 1` to 1 (both included),
778 // so it's always a valid index to access.
779 // It is safe to access index 0 (i.e. `ptr`), because
780 // 1 <= end < self.len(), which means self.len() >= 2.
781 unsafe {
782 let ptr = self.data.as_mut_ptr();
783 ptr::swap(ptr, ptr.add(end));
784 }
785 // SAFETY: `end` goes from `self.len() - 1` to 1 (both included) so:
786 // 0 < 1 <= end <= self.len() - 1 < self.len()
787 // Which means 0 < end and end < self.len().
788 unsafe { self.sift_down_range(0, end) };
789 }
790 self.into_vec()
791 }
792
793 // The implementations of sift_up and sift_down use unsafe blocks in
794 // order to move an element out of the vector (leaving behind a
795 // hole), shift along the others and move the removed element back into the
796 // vector at the final location of the hole.
797 // The `Hole` type is used to represent this, and make sure
798 // the hole is filled back at the end of its scope, even on panic.
799 // Using a hole reduces the constant factor compared to using swaps,
800 // which involves twice as many moves.
801
802 /// # Safety
803 ///
804 /// The caller must guarantee that `pos < self.len()`.
805 ///
806 /// Returns the new position of the element.
807 unsafe fn sift_up(&mut self, start: usize, pos: usize) -> usize {
808 // Take out the value at `pos` and create a hole.
809 // SAFETY: The caller guarantees that pos < self.len()
810 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
811
812 while hole.pos() > start {
813 let parent = (hole.pos() - 1) / 2;
814
815 // SAFETY: hole.pos() > start >= 0, which means hole.pos() > 0
816 // and so hole.pos() - 1 can't underflow.
817 // This guarantees that parent < hole.pos() so
818 // it's a valid index and also != hole.pos().
819 if hole.element() <= unsafe { hole.get(parent) } {
820 break;
821 }
822
823 // SAFETY: Same as above
824 unsafe { hole.move_to(parent) };
825 }
826
827 hole.pos()
828 }
829
830 /// Take an element at `pos` and move it down the heap,
831 /// while its children are larger.
832 ///
833 /// Returns the new position of the element.
834 ///
835 /// # Safety
836 ///
837 /// The caller must guarantee that `pos < end <= self.len()`.
838 unsafe fn sift_down_range(&mut self, pos: usize, end: usize) -> usize {
839 // SAFETY: The caller guarantees that pos < end <= self.len().
840 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
841 let mut child = 2 * hole.pos() + 1;
842
843 // Loop invariant: child == 2 * hole.pos() + 1.
844 while child <= end.saturating_sub(2) {
845 // compare with the greater of the two children
846 // SAFETY: child < end - 1 < self.len() and
847 // child + 1 < end <= self.len(), so they're valid indexes.
848 // child == 2 * hole.pos() + 1 != hole.pos() and
849 // child + 1 == 2 * hole.pos() + 2 != hole.pos().
850 // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
851 // if T is a ZST
852 child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
853
854 // if we are already in order, stop.
855 // SAFETY: child is now either the old child or the old child+1
856 // We already proven that both are < self.len() and != hole.pos()
857 if hole.element() >= unsafe { hole.get(child) } {
858 return hole.pos();
859 }
860
861 // SAFETY: same as above.
862 unsafe { hole.move_to(child) };
863 child = 2 * hole.pos() + 1;
864 }
865
866 // SAFETY: && short circuit, which means that in the
867 // second condition it's already true that child == end - 1 < self.len().
868 if child == end - 1 && hole.element() < unsafe { hole.get(child) } {
869 // SAFETY: child is already proven to be a valid index and
870 // child == 2 * hole.pos() + 1 != hole.pos().
871 unsafe { hole.move_to(child) };
872 }
873
874 hole.pos()
875 }
876
877 /// # Safety
878 ///
879 /// The caller must guarantee that `pos < self.len()`.
880 unsafe fn sift_down(&mut self, pos: usize) -> usize {
881 let len = self.len();
882 // SAFETY: pos < len is guaranteed by the caller and
883 // obviously len = self.len() <= self.len().
884 unsafe { self.sift_down_range(pos, len) }
885 }
886
887 /// Take an element at `pos` and move it all the way down the heap,
888 /// then sift it up to its position.
889 ///
890 /// Note: This is faster when the element is known to be large / should
891 /// be closer to the bottom.
892 ///
893 /// # Safety
894 ///
895 /// The caller must guarantee that `pos < self.len()`.
896 unsafe fn sift_down_to_bottom(&mut self, mut pos: usize) {
897 let end = self.len();
898 let start = pos;
899
900 // SAFETY: The caller guarantees that pos < self.len().
901 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
902 let mut child = 2 * hole.pos() + 1;
903
904 // Loop invariant: child == 2 * hole.pos() + 1.
905 while child <= end.saturating_sub(2) {
906 // SAFETY: child < end - 1 < self.len() and
907 // child + 1 < end <= self.len(), so they're valid indexes.
908 // child == 2 * hole.pos() + 1 != hole.pos() and
909 // child + 1 == 2 * hole.pos() + 2 != hole.pos().
910 // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
911 // if T is a ZST
912 child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
913
914 // SAFETY: Same as above
915 unsafe { hole.move_to(child) };
916 child = 2 * hole.pos() + 1;
917 }
918
919 if child == end - 1 {
920 // SAFETY: child == end - 1 < self.len(), so it's a valid index
921 // and child == 2 * hole.pos() + 1 != hole.pos().
922 unsafe { hole.move_to(child) };
923 }
924 pos = hole.pos();
925 drop(hole);
926
927 // SAFETY: pos is the position in the hole and was already proven
928 // to be a valid index.
929 unsafe { self.sift_up(start, pos) };
930 }
931
932 /// Rebuild assuming data[0..start] is still a proper heap.
933 fn rebuild_tail(&mut self, start: usize) {
934 if start == self.len() {
935 return;
936 }
937
938 let tail_len = self.len() - start;
939
940 #[inline(always)]
941 fn log2_fast(x: usize) -> usize {
942 (usize::BITS - x.leading_zeros() - 1) as usize
943 }
944
945 // `rebuild` takes O(self.len()) operations
946 // and about 2 * self.len() comparisons in the worst case
947 // while repeating `sift_up` takes O(tail_len * log(start)) operations
948 // and about 1 * tail_len * log_2(start) comparisons in the worst case,
949 // assuming start >= tail_len. For larger heaps, the crossover point
950 // no longer follows this reasoning and was determined empirically.
951 let better_to_rebuild = if start < tail_len {
952 true
953 } else if self.len() <= 2048 {
954 2 * self.len() < tail_len * log2_fast(start)
955 } else {
956 2 * self.len() < tail_len * 11
957 };
958
959 if better_to_rebuild {
960 self.rebuild();
961 } else {
962 for i in start..self.len() {
963 // SAFETY: The index `i` is always less than self.len().
964 unsafe { self.sift_up(0, i) };
965 }
966 }
967 }
968
969 fn rebuild(&mut self) {
970 let mut n = self.len() / 2;
971 while n > 0 {
972 n -= 1;
973 // SAFETY: n starts from self.len() / 2 and goes down to 0.
974 // The only case when !(n < self.len()) is if
975 // self.len() == 0, but it's ruled out by the loop condition.
976 unsafe { self.sift_down(n) };
977 }
978 }
979
980 /// Moves all the elements of `other` into `self`, leaving `other` empty.
981 ///
982 /// # Examples
983 ///
984 /// Basic usage:
985 ///
986 /// ```
987 /// use std::collections::BinaryHeap;
988 ///
989 /// let mut a = BinaryHeap::from([-10, 1, 2, 3, 3]);
990 /// let mut b = BinaryHeap::from([-20, 5, 43]);
991 ///
992 /// a.append(&mut b);
993 ///
994 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
995 /// assert!(b.is_empty());
996 /// ```
997 #[stable(feature = "binary_heap_append", since = "1.11.0")]
998 pub fn append(&mut self, other: &mut Self) {
999 if self.len() < other.len() {
1000 swap(self, other);
1001 }
1002
1003 let start = self.data.len();
1004
1005 self.data.append(&mut other.data);
1006
1007 self.rebuild_tail(start);
1008 }
1009
1010 /// Clears the binary heap, returning an iterator over the removed elements
1011 /// in heap order. If the iterator is dropped before being fully consumed,
1012 /// it drops the remaining elements in heap order.
1013 ///
1014 /// The returned iterator keeps a mutable borrow on the heap to optimize
1015 /// its implementation.
1016 ///
1017 /// Note:
1018 /// * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`.
1019 /// You should use the latter for most cases.
1020 ///
1021 /// # Examples
1022 ///
1023 /// Basic usage:
1024 ///
1025 /// ```
1026 /// #![feature(binary_heap_drain_sorted)]
1027 /// use std::collections::BinaryHeap;
1028 ///
1029 /// let mut heap = BinaryHeap::from([1, 2, 3, 4, 5]);
1030 /// assert_eq!(heap.len(), 5);
1031 ///
1032 /// drop(heap.drain_sorted()); // removes all elements in heap order
1033 /// assert_eq!(heap.len(), 0);
1034 /// ```
1035 #[inline]
1036 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1037 pub fn drain_sorted(&mut self) -> DrainSorted<'_, T, A> {
1038 DrainSorted { inner: self }
1039 }
1040
1041 /// Retains only the elements specified by the predicate.
1042 ///
1043 /// In other words, remove all elements `e` for which `f(&e)` returns
1044 /// `false`. The elements are visited in unsorted (and unspecified) order.
1045 ///
1046 /// # Examples
1047 ///
1048 /// Basic usage:
1049 ///
1050 /// ```
1051 /// use std::collections::BinaryHeap;
1052 ///
1053 /// let mut heap = BinaryHeap::from([-10, -5, 1, 2, 4, 13]);
1054 ///
1055 /// heap.retain(|x| x % 2 == 0); // only keep even numbers
1056 ///
1057 /// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
1058 /// ```
1059 #[stable(feature = "binary_heap_retain", since = "1.70.0")]
1060 pub fn retain<F>(&mut self, mut f: F)
1061 where
1062 F: FnMut(&T) -> bool,
1063 {
1064 // rebuild_start will be updated to the first touched element below, and the rebuild will
1065 // only be done for the tail.
1066 let mut guard = RebuildOnDrop { rebuild_from: self.len(), heap: self };
1067 let mut i = 0;
1068
1069 guard.heap.data.retain(|e| {
1070 let keep = f(e);
1071 if !keep && i < guard.rebuild_from {
1072 guard.rebuild_from = i;
1073 }
1074 i += 1;
1075 keep
1076 });
1077 }
1078}
1079
1080impl<T, A: Allocator> BinaryHeap<T, A> {
1081 /// Returns an iterator visiting all values in the underlying vector, in
1082 /// arbitrary order.
1083 ///
1084 /// # Examples
1085 ///
1086 /// Basic usage:
1087 ///
1088 /// ```
1089 /// use std::collections::BinaryHeap;
1090 /// let heap = BinaryHeap::from([1, 2, 3, 4]);
1091 ///
1092 /// // Print 1, 2, 3, 4 in arbitrary order
1093 /// for x in heap.iter() {
1094 /// println!("{x}");
1095 /// }
1096 /// ```
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 #[cfg_attr(not(test), rustc_diagnostic_item = "binaryheap_iter")]
1099 pub fn iter(&self) -> Iter<'_, T> {
1100 Iter { iter: self.data.iter() }
1101 }
1102
1103 /// Returns an iterator which retrieves elements in heap order.
1104 ///
1105 /// This method consumes the original heap.
1106 ///
1107 /// # Examples
1108 ///
1109 /// Basic usage:
1110 ///
1111 /// ```
1112 /// #![feature(binary_heap_into_iter_sorted)]
1113 /// use std::collections::BinaryHeap;
1114 /// let heap = BinaryHeap::from([1, 2, 3, 4, 5]);
1115 ///
1116 /// assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), [5, 4]);
1117 /// ```
1118 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1119 pub fn into_iter_sorted(self) -> IntoIterSorted<T, A> {
1120 IntoIterSorted { inner: self }
1121 }
1122
1123 /// Returns the greatest item in the binary heap, or `None` if it is empty.
1124 ///
1125 /// # Examples
1126 ///
1127 /// Basic usage:
1128 ///
1129 /// ```
1130 /// use std::collections::BinaryHeap;
1131 /// let mut heap = BinaryHeap::new();
1132 /// assert_eq!(heap.peek(), None);
1133 ///
1134 /// heap.push(1);
1135 /// heap.push(5);
1136 /// heap.push(2);
1137 /// assert_eq!(heap.peek(), Some(&5));
1138 ///
1139 /// ```
1140 ///
1141 /// # Time complexity
1142 ///
1143 /// Cost is *O*(1) in the worst case.
1144 #[must_use]
1145 #[stable(feature = "rust1", since = "1.0.0")]
1146 pub fn peek(&self) -> Option<&T> {
1147 self.data.get(0)
1148 }
1149
1150 /// Returns the number of elements the binary heap can hold without reallocating.
1151 ///
1152 /// # Examples
1153 ///
1154 /// Basic usage:
1155 ///
1156 /// ```
1157 /// use std::collections::BinaryHeap;
1158 /// let mut heap = BinaryHeap::with_capacity(100);
1159 /// assert!(heap.capacity() >= 100);
1160 /// heap.push(4);
1161 /// ```
1162 #[must_use]
1163 #[stable(feature = "rust1", since = "1.0.0")]
1164 pub fn capacity(&self) -> usize {
1165 self.data.capacity()
1166 }
1167
1168 /// Reserves the minimum capacity for at least `additional` elements more than
1169 /// the current length. Unlike [`reserve`], this will not
1170 /// deliberately over-allocate to speculatively avoid frequent allocations.
1171 /// After calling `reserve_exact`, capacity will be greater than or equal to
1172 /// `self.len() + additional`. Does nothing if the capacity is already
1173 /// sufficient.
1174 ///
1175 /// [`reserve`]: BinaryHeap::reserve
1176 ///
1177 /// # Panics
1178 ///
1179 /// Panics if the new capacity overflows [`usize`].
1180 ///
1181 /// # Examples
1182 ///
1183 /// Basic usage:
1184 ///
1185 /// ```
1186 /// use std::collections::BinaryHeap;
1187 /// let mut heap = BinaryHeap::new();
1188 /// heap.reserve_exact(100);
1189 /// assert!(heap.capacity() >= 100);
1190 /// heap.push(4);
1191 /// ```
1192 ///
1193 /// [`reserve`]: BinaryHeap::reserve
1194 #[stable(feature = "rust1", since = "1.0.0")]
1195 pub fn reserve_exact(&mut self, additional: usize) {
1196 self.data.reserve_exact(additional);
1197 }
1198
1199 /// Reserves capacity for at least `additional` elements more than the
1200 /// current length. The allocator may reserve more space to speculatively
1201 /// avoid frequent allocations. After calling `reserve`,
1202 /// capacity will be greater than or equal to `self.len() + additional`.
1203 /// Does nothing if capacity is already sufficient.
1204 ///
1205 /// # Panics
1206 ///
1207 /// Panics if the new capacity overflows [`usize`].
1208 ///
1209 /// # Examples
1210 ///
1211 /// Basic usage:
1212 ///
1213 /// ```
1214 /// use std::collections::BinaryHeap;
1215 /// let mut heap = BinaryHeap::new();
1216 /// heap.reserve(100);
1217 /// assert!(heap.capacity() >= 100);
1218 /// heap.push(4);
1219 /// ```
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 pub fn reserve(&mut self, additional: usize) {
1222 self.data.reserve(additional);
1223 }
1224
1225 /// Tries to reserve the minimum capacity for at least `additional` elements
1226 /// more than the current length. Unlike [`try_reserve`], this will not
1227 /// deliberately over-allocate to speculatively avoid frequent allocations.
1228 /// After calling `try_reserve_exact`, capacity will be greater than or
1229 /// equal to `self.len() + additional` if it returns `Ok(())`.
1230 /// Does nothing if the capacity is already sufficient.
1231 ///
1232 /// Note that the allocator may give the collection more space than it
1233 /// requests. Therefore, capacity can not be relied upon to be precisely
1234 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1235 ///
1236 /// [`try_reserve`]: BinaryHeap::try_reserve
1237 ///
1238 /// # Errors
1239 ///
1240 /// If the capacity overflows, or the allocator reports a failure, then an error
1241 /// is returned.
1242 ///
1243 /// # Examples
1244 ///
1245 /// ```
1246 /// use std::collections::BinaryHeap;
1247 /// use std::collections::TryReserveError;
1248 ///
1249 /// fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
1250 /// let mut heap = BinaryHeap::new();
1251 ///
1252 /// // Pre-reserve the memory, exiting if we can't
1253 /// heap.try_reserve_exact(data.len())?;
1254 ///
1255 /// // Now we know this can't OOM in the middle of our complex work
1256 /// heap.extend(data.iter());
1257 ///
1258 /// Ok(heap.pop())
1259 /// }
1260 /// # find_max_slow(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1261 /// ```
1262 #[stable(feature = "try_reserve_2", since = "1.63.0")]
1263 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1264 self.data.try_reserve_exact(additional)
1265 }
1266
1267 /// Tries to reserve capacity for at least `additional` elements more than the
1268 /// current length. The allocator may reserve more space to speculatively
1269 /// avoid frequent allocations. After calling `try_reserve`, capacity will be
1270 /// greater than or equal to `self.len() + additional` if it returns
1271 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1272 /// preserves the contents even if an error occurs.
1273 ///
1274 /// # Errors
1275 ///
1276 /// If the capacity overflows, or the allocator reports a failure, then an error
1277 /// is returned.
1278 ///
1279 /// # Examples
1280 ///
1281 /// ```
1282 /// use std::collections::BinaryHeap;
1283 /// use std::collections::TryReserveError;
1284 ///
1285 /// fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
1286 /// let mut heap = BinaryHeap::new();
1287 ///
1288 /// // Pre-reserve the memory, exiting if we can't
1289 /// heap.try_reserve(data.len())?;
1290 ///
1291 /// // Now we know this can't OOM in the middle of our complex work
1292 /// heap.extend(data.iter());
1293 ///
1294 /// Ok(heap.pop())
1295 /// }
1296 /// # find_max_slow(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1297 /// ```
1298 #[stable(feature = "try_reserve_2", since = "1.63.0")]
1299 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1300 self.data.try_reserve(additional)
1301 }
1302
1303 /// Discards as much additional capacity as possible.
1304 ///
1305 /// # Examples
1306 ///
1307 /// Basic usage:
1308 ///
1309 /// ```
1310 /// use std::collections::BinaryHeap;
1311 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
1312 ///
1313 /// assert!(heap.capacity() >= 100);
1314 /// heap.shrink_to_fit();
1315 /// assert!(heap.capacity() == 0);
1316 /// ```
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 pub fn shrink_to_fit(&mut self) {
1319 self.data.shrink_to_fit();
1320 }
1321
1322 /// Discards capacity with a lower bound.
1323 ///
1324 /// The capacity will remain at least as large as both the length
1325 /// and the supplied value.
1326 ///
1327 /// If the current capacity is less than the lower limit, this is a no-op.
1328 ///
1329 /// # Examples
1330 ///
1331 /// ```
1332 /// use std::collections::BinaryHeap;
1333 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
1334 ///
1335 /// assert!(heap.capacity() >= 100);
1336 /// heap.shrink_to(10);
1337 /// assert!(heap.capacity() >= 10);
1338 /// ```
1339 #[inline]
1340 #[stable(feature = "shrink_to", since = "1.56.0")]
1341 pub fn shrink_to(&mut self, min_capacity: usize) {
1342 self.data.shrink_to(min_capacity)
1343 }
1344
1345 /// Returns a slice of all values in the underlying vector, in arbitrary
1346 /// order.
1347 ///
1348 /// # Examples
1349 ///
1350 /// Basic usage:
1351 ///
1352 /// ```
1353 /// use std::collections::BinaryHeap;
1354 /// use std::io::{self, Write};
1355 ///
1356 /// let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
1357 ///
1358 /// io::sink().write(heap.as_slice()).unwrap();
1359 /// ```
1360 #[must_use]
1361 #[stable(feature = "binary_heap_as_slice", since = "1.80.0")]
1362 pub fn as_slice(&self) -> &[T] {
1363 self.data.as_slice()
1364 }
1365
1366 /// Returns a mutable slice of all values in the underlying vector.
1367 ///
1368 /// # Safety
1369 ///
1370 /// The caller must ensure that the slice remains a max-heap, i.e. for all indices
1371 /// `0 < i < slice.len()`, `slice[(i - 1) / 2] >= slice[i]`, before the borrow ends
1372 /// and the binary heap is used.
1373 ///
1374 /// # Examples
1375 ///
1376 /// Basic usage:
1377 ///
1378 /// ```
1379 /// #![feature(binary_heap_as_mut_slice)]
1380 ///
1381 /// use std::collections::BinaryHeap;
1382 ///
1383 /// let mut heap = BinaryHeap::<u32>::from([1, 2, 3, 4, 5, 6, 7]);
1384 ///
1385 /// unsafe {
1386 /// for value in heap.as_mut_slice() {
1387 /// *value = (*value).saturating_mul(2);
1388 /// }
1389 /// }
1390 /// ```
1391 #[must_use]
1392 #[unstable(feature = "binary_heap_as_mut_slice", issue = "154009")]
1393 pub unsafe fn as_mut_slice(&mut self) -> &mut [T] {
1394 self.data.as_mut_slice()
1395 }
1396
1397 /// Consumes the `BinaryHeap` and returns the underlying vector
1398 /// in arbitrary order.
1399 ///
1400 /// # Examples
1401 ///
1402 /// Basic usage:
1403 ///
1404 /// ```
1405 /// use std::collections::BinaryHeap;
1406 /// let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
1407 /// let vec = heap.into_vec();
1408 ///
1409 /// // Will print in some order
1410 /// for x in vec {
1411 /// println!("{x}");
1412 /// }
1413 /// ```
1414 #[must_use = "`self` will be dropped if the result is not used"]
1415 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1416 pub fn into_vec(self) -> Vec<T, A> {
1417 self.into()
1418 }
1419
1420 /// Returns a reference to the underlying allocator.
1421 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1422 #[inline]
1423 pub fn allocator(&self) -> &A {
1424 self.data.allocator()
1425 }
1426
1427 /// Returns the length of the binary heap.
1428 ///
1429 /// # Examples
1430 ///
1431 /// Basic usage:
1432 ///
1433 /// ```
1434 /// use std::collections::BinaryHeap;
1435 /// let heap = BinaryHeap::from([1, 3]);
1436 ///
1437 /// assert_eq!(heap.len(), 2);
1438 /// ```
1439 #[must_use]
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 #[rustc_confusables("length", "size")]
1442 pub fn len(&self) -> usize {
1443 self.data.len()
1444 }
1445
1446 /// Checks if the binary heap is empty.
1447 ///
1448 /// # Examples
1449 ///
1450 /// Basic usage:
1451 ///
1452 /// ```
1453 /// use std::collections::BinaryHeap;
1454 /// let mut heap = BinaryHeap::new();
1455 ///
1456 /// assert!(heap.is_empty());
1457 ///
1458 /// heap.push(3);
1459 /// heap.push(5);
1460 /// heap.push(1);
1461 ///
1462 /// assert!(!heap.is_empty());
1463 /// ```
1464 #[must_use]
1465 #[stable(feature = "rust1", since = "1.0.0")]
1466 pub fn is_empty(&self) -> bool {
1467 self.len() == 0
1468 }
1469
1470 /// Clears the binary heap, returning an iterator over the removed elements
1471 /// in arbitrary order. If the iterator is dropped before being fully
1472 /// consumed, it drops the remaining elements in arbitrary order.
1473 ///
1474 /// The returned iterator keeps a mutable borrow on the heap to optimize
1475 /// its implementation.
1476 ///
1477 /// # Examples
1478 ///
1479 /// Basic usage:
1480 ///
1481 /// ```
1482 /// use std::collections::BinaryHeap;
1483 /// let mut heap = BinaryHeap::from([1, 3]);
1484 ///
1485 /// assert!(!heap.is_empty());
1486 ///
1487 /// for x in heap.drain() {
1488 /// println!("{x}");
1489 /// }
1490 ///
1491 /// assert!(heap.is_empty());
1492 /// ```
1493 #[inline]
1494 #[stable(feature = "drain", since = "1.6.0")]
1495 pub fn drain(&mut self) -> Drain<'_, T, A>
1496 where
1497 A: AllocatorNightly, // needed for the `Vec::drain` call
1498 {
1499 Drain { iter: self.data.drain(..) }
1500 }
1501
1502 /// Drops all items from the binary heap.
1503 ///
1504 /// # Examples
1505 ///
1506 /// Basic usage:
1507 ///
1508 /// ```
1509 /// use std::collections::BinaryHeap;
1510 /// let mut heap = BinaryHeap::from([1, 3]);
1511 ///
1512 /// assert!(!heap.is_empty());
1513 ///
1514 /// heap.clear();
1515 ///
1516 /// assert!(heap.is_empty());
1517 /// ```
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 pub fn clear(&mut self)
1520 where
1521 A: AllocatorNightly,
1522 {
1523 self.drain();
1524 }
1525}
1526
1527/// Hole represents a hole in a slice i.e., an index without valid value
1528/// (because it was moved from or duplicated).
1529/// In drop, `Hole` will restore the slice by filling the hole
1530/// position with the value that was originally removed.
1531struct Hole<'a, T: 'a> {
1532 data: &'a mut [T],
1533 elt: ManuallyDrop<T>,
1534 pos: usize,
1535}
1536
1537impl<'a, T> Hole<'a, T> {
1538 /// Creates a new `Hole` at index `pos`.
1539 ///
1540 /// # Safety
1541 ///
1542 /// `pos` must be within the data slice.
1543 #[inline]
1544 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
1545 debug_assert!(pos < data.len());
1546 // SAFETY: Caller ensures pos is inside the slice.
1547 let elt = unsafe { ptr::read(data.get_unchecked(pos)) };
1548 Hole { data, elt: ManuallyDrop::new(elt), pos }
1549 }
1550
1551 #[inline]
1552 fn pos(&self) -> usize {
1553 self.pos
1554 }
1555
1556 /// Returns a reference to the element removed.
1557 #[inline]
1558 fn element(&self) -> &T {
1559 &self.elt
1560 }
1561
1562 /// Returns a reference to the element at `index`.
1563 ///
1564 /// # Safety
1565 ///
1566 /// `index` must be within the data slice and not equal to the current position.
1567 #[inline]
1568 unsafe fn get(&self, index: usize) -> &T {
1569 debug_assert!(index != self.pos);
1570 debug_assert!(index < self.data.len());
1571 // SAFETY: Upheld by caller.
1572 unsafe { self.data.get_unchecked(index) }
1573 }
1574
1575 /// Move hole to new location
1576 ///
1577 /// # Safety
1578 ///
1579 /// `index` must be within the data slice and not equal to the current position.
1580 #[inline]
1581 unsafe fn move_to(&mut self, index: usize) {
1582 debug_assert!(index != self.pos);
1583 debug_assert!(index < self.data.len());
1584 let ptr = self.data.as_mut_ptr();
1585 // ignore-tidy-undocumented-unsafe
1586 unsafe {
1587 let index_ptr: *const _ = ptr.add(index);
1588 let hole_ptr = ptr.add(self.pos);
1589 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1590 }
1591 self.pos = index;
1592 }
1593}
1594
1595impl<T> Drop for Hole<'_, T> {
1596 #[inline]
1597 fn drop(&mut self) {
1598 // fill the hole again
1599 let pos = self.pos;
1600 // ignore-tidy-undocumented-unsafe
1601 unsafe {
1602 ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
1603 }
1604 }
1605}
1606
1607/// An iterator over the elements of a `BinaryHeap`.
1608///
1609/// This `struct` is created by [`BinaryHeap::iter()`]. See its
1610/// documentation for more.
1611///
1612/// [`iter`]: BinaryHeap::iter
1613#[must_use = "iterators are lazy and do nothing unless consumed"]
1614#[stable(feature = "rust1", since = "1.0.0")]
1615pub struct Iter<'a, T: 'a> {
1616 iter: slice::Iter<'a, T>,
1617}
1618
1619#[stable(feature = "default_iters_sequel", since = "1.82.0")]
1620impl<T> Default for Iter<'_, T> {
1621 /// Creates an empty `binary_heap::Iter`.
1622 ///
1623 /// ```
1624 /// # use std::collections::binary_heap;
1625 /// let iter: binary_heap::Iter<'_, u8> = Default::default();
1626 /// assert_eq!(iter.len(), 0);
1627 /// ```
1628 fn default() -> Self {
1629 Iter { iter: Default::default() }
1630 }
1631}
1632
1633#[stable(feature = "collection_debug", since = "1.17.0")]
1634impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1635 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1636 f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
1637 }
1638}
1639
1640// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1641#[stable(feature = "rust1", since = "1.0.0")]
1642impl<T> Clone for Iter<'_, T> {
1643 fn clone(&self) -> Self {
1644 Iter { iter: self.iter.clone() }
1645 }
1646}
1647
1648#[stable(feature = "rust1", since = "1.0.0")]
1649impl<'a, T> Iterator for Iter<'a, T> {
1650 type Item = &'a T;
1651
1652 #[inline]
1653 fn next(&mut self) -> Option<&'a T> {
1654 self.iter.next()
1655 }
1656
1657 #[inline]
1658 fn size_hint(&self) -> (usize, Option<usize>) {
1659 self.iter.size_hint()
1660 }
1661
1662 #[inline]
1663 fn last(self) -> Option<&'a T> {
1664 self.iter.last()
1665 }
1666}
1667
1668#[stable(feature = "rust1", since = "1.0.0")]
1669impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1670 #[inline]
1671 fn next_back(&mut self) -> Option<&'a T> {
1672 self.iter.next_back()
1673 }
1674}
1675
1676#[stable(feature = "rust1", since = "1.0.0")]
1677impl<T> ExactSizeIterator for Iter<'_, T> {
1678 fn is_empty(&self) -> bool {
1679 self.iter.is_empty()
1680 }
1681}
1682
1683#[stable(feature = "fused", since = "1.26.0")]
1684impl<T> FusedIterator for Iter<'_, T> {}
1685
1686/// An owning iterator over the elements of a `BinaryHeap`.
1687///
1688/// This `struct` is created by [`BinaryHeap::into_iter()`]
1689/// (provided by the [`IntoIterator`] trait). See its documentation for more.
1690///
1691/// [`into_iter`]: BinaryHeap::into_iter
1692#[stable(feature = "rust1", since = "1.0.0")]
1693#[derive(Clone)]
1694pub struct IntoIter<
1695 T,
1696 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1697> {
1698 iter: vec::IntoIter<T, A>,
1699}
1700
1701impl<T, A: Allocator> IntoIter<T, A> {
1702 /// Returns a reference to the underlying allocator.
1703 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1704 pub fn allocator(&self) -> &A {
1705 self.iter.allocator()
1706 }
1707}
1708
1709#[stable(feature = "collection_debug", since = "1.17.0")]
1710impl<T: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<T, A> {
1711 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1712 f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
1713 }
1714}
1715
1716#[stable(feature = "rust1", since = "1.0.0")]
1717impl<T, A: Allocator> Iterator for IntoIter<T, A> {
1718 type Item = T;
1719
1720 #[inline]
1721 fn next(&mut self) -> Option<T> {
1722 self.iter.next()
1723 }
1724
1725 #[inline]
1726 fn size_hint(&self) -> (usize, Option<usize>) {
1727 self.iter.size_hint()
1728 }
1729}
1730
1731#[stable(feature = "rust1", since = "1.0.0")]
1732impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
1733 #[inline]
1734 fn next_back(&mut self) -> Option<T> {
1735 self.iter.next_back()
1736 }
1737}
1738
1739#[stable(feature = "rust1", since = "1.0.0")]
1740impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {
1741 fn is_empty(&self) -> bool {
1742 self.iter.is_empty()
1743 }
1744}
1745
1746#[stable(feature = "fused", since = "1.26.0")]
1747impl<T, A: Allocator> FusedIterator for IntoIter<T, A> {}
1748
1749#[doc(hidden)]
1750#[unstable(issue = "none", feature = "trusted_fused")]
1751unsafe impl<T, A: Allocator> TrustedFused for IntoIter<T, A> {}
1752
1753#[stable(feature = "default_iters", since = "1.70.0")]
1754impl<T> Default for IntoIter<T> {
1755 /// Creates an empty `binary_heap::IntoIter`.
1756 ///
1757 /// ```
1758 /// # use std::collections::binary_heap;
1759 /// let iter: binary_heap::IntoIter<u8> = Default::default();
1760 /// assert_eq!(iter.len(), 0);
1761 /// ```
1762 fn default() -> Self {
1763 IntoIter { iter: Default::default() }
1764 }
1765}
1766
1767// In addition to the SAFETY invariants of the following three unsafe traits
1768// also refer to the vec::in_place_collect module documentation to get an overview
1769#[unstable(issue = "none", feature = "inplace_iteration")]
1770#[doc(hidden)]
1771unsafe impl<T, A: Allocator> SourceIter for IntoIter<T, A> {
1772 type Source = IntoIter<T, A>;
1773
1774 #[inline]
1775 unsafe fn as_inner(&mut self) -> &mut Self::Source {
1776 self
1777 }
1778}
1779
1780#[unstable(issue = "none", feature = "inplace_iteration")]
1781#[doc(hidden)]
1782unsafe impl<I, A: Allocator> InPlaceIterable for IntoIter<I, A> {
1783 const EXPAND_BY: Option<NonZero<usize>> = NonZero::new(1);
1784 const MERGE_BY: Option<NonZero<usize>> = NonZero::new(1);
1785}
1786
1787#[cfg(not(test))]
1788unsafe impl<I> AsVecIntoIter for IntoIter<I> {
1789 type Item = I;
1790
1791 fn as_into_iter(&mut self) -> &mut vec::IntoIter<Self::Item> {
1792 &mut self.iter
1793 }
1794}
1795
1796#[must_use = "iterators are lazy and do nothing unless consumed"]
1797#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1798#[derive(Clone, Debug)]
1799pub struct IntoIterSorted<
1800 T,
1801 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1802> {
1803 inner: BinaryHeap<T, A>,
1804}
1805
1806impl<T, A: Allocator> IntoIterSorted<T, A> {
1807 /// Returns a reference to the underlying allocator.
1808 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1809 pub fn allocator(&self) -> &A {
1810 self.inner.allocator()
1811 }
1812}
1813
1814#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1815impl<T: Ord, A: Allocator> Iterator for IntoIterSorted<T, A> {
1816 type Item = T;
1817
1818 #[inline]
1819 fn next(&mut self) -> Option<T> {
1820 self.inner.pop()
1821 }
1822
1823 #[inline]
1824 fn size_hint(&self) -> (usize, Option<usize>) {
1825 let exact = self.inner.len();
1826 (exact, Some(exact))
1827 }
1828}
1829
1830#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1831impl<T: Ord, A: Allocator> ExactSizeIterator for IntoIterSorted<T, A> {}
1832
1833#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1834impl<T: Ord, A: Allocator> FusedIterator for IntoIterSorted<T, A> {}
1835
1836#[unstable(feature = "trusted_len", issue = "37572")]
1837unsafe impl<T: Ord, A: Allocator> TrustedLen for IntoIterSorted<T, A> {}
1838
1839/// A draining iterator over the elements of a `BinaryHeap`.
1840///
1841/// This `struct` is created by [`BinaryHeap::drain()`]. See its
1842/// documentation for more.
1843///
1844/// [`drain`]: BinaryHeap::drain
1845#[stable(feature = "drain", since = "1.6.0")]
1846#[derive(Debug)]
1847pub struct Drain<
1848 'a,
1849 T: 'a,
1850 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1851> {
1852 iter: vec::Drain<'a, T, A>,
1853}
1854
1855impl<T, A: Allocator> Drain<'_, T, A> {
1856 /// Returns a reference to the underlying allocator.
1857 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1858 pub fn allocator(&self) -> &A {
1859 self.iter.allocator()
1860 }
1861}
1862
1863#[stable(feature = "drain", since = "1.6.0")]
1864impl<T, A: Allocator> Iterator for Drain<'_, T, A> {
1865 type Item = T;
1866
1867 #[inline]
1868 fn next(&mut self) -> Option<T> {
1869 self.iter.next()
1870 }
1871
1872 #[inline]
1873 fn size_hint(&self) -> (usize, Option<usize>) {
1874 self.iter.size_hint()
1875 }
1876}
1877
1878#[stable(feature = "drain", since = "1.6.0")]
1879impl<T, A: Allocator> DoubleEndedIterator for Drain<'_, T, A> {
1880 #[inline]
1881 fn next_back(&mut self) -> Option<T> {
1882 self.iter.next_back()
1883 }
1884}
1885
1886#[stable(feature = "drain", since = "1.6.0")]
1887impl<T, A: Allocator> ExactSizeIterator for Drain<'_, T, A> {
1888 fn is_empty(&self) -> bool {
1889 self.iter.is_empty()
1890 }
1891}
1892
1893#[stable(feature = "fused", since = "1.26.0")]
1894impl<T, A: Allocator> FusedIterator for Drain<'_, T, A> {}
1895
1896/// A draining iterator over the elements of a `BinaryHeap`.
1897///
1898/// This `struct` is created by [`BinaryHeap::drain_sorted()`]. See its
1899/// documentation for more.
1900///
1901/// [`drain_sorted`]: BinaryHeap::drain_sorted
1902#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1903#[derive(Debug)]
1904pub struct DrainSorted<
1905 'a,
1906 T: Ord,
1907 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1908> {
1909 inner: &'a mut BinaryHeap<T, A>,
1910}
1911
1912impl<'a, T: Ord, A: Allocator> DrainSorted<'a, T, A> {
1913 /// Returns a reference to the underlying allocator.
1914 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1915 pub fn allocator(&self) -> &A {
1916 self.inner.allocator()
1917 }
1918}
1919
1920#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1921impl<'a, T: Ord, A: Allocator> Drop for DrainSorted<'a, T, A> {
1922 /// Removes heap elements in heap order.
1923 fn drop(&mut self) {
1924 struct DropGuard<'r, 'a, T: Ord, A: Allocator>(&'r mut DrainSorted<'a, T, A>);
1925
1926 impl<'r, 'a, T: Ord, A: Allocator> Drop for DropGuard<'r, 'a, T, A> {
1927 fn drop(&mut self) {
1928 while self.0.inner.pop().is_some() {}
1929 }
1930 }
1931
1932 while let Some(item) = self.inner.pop() {
1933 let guard = DropGuard(self);
1934 drop(item);
1935 mem::forget(guard);
1936 }
1937 }
1938}
1939
1940#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1941impl<T: Ord, A: Allocator> Iterator for DrainSorted<'_, T, A> {
1942 type Item = T;
1943
1944 #[inline]
1945 fn next(&mut self) -> Option<T> {
1946 self.inner.pop()
1947 }
1948
1949 #[inline]
1950 fn size_hint(&self) -> (usize, Option<usize>) {
1951 let exact = self.inner.len();
1952 (exact, Some(exact))
1953 }
1954}
1955
1956#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1957impl<T: Ord, A: Allocator> ExactSizeIterator for DrainSorted<'_, T, A> {}
1958
1959#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1960impl<T: Ord, A: Allocator> FusedIterator for DrainSorted<'_, T, A> {}
1961
1962#[unstable(feature = "trusted_len", issue = "37572")]
1963unsafe impl<T: Ord, A: Allocator> TrustedLen for DrainSorted<'_, T, A> {}
1964
1965#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1966impl<T: Ord, A: AllocatorNightly> From<Vec<T, A>> for BinaryHeap<T, A> {
1967 /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1968 ///
1969 /// This conversion happens in-place, and has *O*(*n*) time complexity.
1970 fn from(vec: Vec<T, A>) -> BinaryHeap<T, A> {
1971 let mut heap = BinaryHeap { data: vec };
1972 heap.rebuild();
1973 heap
1974 }
1975}
1976
1977#[stable(feature = "std_collections_from_array", since = "1.56.0")]
1978impl<T: Ord, const N: usize> From<[T; N]> for BinaryHeap<T> {
1979 /// ```
1980 /// use std::collections::BinaryHeap;
1981 ///
1982 /// let mut h1 = BinaryHeap::from([1, 4, 2, 3]);
1983 /// let mut h2: BinaryHeap<_> = [1, 4, 2, 3].into();
1984 /// while let Some((a, b)) = h1.pop().zip(h2.pop()) {
1985 /// assert_eq!(a, b);
1986 /// }
1987 /// ```
1988 fn from(arr: [T; N]) -> Self {
1989 Self::from_iter(arr)
1990 }
1991}
1992
1993#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1994impl<T, A: Allocator> From<BinaryHeap<T, A>> for Vec<T, A> {
1995 /// Converts a `BinaryHeap<T>` into a `Vec<T>`.
1996 ///
1997 /// This conversion requires no data movement or allocation, and has
1998 /// constant time complexity.
1999 fn from(heap: BinaryHeap<T, A>) -> Vec<T, A> {
2000 heap.data
2001 }
2002}
2003
2004#[stable(feature = "rust1", since = "1.0.0")]
2005impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
2006 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
2007 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
2008 }
2009}
2010
2011#[stable(feature = "rust1", since = "1.0.0")]
2012impl<T, A: Allocator> IntoIterator for BinaryHeap<T, A> {
2013 type Item = T;
2014 type IntoIter = IntoIter<T, A>;
2015
2016 /// Creates a consuming iterator, that is, one that moves each value out of
2017 /// the binary heap in arbitrary order. The binary heap cannot be used
2018 /// after calling this.
2019 ///
2020 /// # Examples
2021 ///
2022 /// Basic usage:
2023 ///
2024 /// ```
2025 /// use std::collections::BinaryHeap;
2026 /// let heap = BinaryHeap::from([1, 2, 3, 4]);
2027 ///
2028 /// // Print 1, 2, 3, 4 in arbitrary order
2029 /// for x in heap.into_iter() {
2030 /// // x has type i32, not &i32
2031 /// println!("{x}");
2032 /// }
2033 /// ```
2034 fn into_iter(self) -> IntoIter<T, A> {
2035 IntoIter { iter: self.data.into_iter() }
2036 }
2037}
2038
2039#[stable(feature = "rust1", since = "1.0.0")]
2040impl<'a, T, A: Allocator> IntoIterator for &'a BinaryHeap<T, A> {
2041 type Item = &'a T;
2042 type IntoIter = Iter<'a, T>;
2043
2044 fn into_iter(self) -> Iter<'a, T> {
2045 self.iter()
2046 }
2047}
2048
2049#[stable(feature = "rust1", since = "1.0.0")]
2050impl<T: Ord, A: Allocator> Extend<T> for BinaryHeap<T, A> {
2051 #[inline]
2052 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2053 let guard = RebuildOnDrop { rebuild_from: self.len(), heap: self };
2054 guard.heap.data.extend(iter);
2055 }
2056
2057 #[inline]
2058 fn extend_one(&mut self, item: T) {
2059 self.push(item);
2060 }
2061
2062 #[inline]
2063 fn extend_reserve(&mut self, additional: usize) {
2064 self.reserve(additional);
2065 }
2066}
2067
2068#[stable(feature = "extend_ref", since = "1.2.0")]
2069impl<'a, T: 'a + Ord + Copy, A: Allocator> Extend<&'a T> for BinaryHeap<T, A> {
2070 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2071 self.extend(iter.into_iter().cloned());
2072 }
2073
2074 #[inline]
2075 fn extend_one(&mut self, &item: &'a T) {
2076 self.push(item);
2077 }
2078
2079 #[inline]
2080 fn extend_reserve(&mut self, additional: usize) {
2081 self.reserve(additional);
2082 }
2083}