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#![stable(feature = "rust1", since = "1.0.0")]
144
145use core::alloc::Allocator;
146use core::iter::{FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen};
147use core::mem::{self, ManuallyDrop, swap};
148use core::num::NonZero;
149use core::ops::{Deref, DerefMut};
150use core::{fmt, ptr};
151
152use crate::alloc::{AllocatorNightly, Global};
153use crate::collections::TryReserveError;
154use crate::slice;
155#[cfg(not(test))]
156use crate::vec::AsVecIntoIter;
157use crate::vec::{self, Vec};
158
159/// A priority queue implemented with a binary heap.
160///
161/// This will be a max-heap.
162///
163/// It is a logic error for an item to be modified in such a way that the
164/// item's ordering relative to any other item, as determined by the [`Ord`]
165/// trait, changes while it is in the heap. This is normally only possible
166/// through interior mutability, global state, I/O, or unsafe code. The
167/// behavior resulting from such a logic error is not specified, but will
168/// be encapsulated to the `BinaryHeap` that observed the logic error and not
169/// result in undefined behavior. This could include panics, incorrect results,
170/// aborts, memory leaks, and non-termination.
171///
172/// As long as no elements change their relative order while being in the heap
173/// as described above, the API of `BinaryHeap` guarantees that the heap
174/// invariant remains intact i.e. its methods all behave as documented. For
175/// example if a method is documented as iterating in sorted order, that's
176/// guaranteed to work as long as elements in the heap have not changed order,
177/// even in the presence of closures getting unwinded out of, iterators getting
178/// leaked, and similar foolishness.
179///
180/// # Examples
181///
182/// ```
183/// use std::collections::BinaryHeap;
184///
185/// // Type inference lets us omit an explicit type signature (which
186/// // would be `BinaryHeap<i32>` in this example).
187/// let mut heap = BinaryHeap::new();
188///
189/// // We can use peek to look at the next item in the heap. In this case,
190/// // there's no items in there yet so we get None.
191/// assert_eq!(heap.peek(), None);
192///
193/// // Let's add some scores...
194/// heap.push(1);
195/// heap.push(5);
196/// heap.push(2);
197///
198/// // Now peek shows the most important item in the heap.
199/// assert_eq!(heap.peek(), Some(&5));
200///
201/// // We can check the length of a heap.
202/// assert_eq!(heap.len(), 3);
203///
204/// // We can iterate over the items in the heap, although they are returned in
205/// // a random order.
206/// for x in &heap {
207/// println!("{x}");
208/// }
209///
210/// // If we instead pop these scores, they should come back in order.
211/// assert_eq!(heap.pop(), Some(5));
212/// assert_eq!(heap.pop(), Some(2));
213/// assert_eq!(heap.pop(), Some(1));
214/// assert_eq!(heap.pop(), None);
215///
216/// // We can clear the heap of any remaining items.
217/// heap.clear();
218///
219/// // The heap should now be empty.
220/// assert!(heap.is_empty())
221/// ```
222///
223/// A `BinaryHeap` with a known list of items can be initialized from an array:
224///
225/// ```
226/// use std::collections::BinaryHeap;
227///
228/// let heap = BinaryHeap::from([1, 5, 2]);
229/// ```
230///
231/// ## Min-heap
232///
233/// Either [`core::cmp::Reverse`] or a custom [`Ord`] implementation can be used to
234/// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest
235/// value instead of the greatest one.
236///
237/// ```
238/// use std::collections::BinaryHeap;
239/// use std::cmp::Reverse;
240///
241/// let mut heap = BinaryHeap::new();
242///
243/// // Wrap values in `Reverse`
244/// heap.push(Reverse(1));
245/// heap.push(Reverse(5));
246/// heap.push(Reverse(2));
247///
248/// // If we pop these scores now, they should come back in the reverse order.
249/// assert_eq!(heap.pop(), Some(Reverse(1)));
250/// assert_eq!(heap.pop(), Some(Reverse(2)));
251/// assert_eq!(heap.pop(), Some(Reverse(5)));
252/// assert_eq!(heap.pop(), None);
253/// ```
254///
255/// # Time complexity
256///
257/// | [push] | [pop] | [peek]/[peek\_mut] |
258/// |---------|---------------|--------------------|
259/// | *O*(1)~ | *O*(log(*n*)) | *O*(1) |
260///
261/// The value for `push` is an expected cost; the method documentation gives a
262/// more detailed analysis.
263///
264/// [`core::cmp::Reverse`]: core::cmp::Reverse
265/// [`Cell`]: core::cell::Cell
266/// [`RefCell`]: core::cell::RefCell
267/// [push]: BinaryHeap::push
268/// [pop]: BinaryHeap::pop
269/// [peek]: BinaryHeap::peek
270/// [peek\_mut]: BinaryHeap::peek_mut
271#[stable(feature = "rust1", since = "1.0.0")]
272#[cfg_attr(not(test), rustc_diagnostic_item = "BinaryHeap")]
273pub struct BinaryHeap<
274 T,
275 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
276> {
277 data: Vec<T, A>,
278}
279
280/// Structure wrapping a mutable reference to the greatest item on a
281/// `BinaryHeap`.
282///
283/// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
284/// its documentation for more.
285///
286/// [`peek_mut`]: BinaryHeap::peek_mut
287#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
288pub struct PeekMut<
289 'a,
290 T: 'a + Ord,
291 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
292> {
293 heap: &'a mut BinaryHeap<T, A>,
294 // If a set_len + sift_down are required, this is Some. If a &mut T has not
295 // yet been exposed to peek_mut()'s caller, it's None.
296 original_len: Option<NonZero<usize>>,
297}
298
299#[stable(feature = "collection_debug", since = "1.17.0")]
300impl<T: Ord + fmt::Debug, A: Allocator> fmt::Debug for PeekMut<'_, T, A> {
301 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302 f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish()
303 }
304}
305
306#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
307impl<T: Ord, A: Allocator> Drop for PeekMut<'_, T, A> {
308 fn drop(&mut self) {
309 if let Some(original_len) = self.original_len {
310 // SAFETY: That's how many elements were in the Vec at the time of
311 // the PeekMut::deref_mut call, and therefore also at the time of
312 // the BinaryHeap::peek_mut call. Since the PeekMut did not end up
313 // getting leaked, we are now undoing the leak amplification that
314 // the DerefMut prepared for.
315 unsafe { self.heap.data.set_len(original_len.get()) };
316
317 // SAFETY: PeekMut is only instantiated for non-empty heaps.
318 unsafe { self.heap.sift_down(0) };
319 }
320 }
321}
322
323#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
324impl<T: Ord, A: Allocator> Deref for PeekMut<'_, T, A> {
325 type Target = T;
326 fn deref(&self) -> &T {
327 debug_assert!(!self.heap.is_empty());
328 // SAFETY: PeekMut is only instantiated for non-empty heaps
329 unsafe { self.heap.data.get_unchecked(0) }
330 }
331}
332
333#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
334impl<T: Ord, A: Allocator> DerefMut for PeekMut<'_, T, A> {
335 fn deref_mut(&mut self) -> &mut T {
336 debug_assert!(!self.heap.is_empty());
337
338 let len = self.heap.len();
339 if len > 1 {
340 // Here we preemptively leak all the rest of the underlying vector
341 // after the currently max element. If the caller mutates the &mut T
342 // we're about to give them, and then leaks the PeekMut, all these
343 // elements will remain leaked. If they don't leak the PeekMut, then
344 // either Drop or PeekMut::pop will un-leak the vector elements.
345 //
346 // This is technique is described throughout several other places in
347 // the standard library as "leak amplification".
348 // SAFETY: len > 1 so len != 0.
349 self.original_len = Some(unsafe { NonZero::new_unchecked(len) });
350 // SAFETY: len > 1 so all this does for now is leak elements,
351 // which is safe.
352 unsafe { self.heap.data.set_len(1) };
353 }
354
355 // SAFETY: PeekMut is only instantiated for non-empty heaps
356 unsafe { self.heap.data.get_unchecked_mut(0) }
357 }
358}
359
360impl<'a, T: Ord, A: Allocator> PeekMut<'a, T, A> {
361 /// Sifts the current element to its new position.
362 ///
363 /// Afterwards refers to the new element. Returns if the element changed.
364 ///
365 /// ## Examples
366 ///
367 /// The condition can be used to upper bound all elements in the heap. When only few elements
368 /// are affected, the heap's sort ensures this is faster than a reconstruction from the raw
369 /// element list and requires no additional allocation.
370 ///
371 /// ```
372 /// #![feature(binary_heap_peek_mut_refresh)]
373 /// use std::collections::BinaryHeap;
374 ///
375 /// let mut heap: BinaryHeap<u32> = (0..128).collect();
376 /// let mut peek = heap.peek_mut().unwrap();
377 ///
378 /// loop {
379 /// *peek = 99;
380 ///
381 /// if !peek.refresh() {
382 /// break;
383 /// }
384 /// }
385 ///
386 /// // Post condition, this is now an upper bound.
387 /// assert!(*peek < 100);
388 /// ```
389 ///
390 /// When the element remains the maximum after modification, the peek remains unchanged:
391 ///
392 /// ```
393 /// #![feature(binary_heap_peek_mut_refresh)]
394 /// use std::collections::BinaryHeap;
395 ///
396 /// let mut heap: BinaryHeap<u32> = [1, 2, 3].into();
397 /// let mut peek = heap.peek_mut().unwrap();
398 ///
399 /// assert_eq!(*peek, 3);
400 /// *peek = 42;
401 ///
402 /// // When we refresh, the peek is updated to the new maximum.
403 /// assert!(!peek.refresh(), "42 is even larger than 3");
404 /// assert_eq!(*peek, 42);
405 /// ```
406 #[unstable(feature = "binary_heap_peek_mut_refresh", issue = "138355")]
407 #[must_use = "is equivalent to dropping and getting a new PeekMut except for return information"]
408 pub fn refresh(&mut self) -> bool {
409 // The length of the underlying heap is unchanged by sifting down. The value stored for leak
410 // amplification thus remains accurate. We erase the leak amplification firstly because the
411 // operation is then equivalent to constructing a new PeekMut and secondly this avoids any
412 // future complication where original_len being non-empty would be interpreted as the heap
413 // having been leak amplified instead of checking the heap itself.
414 if let Some(original_len) = self.original_len.take() {
415 // SAFETY: This is how many elements were in the Vec at the time of
416 // the BinaryHeap::peek_mut call.
417 unsafe { self.heap.data.set_len(original_len.get()) };
418
419 // The length of the heap did not change by sifting, upholding our own invariants.
420
421 // SAFETY: PeekMut is only instantiated for non-empty heaps.
422 (unsafe { self.heap.sift_down(0) }) != 0
423 } else {
424 // The element was not modified.
425 false
426 }
427 }
428
429 /// Removes the peeked value from the heap and returns it.
430 #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
431 pub fn pop(mut this: PeekMut<'a, T, A>) -> T {
432 if let Some(original_len) = this.original_len.take() {
433 // SAFETY: This is how many elements were in the Vec at the time of
434 // the BinaryHeap::peek_mut call.
435 unsafe { this.heap.data.set_len(original_len.get()) };
436
437 // Unlike in Drop, here we don't also need to do a sift_down even if
438 // the caller could've mutated the element. It is removed from the
439 // heap on the next line and pop() is not sensitive to its value.
440 }
441
442 // SAFETY: Have a `PeekMut` element proves that the associated binary heap being non-empty,
443 // so the `pop` operation will not fail.
444 unsafe { this.heap.pop().unwrap_unchecked() }
445 }
446}
447
448#[stable(feature = "rust1", since = "1.0.0")]
449impl<T: Clone, A: Allocator + Clone> Clone for BinaryHeap<T, A> {
450 fn clone(&self) -> Self {
451 BinaryHeap { data: self.data.clone() }
452 }
453
454 /// Overwrites the contents of `self` with a clone of the contents of `source`.
455 ///
456 /// This method is preferred over simply assigning `source.clone()` to `self`,
457 /// as it avoids reallocation if possible.
458 ///
459 /// See [`Vec::clone_from()`] for more details.
460 fn clone_from(&mut self, source: &Self) {
461 self.data.clone_from(&source.data);
462 }
463}
464
465#[stable(feature = "rust1", since = "1.0.0")]
466impl<T> Default for BinaryHeap<T> {
467 /// Creates an empty `BinaryHeap<T>`.
468 #[inline]
469 fn default() -> BinaryHeap<T> {
470 BinaryHeap::new()
471 }
472}
473
474#[stable(feature = "binaryheap_debug", since = "1.4.0")]
475impl<T: fmt::Debug, A: Allocator> fmt::Debug for BinaryHeap<T, A> {
476 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
477 f.debug_list().entries(self.iter()).finish()
478 }
479}
480
481struct RebuildOnDrop<
482 'a,
483 T: Ord,
484 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
485> {
486 heap: &'a mut BinaryHeap<T, A>,
487 rebuild_from: usize,
488}
489
490impl<T: Ord, A: Allocator> Drop for RebuildOnDrop<'_, T, A> {
491 fn drop(&mut self) {
492 self.heap.rebuild_tail(self.rebuild_from);
493 }
494}
495
496impl<T> BinaryHeap<T> {
497 /// Creates an empty `BinaryHeap` as a max-heap.
498 ///
499 /// # Examples
500 ///
501 /// Basic usage:
502 ///
503 /// ```
504 /// use std::collections::BinaryHeap;
505 /// let mut heap = BinaryHeap::new();
506 /// heap.push(4);
507 /// ```
508 #[stable(feature = "rust1", since = "1.0.0")]
509 #[rustc_const_stable(feature = "const_binary_heap_constructor", since = "1.80.0")]
510 #[must_use]
511 pub const fn new() -> BinaryHeap<T> {
512 BinaryHeap { data: vec![] }
513 }
514
515 /// Creates an empty `BinaryHeap` with at least the specified capacity.
516 ///
517 /// The binary heap will be able to hold at least `capacity` elements without
518 /// reallocating. This method is allowed to allocate for more elements than
519 /// `capacity`. If `capacity` is zero, the binary heap will not allocate.
520 ///
521 /// # Examples
522 ///
523 /// Basic usage:
524 ///
525 /// ```
526 /// use std::collections::BinaryHeap;
527 /// let mut heap = BinaryHeap::with_capacity(10);
528 /// heap.push(4);
529 /// ```
530 #[stable(feature = "rust1", since = "1.0.0")]
531 #[must_use]
532 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
533 BinaryHeap { data: Vec::with_capacity(capacity) }
534 }
535}
536
537impl<T, A: Allocator> BinaryHeap<T, A> {
538 /// Creates an empty `BinaryHeap` as a max-heap, using `A` as allocator.
539 ///
540 /// # Examples
541 ///
542 /// Basic usage:
543 ///
544 /// ```
545 /// #![feature(allocator_ext)]
546 ///
547 /// use std::alloc::System;
548 /// use std::collections::BinaryHeap;
549 ///
550 /// let heap : BinaryHeap<i32, System> = BinaryHeap::new_in(System);
551 /// ```
552 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
553 #[rustc_const_unstable(feature = "allocator_ext", issue = "163177")]
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_ext)]
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_ext", issue = "163177", implied_by = "allocator_api")]
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 /// For performance, `self` and `other` may be swapped before appending.
982 ///
983 /// # Examples
984 ///
985 /// Basic usage:
986 ///
987 /// ```
988 /// use std::collections::BinaryHeap;
989 ///
990 /// let mut a = BinaryHeap::from([-10, 1, 2, 3, 3]);
991 /// let mut b = BinaryHeap::from([-20, 5, 43]);
992 ///
993 /// a.append(&mut b);
994 ///
995 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
996 /// assert!(b.is_empty());
997 /// ```
998 #[stable(feature = "binary_heap_append", since = "1.11.0")]
999 pub fn append(&mut self, other: &mut Self) {
1000 if self.len() < other.len() {
1001 swap(self, other);
1002 }
1003
1004 let start = self.data.len();
1005
1006 self.data.append(&mut other.data);
1007
1008 self.rebuild_tail(start);
1009 }
1010
1011 /// Clears the binary heap, returning an iterator over the removed elements
1012 /// in heap order. If the iterator is dropped before being fully consumed,
1013 /// it drops the remaining elements in heap order.
1014 ///
1015 /// The returned iterator keeps a mutable borrow on the heap to optimize
1016 /// its implementation.
1017 ///
1018 /// Note:
1019 /// * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`.
1020 /// You should use the latter for most cases.
1021 ///
1022 /// # Examples
1023 ///
1024 /// Basic usage:
1025 ///
1026 /// ```
1027 /// #![feature(binary_heap_drain_sorted)]
1028 /// use std::collections::BinaryHeap;
1029 ///
1030 /// let mut heap = BinaryHeap::from([1, 2, 3, 4, 5]);
1031 /// assert_eq!(heap.len(), 5);
1032 ///
1033 /// drop(heap.drain_sorted()); // removes all elements in heap order
1034 /// assert_eq!(heap.len(), 0);
1035 /// ```
1036 #[inline]
1037 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1038 pub fn drain_sorted(&mut self) -> DrainSorted<'_, T, A> {
1039 DrainSorted { inner: self }
1040 }
1041
1042 /// Retains only the elements specified by the predicate.
1043 ///
1044 /// In other words, remove all elements `e` for which `f(&e)` returns
1045 /// `false`. The elements are visited in unsorted (and unspecified) order.
1046 ///
1047 /// # Examples
1048 ///
1049 /// Basic usage:
1050 ///
1051 /// ```
1052 /// use std::collections::BinaryHeap;
1053 ///
1054 /// let mut heap = BinaryHeap::from([-10, -5, 1, 2, 4, 13]);
1055 ///
1056 /// heap.retain(|x| x % 2 == 0); // only keep even numbers
1057 ///
1058 /// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
1059 /// ```
1060 #[stable(feature = "binary_heap_retain", since = "1.70.0")]
1061 pub fn retain<F>(&mut self, mut f: F)
1062 where
1063 F: FnMut(&T) -> bool,
1064 {
1065 // rebuild_start will be updated to the first touched element below, and the rebuild will
1066 // only be done for the tail.
1067 let mut guard = RebuildOnDrop { rebuild_from: self.len(), heap: self };
1068 let mut i = 0;
1069
1070 guard.heap.data.retain(|e| {
1071 let keep = f(e);
1072 if !keep && i < guard.rebuild_from {
1073 guard.rebuild_from = i;
1074 }
1075 i += 1;
1076 keep
1077 });
1078 }
1079}
1080
1081impl<T, A: Allocator> BinaryHeap<T, A> {
1082 /// Returns an iterator visiting all values in the underlying vector, in
1083 /// arbitrary order.
1084 ///
1085 /// # Examples
1086 ///
1087 /// Basic usage:
1088 ///
1089 /// ```
1090 /// use std::collections::BinaryHeap;
1091 /// let heap = BinaryHeap::from([1, 2, 3, 4]);
1092 ///
1093 /// // Print 1, 2, 3, 4 in arbitrary order
1094 /// for x in heap.iter() {
1095 /// println!("{x}");
1096 /// }
1097 /// ```
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 #[cfg_attr(not(test), rustc_diagnostic_item = "binaryheap_iter")]
1100 pub fn iter(&self) -> Iter<'_, T> {
1101 Iter { iter: self.data.iter() }
1102 }
1103
1104 /// Returns an iterator which retrieves elements in heap order.
1105 ///
1106 /// This method consumes the original heap.
1107 ///
1108 /// # Examples
1109 ///
1110 /// Basic usage:
1111 ///
1112 /// ```
1113 /// #![feature(binary_heap_into_iter_sorted)]
1114 /// use std::collections::BinaryHeap;
1115 /// let heap = BinaryHeap::from([1, 2, 3, 4, 5]);
1116 ///
1117 /// assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), [5, 4]);
1118 /// ```
1119 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1120 pub fn into_iter_sorted(self) -> IntoIterSorted<T, A> {
1121 IntoIterSorted { inner: self }
1122 }
1123
1124 /// Returns the greatest item in the binary heap, or `None` if it is empty.
1125 ///
1126 /// # Examples
1127 ///
1128 /// Basic usage:
1129 ///
1130 /// ```
1131 /// use std::collections::BinaryHeap;
1132 /// let mut heap = BinaryHeap::new();
1133 /// assert_eq!(heap.peek(), None);
1134 ///
1135 /// heap.push(1);
1136 /// heap.push(5);
1137 /// heap.push(2);
1138 /// assert_eq!(heap.peek(), Some(&5));
1139 ///
1140 /// ```
1141 ///
1142 /// # Time complexity
1143 ///
1144 /// Cost is *O*(1) in the worst case.
1145 #[must_use]
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 pub fn peek(&self) -> Option<&T> {
1148 self.data.get(0)
1149 }
1150
1151 /// Returns the number of elements the binary heap can hold without reallocating.
1152 ///
1153 /// # Examples
1154 ///
1155 /// Basic usage:
1156 ///
1157 /// ```
1158 /// use std::collections::BinaryHeap;
1159 /// let mut heap = BinaryHeap::with_capacity(100);
1160 /// assert!(heap.capacity() >= 100);
1161 /// heap.push(4);
1162 /// ```
1163 #[must_use]
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 pub fn capacity(&self) -> usize {
1166 self.data.capacity()
1167 }
1168
1169 /// Reserves the minimum capacity for at least `additional` elements more than
1170 /// the current length. Unlike [`reserve`], this will not
1171 /// deliberately over-allocate to speculatively avoid frequent allocations.
1172 /// After calling `reserve_exact`, capacity will be greater than or equal to
1173 /// `self.len() + additional`. Does nothing if the capacity is already
1174 /// sufficient.
1175 ///
1176 /// [`reserve`]: BinaryHeap::reserve
1177 ///
1178 /// # Panics
1179 ///
1180 /// Panics if the new capacity overflows [`usize`].
1181 ///
1182 /// # Examples
1183 ///
1184 /// Basic usage:
1185 ///
1186 /// ```
1187 /// use std::collections::BinaryHeap;
1188 /// let mut heap = BinaryHeap::new();
1189 /// heap.reserve_exact(100);
1190 /// assert!(heap.capacity() >= 100);
1191 /// heap.push(4);
1192 /// ```
1193 ///
1194 /// [`reserve`]: BinaryHeap::reserve
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 pub fn reserve_exact(&mut self, additional: usize) {
1197 self.data.reserve_exact(additional);
1198 }
1199
1200 /// Reserves capacity for at least `additional` elements more than the
1201 /// current length. The allocator may reserve more space to speculatively
1202 /// avoid frequent allocations. After calling `reserve`,
1203 /// capacity will be greater than or equal to `self.len() + additional`.
1204 /// Does nothing if capacity is already sufficient.
1205 ///
1206 /// # Panics
1207 ///
1208 /// Panics if the new capacity overflows [`usize`].
1209 ///
1210 /// # Examples
1211 ///
1212 /// Basic usage:
1213 ///
1214 /// ```
1215 /// use std::collections::BinaryHeap;
1216 /// let mut heap = BinaryHeap::new();
1217 /// heap.reserve(100);
1218 /// assert!(heap.capacity() >= 100);
1219 /// heap.push(4);
1220 /// ```
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 pub fn reserve(&mut self, additional: usize) {
1223 self.data.reserve(additional);
1224 }
1225
1226 /// Tries to reserve the minimum capacity for at least `additional` elements
1227 /// more than the current length. Unlike [`try_reserve`], this will not
1228 /// deliberately over-allocate to speculatively avoid frequent allocations.
1229 /// After calling `try_reserve_exact`, capacity will be greater than or
1230 /// equal to `self.len() + additional` if it returns `Ok(())`.
1231 /// Does nothing if the capacity is already sufficient.
1232 ///
1233 /// Note that the allocator may give the collection more space than it
1234 /// requests. Therefore, capacity can not be relied upon to be precisely
1235 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1236 ///
1237 /// [`try_reserve`]: BinaryHeap::try_reserve
1238 ///
1239 /// # Errors
1240 ///
1241 /// If the capacity overflows, or the allocator reports a failure, then an error
1242 /// is returned.
1243 ///
1244 /// # Examples
1245 ///
1246 /// ```
1247 /// use std::collections::BinaryHeap;
1248 /// use std::collections::TryReserveError;
1249 ///
1250 /// fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
1251 /// let mut heap = BinaryHeap::new();
1252 ///
1253 /// // Pre-reserve the memory, exiting if we can't
1254 /// heap.try_reserve_exact(data.len())?;
1255 ///
1256 /// // Now we know this can't OOM in the middle of our complex work
1257 /// heap.extend(data.iter());
1258 ///
1259 /// Ok(heap.pop())
1260 /// }
1261 /// # find_max_slow(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1262 /// ```
1263 #[stable(feature = "try_reserve_2", since = "1.63.0")]
1264 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1265 self.data.try_reserve_exact(additional)
1266 }
1267
1268 /// Tries to reserve capacity for at least `additional` elements more than the
1269 /// current length. The allocator may reserve more space to speculatively
1270 /// avoid frequent allocations. After calling `try_reserve`, capacity will be
1271 /// greater than or equal to `self.len() + additional` if it returns
1272 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1273 /// preserves the contents even if an error occurs.
1274 ///
1275 /// # Errors
1276 ///
1277 /// If the capacity overflows, or the allocator reports a failure, then an error
1278 /// is returned.
1279 ///
1280 /// # Examples
1281 ///
1282 /// ```
1283 /// use std::collections::BinaryHeap;
1284 /// use std::collections::TryReserveError;
1285 ///
1286 /// fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
1287 /// let mut heap = BinaryHeap::new();
1288 ///
1289 /// // Pre-reserve the memory, exiting if we can't
1290 /// heap.try_reserve(data.len())?;
1291 ///
1292 /// // Now we know this can't OOM in the middle of our complex work
1293 /// heap.extend(data.iter());
1294 ///
1295 /// Ok(heap.pop())
1296 /// }
1297 /// # find_max_slow(&[1, 2, 3]).expect("reserving capacity for 12 bytes should never fail");
1298 /// ```
1299 #[stable(feature = "try_reserve_2", since = "1.63.0")]
1300 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1301 self.data.try_reserve(additional)
1302 }
1303
1304 /// Discards as much additional capacity as possible.
1305 ///
1306 /// # Examples
1307 ///
1308 /// Basic usage:
1309 ///
1310 /// ```
1311 /// use std::collections::BinaryHeap;
1312 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
1313 ///
1314 /// assert!(heap.capacity() >= 100);
1315 /// heap.shrink_to_fit();
1316 /// assert!(heap.capacity() == 0);
1317 /// ```
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 pub fn shrink_to_fit(&mut self) {
1320 self.data.shrink_to_fit();
1321 }
1322
1323 /// Discards capacity with a lower bound.
1324 ///
1325 /// The capacity will remain at least as large as both the length
1326 /// and the supplied value.
1327 ///
1328 /// If the current capacity is less than the lower limit, this is a no-op.
1329 ///
1330 /// # Examples
1331 ///
1332 /// ```
1333 /// use std::collections::BinaryHeap;
1334 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
1335 ///
1336 /// assert!(heap.capacity() >= 100);
1337 /// heap.shrink_to(10);
1338 /// assert!(heap.capacity() >= 10);
1339 /// ```
1340 #[inline]
1341 #[stable(feature = "shrink_to", since = "1.56.0")]
1342 pub fn shrink_to(&mut self, min_capacity: usize) {
1343 self.data.shrink_to(min_capacity)
1344 }
1345
1346 /// Returns a slice of all values in the underlying vector, in arbitrary
1347 /// order.
1348 ///
1349 /// # Examples
1350 ///
1351 /// Basic usage:
1352 ///
1353 /// ```
1354 /// use std::collections::BinaryHeap;
1355 /// use std::io::{self, Write};
1356 ///
1357 /// let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
1358 ///
1359 /// io::sink().write(heap.as_slice()).unwrap();
1360 /// ```
1361 #[must_use]
1362 #[stable(feature = "binary_heap_as_slice", since = "1.80.0")]
1363 pub fn as_slice(&self) -> &[T] {
1364 self.data.as_slice()
1365 }
1366
1367 /// Returns a mutable slice of all values in the underlying vector.
1368 ///
1369 /// # Safety
1370 ///
1371 /// The caller must ensure that the slice remains a max-heap, i.e. for all indices
1372 /// `0 < i < slice.len()`, `slice[(i - 1) / 2] >= slice[i]`, before the borrow ends
1373 /// and the binary heap is used.
1374 ///
1375 /// # Examples
1376 ///
1377 /// Basic usage:
1378 ///
1379 /// ```
1380 /// #![feature(binary_heap_as_mut_slice)]
1381 ///
1382 /// use std::collections::BinaryHeap;
1383 ///
1384 /// let mut heap = BinaryHeap::<u32>::from([1, 2, 3, 4, 5, 6, 7]);
1385 ///
1386 /// unsafe {
1387 /// for value in heap.as_mut_slice() {
1388 /// *value = (*value).saturating_mul(2);
1389 /// }
1390 /// }
1391 /// ```
1392 #[must_use]
1393 #[unstable(feature = "binary_heap_as_mut_slice", issue = "154009")]
1394 pub unsafe fn as_mut_slice(&mut self) -> &mut [T] {
1395 self.data.as_mut_slice()
1396 }
1397
1398 /// Consumes the `BinaryHeap` and returns the underlying vector
1399 /// in arbitrary order.
1400 ///
1401 /// # Examples
1402 ///
1403 /// Basic usage:
1404 ///
1405 /// ```
1406 /// use std::collections::BinaryHeap;
1407 /// let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
1408 /// let vec = heap.into_vec();
1409 ///
1410 /// // Will print in some order
1411 /// for x in vec {
1412 /// println!("{x}");
1413 /// }
1414 /// ```
1415 #[must_use = "`self` will be dropped if the result is not used"]
1416 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1417 pub fn into_vec(self) -> Vec<T, A> {
1418 self.into()
1419 }
1420
1421 /// Returns a reference to the underlying allocator.
1422 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1423 #[inline]
1424 pub fn allocator(&self) -> &A {
1425 self.data.allocator()
1426 }
1427
1428 /// Returns the length of the binary heap.
1429 ///
1430 /// # Examples
1431 ///
1432 /// Basic usage:
1433 ///
1434 /// ```
1435 /// use std::collections::BinaryHeap;
1436 /// let heap = BinaryHeap::from([1, 3]);
1437 ///
1438 /// assert_eq!(heap.len(), 2);
1439 /// ```
1440 #[must_use]
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 #[rustc_confusables("length", "size")]
1443 #[rustc_const_stable(feature = "const_binary_heap_len", since = "1.101.0")]
1444 pub const fn len(&self) -> usize {
1445 self.data.len()
1446 }
1447
1448 /// Checks if the binary heap is empty.
1449 ///
1450 /// # Examples
1451 ///
1452 /// Basic usage:
1453 ///
1454 /// ```
1455 /// use std::collections::BinaryHeap;
1456 /// let mut heap = BinaryHeap::new();
1457 ///
1458 /// assert!(heap.is_empty());
1459 ///
1460 /// heap.push(3);
1461 /// heap.push(5);
1462 /// heap.push(1);
1463 ///
1464 /// assert!(!heap.is_empty());
1465 /// ```
1466 #[must_use]
1467 #[stable(feature = "rust1", since = "1.0.0")]
1468 #[rustc_const_stable(feature = "const_binary_heap_len", since = "1.101.0")]
1469 pub const fn is_empty(&self) -> bool {
1470 self.len() == 0
1471 }
1472
1473 /// Clears the binary heap, returning an iterator over the removed elements
1474 /// in arbitrary order. If the iterator is dropped before being fully
1475 /// consumed, it drops the remaining elements in arbitrary order.
1476 ///
1477 /// The returned iterator keeps a mutable borrow on the heap to optimize
1478 /// its implementation.
1479 ///
1480 /// # Examples
1481 ///
1482 /// Basic usage:
1483 ///
1484 /// ```
1485 /// use std::collections::BinaryHeap;
1486 /// let mut heap = BinaryHeap::from([1, 3]);
1487 ///
1488 /// assert!(!heap.is_empty());
1489 ///
1490 /// for x in heap.drain() {
1491 /// println!("{x}");
1492 /// }
1493 ///
1494 /// assert!(heap.is_empty());
1495 /// ```
1496 #[inline]
1497 #[stable(feature = "drain", since = "1.6.0")]
1498 pub fn drain(&mut self) -> Drain<'_, T, A>
1499 where
1500 A: AllocatorNightly, // needed for the `Vec::drain` call
1501 {
1502 Drain { iter: self.data.drain(..) }
1503 }
1504
1505 /// Drops all items from the binary heap.
1506 ///
1507 /// # Examples
1508 ///
1509 /// Basic usage:
1510 ///
1511 /// ```
1512 /// use std::collections::BinaryHeap;
1513 /// let mut heap = BinaryHeap::from([1, 3]);
1514 ///
1515 /// assert!(!heap.is_empty());
1516 ///
1517 /// heap.clear();
1518 ///
1519 /// assert!(heap.is_empty());
1520 /// ```
1521 #[stable(feature = "rust1", since = "1.0.0")]
1522 pub fn clear(&mut self)
1523 where
1524 A: AllocatorNightly,
1525 {
1526 self.drain();
1527 }
1528}
1529
1530/// Hole represents a hole in a slice i.e., an index without valid value
1531/// (because it was moved from or duplicated).
1532/// In drop, `Hole` will restore the slice by filling the hole
1533/// position with the value that was originally removed.
1534struct Hole<'a, T: 'a> {
1535 data: &'a mut [T],
1536 elt: ManuallyDrop<T>,
1537 pos: usize,
1538}
1539
1540impl<'a, T> Hole<'a, T> {
1541 /// Creates a new `Hole` at index `pos`.
1542 ///
1543 /// # Safety
1544 ///
1545 /// `pos` must be within the data slice.
1546 #[inline]
1547 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
1548 debug_assert!(pos < data.len());
1549 // SAFETY: Caller ensures pos is inside the slice.
1550 let elt = unsafe { ptr::read(data.get_unchecked(pos)) };
1551 Hole { data, elt: ManuallyDrop::new(elt), pos }
1552 }
1553
1554 #[inline]
1555 fn pos(&self) -> usize {
1556 self.pos
1557 }
1558
1559 /// Returns a reference to the element removed.
1560 #[inline]
1561 fn element(&self) -> &T {
1562 &self.elt
1563 }
1564
1565 /// Returns a reference to the element at `index`.
1566 ///
1567 /// # Safety
1568 ///
1569 /// `index` must be within the data slice and not equal to the current position.
1570 #[inline]
1571 unsafe fn get(&self, index: usize) -> &T {
1572 debug_assert!(index != self.pos);
1573 debug_assert!(index < self.data.len());
1574 // SAFETY: Upheld by caller.
1575 unsafe { self.data.get_unchecked(index) }
1576 }
1577
1578 /// Move hole to new location
1579 ///
1580 /// # Safety
1581 ///
1582 /// `index` must be within the data slice and not equal to the current position.
1583 #[inline]
1584 unsafe fn move_to(&mut self, index: usize) {
1585 debug_assert!(index != self.pos);
1586 debug_assert!(index < self.data.len());
1587 let ptr = self.data.as_mut_ptr();
1588 // ignore-tidy-undocumented-unsafe
1589 unsafe {
1590 let index_ptr: *const _ = ptr.add(index);
1591 let hole_ptr = ptr.add(self.pos);
1592 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1593 }
1594 self.pos = index;
1595 }
1596}
1597
1598impl<T> Drop for Hole<'_, T> {
1599 #[inline]
1600 fn drop(&mut self) {
1601 // fill the hole again
1602 let pos = self.pos;
1603 // ignore-tidy-undocumented-unsafe
1604 unsafe {
1605 ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
1606 }
1607 }
1608}
1609
1610/// An iterator over the elements of a `BinaryHeap`.
1611///
1612/// This `struct` is created by [`BinaryHeap::iter()`]. See its
1613/// documentation for more.
1614///
1615/// [`iter`]: BinaryHeap::iter
1616#[must_use = "iterators are lazy and do nothing unless consumed"]
1617#[stable(feature = "rust1", since = "1.0.0")]
1618pub struct Iter<'a, T: 'a> {
1619 iter: slice::Iter<'a, T>,
1620}
1621
1622#[stable(feature = "default_iters_sequel", since = "1.82.0")]
1623impl<T> Default for Iter<'_, T> {
1624 /// Creates an empty `binary_heap::Iter`.
1625 ///
1626 /// ```
1627 /// # use std::collections::binary_heap;
1628 /// let iter: binary_heap::Iter<'_, u8> = Default::default();
1629 /// assert_eq!(iter.len(), 0);
1630 /// ```
1631 fn default() -> Self {
1632 Iter { iter: Default::default() }
1633 }
1634}
1635
1636#[stable(feature = "collection_debug", since = "1.17.0")]
1637impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1638 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1639 f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
1640 }
1641}
1642
1643// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1644#[stable(feature = "rust1", since = "1.0.0")]
1645impl<T> Clone for Iter<'_, T> {
1646 fn clone(&self) -> Self {
1647 Iter { iter: self.iter.clone() }
1648 }
1649}
1650
1651#[stable(feature = "rust1", since = "1.0.0")]
1652impl<'a, T> Iterator for Iter<'a, T> {
1653 type Item = &'a T;
1654
1655 #[inline]
1656 fn next(&mut self) -> Option<&'a T> {
1657 self.iter.next()
1658 }
1659
1660 #[inline]
1661 fn size_hint(&self) -> (usize, Option<usize>) {
1662 self.iter.size_hint()
1663 }
1664
1665 #[inline]
1666 fn last(self) -> Option<&'a T> {
1667 self.iter.last()
1668 }
1669}
1670
1671#[stable(feature = "rust1", since = "1.0.0")]
1672impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1673 #[inline]
1674 fn next_back(&mut self) -> Option<&'a T> {
1675 self.iter.next_back()
1676 }
1677}
1678
1679#[stable(feature = "rust1", since = "1.0.0")]
1680impl<T> ExactSizeIterator for Iter<'_, T> {
1681 fn is_empty(&self) -> bool {
1682 self.iter.is_empty()
1683 }
1684}
1685
1686#[stable(feature = "fused", since = "1.26.0")]
1687impl<T> FusedIterator for Iter<'_, T> {}
1688
1689/// An owning iterator over the elements of a `BinaryHeap`.
1690///
1691/// This `struct` is created by [`BinaryHeap::into_iter()`]
1692/// (provided by the [`IntoIterator`] trait). See its documentation for more.
1693///
1694/// [`into_iter`]: BinaryHeap::into_iter
1695#[stable(feature = "rust1", since = "1.0.0")]
1696#[derive(Clone)]
1697pub struct IntoIter<
1698 T,
1699 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1700> {
1701 iter: vec::IntoIter<T, A>,
1702}
1703
1704impl<T, A: Allocator> IntoIter<T, A> {
1705 /// Returns a reference to the underlying allocator.
1706 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1707 pub fn allocator(&self) -> &A {
1708 self.iter.allocator()
1709 }
1710}
1711
1712#[stable(feature = "collection_debug", since = "1.17.0")]
1713impl<T: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<T, A> {
1714 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1715 f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
1716 }
1717}
1718
1719#[stable(feature = "rust1", since = "1.0.0")]
1720impl<T, A: Allocator> Iterator for IntoIter<T, A> {
1721 type Item = T;
1722
1723 #[inline]
1724 fn next(&mut self) -> Option<T> {
1725 self.iter.next()
1726 }
1727
1728 #[inline]
1729 fn size_hint(&self) -> (usize, Option<usize>) {
1730 self.iter.size_hint()
1731 }
1732}
1733
1734#[stable(feature = "rust1", since = "1.0.0")]
1735impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
1736 #[inline]
1737 fn next_back(&mut self) -> Option<T> {
1738 self.iter.next_back()
1739 }
1740}
1741
1742#[stable(feature = "rust1", since = "1.0.0")]
1743impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {
1744 fn is_empty(&self) -> bool {
1745 self.iter.is_empty()
1746 }
1747}
1748
1749#[stable(feature = "fused", since = "1.26.0")]
1750impl<T, A: Allocator> FusedIterator for IntoIter<T, A> {}
1751
1752#[doc(hidden)]
1753#[unstable(issue = "none", feature = "trusted_fused")]
1754unsafe impl<T, A: Allocator> TrustedFused for IntoIter<T, A> {}
1755
1756#[stable(feature = "default_iters", since = "1.70.0")]
1757impl<T> Default for IntoIter<T> {
1758 /// Creates an empty `binary_heap::IntoIter`.
1759 ///
1760 /// ```
1761 /// # use std::collections::binary_heap;
1762 /// let iter: binary_heap::IntoIter<u8> = Default::default();
1763 /// assert_eq!(iter.len(), 0);
1764 /// ```
1765 fn default() -> Self {
1766 IntoIter { iter: Default::default() }
1767 }
1768}
1769
1770// In addition to the SAFETY invariants of the following three unsafe traits
1771// also refer to the vec::in_place_collect module documentation to get an overview
1772#[unstable(issue = "none", feature = "inplace_iteration")]
1773#[doc(hidden)]
1774unsafe impl<T, A: Allocator> SourceIter for IntoIter<T, A> {
1775 type Source = IntoIter<T, A>;
1776
1777 #[inline]
1778 unsafe fn as_inner(&mut self) -> &mut Self::Source {
1779 self
1780 }
1781}
1782
1783#[unstable(issue = "none", feature = "inplace_iteration")]
1784#[doc(hidden)]
1785unsafe impl<I, A: Allocator> InPlaceIterable for IntoIter<I, A> {
1786 const EXPAND_BY: Option<NonZero<usize>> = NonZero::new(1);
1787 const MERGE_BY: Option<NonZero<usize>> = NonZero::new(1);
1788}
1789
1790#[cfg(not(test))]
1791unsafe impl<I> AsVecIntoIter for IntoIter<I> {
1792 type Item = I;
1793
1794 fn as_into_iter(&mut self) -> &mut vec::IntoIter<Self::Item> {
1795 &mut self.iter
1796 }
1797}
1798
1799/// Iterator which retrieves elements in heap order.
1800#[must_use = "iterators are lazy and do nothing unless consumed"]
1801#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1802#[derive(Clone, Debug)]
1803pub struct IntoIterSorted<
1804 T,
1805 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1806> {
1807 inner: BinaryHeap<T, A>,
1808}
1809
1810impl<T, A: Allocator> IntoIterSorted<T, A> {
1811 /// Returns a reference to the underlying allocator.
1812 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1813 pub fn allocator(&self) -> &A {
1814 self.inner.allocator()
1815 }
1816}
1817
1818#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1819impl<T: Ord, A: Allocator> Iterator for IntoIterSorted<T, A> {
1820 type Item = T;
1821
1822 #[inline]
1823 fn next(&mut self) -> Option<T> {
1824 self.inner.pop()
1825 }
1826
1827 #[inline]
1828 fn size_hint(&self) -> (usize, Option<usize>) {
1829 let exact = self.inner.len();
1830 (exact, Some(exact))
1831 }
1832}
1833
1834#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1835impl<T: Ord, A: Allocator> ExactSizeIterator for IntoIterSorted<T, A> {}
1836
1837#[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1838impl<T: Ord, A: Allocator> FusedIterator for IntoIterSorted<T, A> {}
1839
1840#[unstable(feature = "trusted_len", issue = "37572")]
1841unsafe impl<T: Ord, A: Allocator> TrustedLen for IntoIterSorted<T, A> {}
1842
1843/// A draining iterator over the elements of a `BinaryHeap`.
1844///
1845/// This `struct` is created by [`BinaryHeap::drain()`]. See its
1846/// documentation for more.
1847///
1848/// [`drain`]: BinaryHeap::drain
1849#[stable(feature = "drain", since = "1.6.0")]
1850#[derive(Debug)]
1851pub struct Drain<
1852 'a,
1853 T: 'a,
1854 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1855> {
1856 iter: vec::Drain<'a, T, A>,
1857}
1858
1859impl<T, A: Allocator> Drain<'_, T, A> {
1860 /// Returns a reference to the underlying allocator.
1861 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1862 pub fn allocator(&self) -> &A {
1863 self.iter.allocator()
1864 }
1865}
1866
1867#[stable(feature = "drain", since = "1.6.0")]
1868impl<T, A: Allocator> Iterator for Drain<'_, T, A> {
1869 type Item = T;
1870
1871 #[inline]
1872 fn next(&mut self) -> Option<T> {
1873 self.iter.next()
1874 }
1875
1876 #[inline]
1877 fn size_hint(&self) -> (usize, Option<usize>) {
1878 self.iter.size_hint()
1879 }
1880}
1881
1882#[stable(feature = "drain", since = "1.6.0")]
1883impl<T, A: Allocator> DoubleEndedIterator for Drain<'_, T, A> {
1884 #[inline]
1885 fn next_back(&mut self) -> Option<T> {
1886 self.iter.next_back()
1887 }
1888}
1889
1890#[stable(feature = "drain", since = "1.6.0")]
1891impl<T, A: Allocator> ExactSizeIterator for Drain<'_, T, A> {
1892 fn is_empty(&self) -> bool {
1893 self.iter.is_empty()
1894 }
1895}
1896
1897#[stable(feature = "fused", since = "1.26.0")]
1898impl<T, A: Allocator> FusedIterator for Drain<'_, T, A> {}
1899
1900/// A draining iterator over the elements of a `BinaryHeap`.
1901///
1902/// This `struct` is created by [`BinaryHeap::drain_sorted()`]. See its
1903/// documentation for more.
1904///
1905/// [`drain_sorted`]: BinaryHeap::drain_sorted
1906#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1907#[derive(Debug)]
1908pub struct DrainSorted<
1909 'a,
1910 T: Ord,
1911 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
1912> {
1913 inner: &'a mut BinaryHeap<T, A>,
1914}
1915
1916impl<'a, T: Ord, A: Allocator> DrainSorted<'a, T, A> {
1917 /// Returns a reference to the underlying allocator.
1918 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1919 pub fn allocator(&self) -> &A {
1920 self.inner.allocator()
1921 }
1922}
1923
1924#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1925impl<'a, T: Ord, A: Allocator> Drop for DrainSorted<'a, T, A> {
1926 /// Removes heap elements in heap order.
1927 fn drop(&mut self) {
1928 struct DropGuard<'r, 'a, T: Ord, A: Allocator>(&'r mut DrainSorted<'a, T, A>);
1929
1930 impl<'r, 'a, T: Ord, A: Allocator> Drop for DropGuard<'r, 'a, T, A> {
1931 fn drop(&mut self) {
1932 while self.0.inner.pop().is_some() {}
1933 }
1934 }
1935
1936 while let Some(item) = self.inner.pop() {
1937 let guard = DropGuard(self);
1938 drop(item);
1939 mem::forget(guard);
1940 }
1941 }
1942}
1943
1944#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1945impl<T: Ord, A: Allocator> Iterator for DrainSorted<'_, T, A> {
1946 type Item = T;
1947
1948 #[inline]
1949 fn next(&mut self) -> Option<T> {
1950 self.inner.pop()
1951 }
1952
1953 #[inline]
1954 fn size_hint(&self) -> (usize, Option<usize>) {
1955 let exact = self.inner.len();
1956 (exact, Some(exact))
1957 }
1958}
1959
1960#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1961impl<T: Ord, A: Allocator> ExactSizeIterator for DrainSorted<'_, T, A> {}
1962
1963#[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1964impl<T: Ord, A: Allocator> FusedIterator for DrainSorted<'_, T, A> {}
1965
1966#[unstable(feature = "trusted_len", issue = "37572")]
1967unsafe impl<T: Ord, A: Allocator> TrustedLen for DrainSorted<'_, T, A> {}
1968
1969#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1970impl<T: Ord, A: AllocatorNightly> From<Vec<T, A>> for BinaryHeap<T, A> {
1971 /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1972 ///
1973 /// This conversion happens in-place, and has *O*(*n*) time complexity.
1974 fn from(vec: Vec<T, A>) -> BinaryHeap<T, A> {
1975 let mut heap = BinaryHeap { data: vec };
1976 heap.rebuild();
1977 heap
1978 }
1979}
1980
1981#[stable(feature = "std_collections_from_array", since = "1.56.0")]
1982impl<T: Ord, const N: usize> From<[T; N]> for BinaryHeap<T> {
1983 /// ```
1984 /// use std::collections::BinaryHeap;
1985 ///
1986 /// let mut h1 = BinaryHeap::from([1, 4, 2, 3]);
1987 /// let mut h2: BinaryHeap<_> = [1, 4, 2, 3].into();
1988 /// while let Some((a, b)) = h1.pop().zip(h2.pop()) {
1989 /// assert_eq!(a, b);
1990 /// }
1991 /// ```
1992 fn from(arr: [T; N]) -> Self {
1993 Self::from_iter(arr)
1994 }
1995}
1996
1997#[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1998impl<T, A: Allocator> From<BinaryHeap<T, A>> for Vec<T, A> {
1999 /// Converts a `BinaryHeap<T>` into a `Vec<T>`.
2000 ///
2001 /// This conversion requires no data movement or allocation, and has
2002 /// constant time complexity.
2003 fn from(heap: BinaryHeap<T, A>) -> Vec<T, A> {
2004 heap.data
2005 }
2006}
2007
2008#[stable(feature = "rust1", since = "1.0.0")]
2009impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
2010 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
2011 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
2012 }
2013}
2014
2015#[stable(feature = "rust1", since = "1.0.0")]
2016impl<T, A: Allocator> IntoIterator for BinaryHeap<T, A> {
2017 type Item = T;
2018 type IntoIter = IntoIter<T, A>;
2019
2020 /// Creates a consuming iterator, that is, one that moves each value out of
2021 /// the binary heap in arbitrary order. The binary heap cannot be used
2022 /// after calling this.
2023 ///
2024 /// # Examples
2025 ///
2026 /// Basic usage:
2027 ///
2028 /// ```
2029 /// use std::collections::BinaryHeap;
2030 /// let heap = BinaryHeap::from([1, 2, 3, 4]);
2031 ///
2032 /// // Print 1, 2, 3, 4 in arbitrary order
2033 /// for x in heap.into_iter() {
2034 /// // x has type i32, not &i32
2035 /// println!("{x}");
2036 /// }
2037 /// ```
2038 fn into_iter(self) -> IntoIter<T, A> {
2039 IntoIter { iter: self.data.into_iter() }
2040 }
2041}
2042
2043#[stable(feature = "rust1", since = "1.0.0")]
2044impl<'a, T, A: Allocator> IntoIterator for &'a BinaryHeap<T, A> {
2045 type Item = &'a T;
2046 type IntoIter = Iter<'a, T>;
2047
2048 fn into_iter(self) -> Iter<'a, T> {
2049 self.iter()
2050 }
2051}
2052
2053#[stable(feature = "rust1", since = "1.0.0")]
2054impl<T: Ord, A: Allocator> Extend<T> for BinaryHeap<T, A> {
2055 #[inline]
2056 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2057 let guard = RebuildOnDrop { rebuild_from: self.len(), heap: self };
2058 guard.heap.data.extend(iter);
2059 }
2060
2061 #[inline]
2062 fn extend_one(&mut self, item: T) {
2063 self.push(item);
2064 }
2065
2066 #[inline]
2067 fn extend_reserve(&mut self, additional: usize) {
2068 self.reserve(additional);
2069 }
2070}
2071
2072#[stable(feature = "extend_ref", since = "1.2.0")]
2073impl<'a, T: 'a + Ord + Copy, A: Allocator> Extend<&'a T> for BinaryHeap<T, A> {
2074 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2075 self.extend(iter.into_iter().cloned());
2076 }
2077
2078 #[inline]
2079 fn extend_one(&mut self, &item: &'a T) {
2080 self.push(item);
2081 }
2082
2083 #[inline]
2084 fn extend_reserve(&mut self, additional: usize) {
2085 self.reserve(additional);
2086 }
2087}