Skip to main content

dary_heap/
lib.rs

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