#![no_std]
#![cfg_attr(feature = "exact_size_is_empty", feature(exact_size_is_empty))]
#![cfg_attr(feature = "extend_one", feature(extend_one))]
#![cfg_attr(feature = "shrink_to", feature(shrink_to))]
#![cfg_attr(feature = "trusted_len", feature(trusted_len))]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![allow(clippy::needless_doctest_main)]
extern crate alloc;
use core::fmt;
use core::iter::{FromIterator, FusedIterator};
use core::marker::PhantomData;
use core::mem::{size_of, swap, ManuallyDrop};
use core::ops::{Deref, DerefMut};
use core::ptr;
use core::slice;
use alloc::{vec, vec::Vec};
pub trait Arity {
const D: usize;
}
#[macro_export]
macro_rules! arity {
($(#[$attr:meta])* $vis:vis $arity:ident = $num:expr; $($t:tt)*) => {
$(#[$attr])*
$vis enum $arity {}
impl $crate::Arity for $arity {
const D: usize = $num;
}
$crate::arity!($($t)*);
};
() => {}
}
arity! {
pub D2 = 2;
pub D3 = 3;
pub D4 = 4;
pub D5 = 5;
pub D6 = 6;
pub D7 = 7;
pub D8 = 8;
}
pub type BinaryHeap<T> = DaryHeap<T, D2>;
pub type TernaryHeap<T> = DaryHeap<T, D3>;
pub type QuaternaryHeap<T> = DaryHeap<T, D4>;
pub type QuinaryHeap<T> = DaryHeap<T, D5>;
pub type SenaryHeap<T> = DaryHeap<T, D6>;
pub type SeptenaryHeap<T> = DaryHeap<T, D7>;
pub type OctonaryHeap<T> = DaryHeap<T, D8>;
pub struct DaryHeap<T, D: Arity> {
data: Vec<T>,
marker: PhantomData<D>,
}
pub struct PeekMut<'a, T: 'a + Ord, D: Arity> {
heap: &'a mut DaryHeap<T, D>,
sift: bool,
}
impl<T: Ord + fmt::Debug, D: Arity> fmt::Debug for PeekMut<'_, T, D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish()
}
}
impl<T: Ord, D: Arity> Drop for PeekMut<'_, T, D> {
fn drop(&mut self) {
if self.sift {
self.heap.sift_down(0);
}
}
}
impl<T: Ord, D: Arity> Deref for PeekMut<'_, T, D> {
type Target = T;
fn deref(&self) -> &T {
debug_assert!(!self.heap.is_empty());
unsafe { self.heap.data.get_unchecked(0) }
}
}
impl<T: Ord, D: Arity> DerefMut for PeekMut<'_, T, D> {
fn deref_mut(&mut self) -> &mut T {
debug_assert!(!self.heap.is_empty());
unsafe { self.heap.data.get_unchecked_mut(0) }
}
}
impl<'a, T: Ord, D: Arity> PeekMut<'a, T, D> {
pub fn pop(mut this: PeekMut<'a, T, D>) -> T {
let value = this.heap.pop().unwrap();
this.sift = false;
value
}
}
impl<T: Clone, D: Arity> Clone for DaryHeap<T, D> {
fn clone(&self) -> Self {
DaryHeap {
data: self.data.clone(),
marker: PhantomData,
}
}
fn clone_from(&mut self, source: &Self) {
self.data.clone_from(&source.data);
}
}
impl<T: Ord, D: Arity> Default for DaryHeap<T, D> {
#[inline]
fn default() -> DaryHeap<T, D> {
DaryHeap::new()
}
}
impl<T: fmt::Debug, D: Arity> fmt::Debug for DaryHeap<T, D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl<T: Ord, D: Arity> DaryHeap<T, D> {
pub fn new() -> DaryHeap<T, D> {
DaryHeap {
data: vec![],
marker: PhantomData,
}
}
pub fn with_capacity(capacity: usize) -> DaryHeap<T, D> {
DaryHeap {
data: Vec::with_capacity(capacity),
marker: PhantomData,
}
}
pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, D>> {
if self.is_empty() {
None
} else {
Some(PeekMut {
heap: self,
sift: true,
})
}
}
pub fn pop(&mut self) -> Option<T> {
self.data.pop().map(|mut item| {
if !self.is_empty() {
swap(&mut item, &mut self.data[0]);
self.sift_down_to_bottom(0);
}
item
})
}
pub fn push(&mut self, item: T) {
let old_len = self.len();
self.data.push(item);
self.sift_up(0, old_len);
}
pub fn into_sorted_vec(mut self) -> Vec<T> {
let mut end = self.len();
while end > 1 {
end -= 1;
self.data.swap(0, end);
self.sift_down_range(0, end);
}
self.into_vec()
}
fn sift_up(&mut self, start: usize, pos: usize) -> usize {
unsafe {
let mut hole = Hole::new(&mut self.data, pos);
while hole.pos() > start {
let parent = (hole.pos() - 1) / D::D;
if hole.element() <= hole.get(parent) {
break;
}
hole.move_to(parent);
}
hole.pos()
}
}
fn sift_down_range(&mut self, pos: usize, end: usize) {
unsafe {
let mut hole = Hole::new(&mut self.data, pos);
let mut child = D::D * pos + 1;
while child < end {
for other_child in child + 1..child + D::D {
if other_child < end && hole.get(child) <= hole.get(other_child) {
child = other_child;
}
}
if hole.element() >= hole.get(child) {
break;
}
hole.move_to(child);
child = D::D * hole.pos() + 1;
}
}
}
fn sift_down(&mut self, pos: usize) {
let len = self.len();
self.sift_down_range(pos, len);
}
fn sift_down_to_bottom(&mut self, mut pos: usize) {
let end = self.len();
let start = pos;
unsafe {
let mut hole = Hole::new(&mut self.data, pos);
let mut child = D::D * pos + 1;
while child < end {
for other_child in child + 1..child + D::D {
if other_child < end && hole.get(child) <= hole.get(other_child) {
child = other_child;
}
}
hole.move_to(child);
child = D::D * hole.pos() + 1;
}
pos = hole.pos;
}
self.sift_up(start, pos);
}
fn rebuild(&mut self) {
if self.len() < 2 {
return;
}
let mut n = (self.len() - 1) / D::D + 1;
while n > 0 {
n -= 1;
self.sift_down(n);
}
}
pub fn append(&mut self, other: &mut Self) {
if self.len() < other.len() {
swap(self, other);
}
if other.is_empty() {
return;
}
#[inline(always)]
fn log2_fast(x: usize) -> usize {
8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
}
#[inline]
fn better_to_rebuild<D: Arity>(len1: usize, len2: usize) -> bool {
let logd_len1 = log2_fast(len1) / log2_fast(D::D);
D::D * (len1 + len2) < (D::D - 1) * len2 * logd_len1
}
if better_to_rebuild::<D>(self.len(), other.len()) {
self.data.append(&mut other.data);
self.rebuild();
} else {
self.extend(other.drain());
}
}
#[inline]
#[cfg(feature = "drain_sorted")]
#[cfg_attr(docsrs, doc(cfg(feature = "drain_sorted")))]
pub fn drain_sorted(&mut self) -> DrainSorted<'_, T, D> {
DrainSorted { inner: self }
}
#[cfg(feature = "retain")]
#[cfg_attr(docsrs, doc(cfg(feature = "retain")))]
pub fn retain<F>(&mut self, f: F)
where
F: FnMut(&T) -> bool,
{
self.data.retain(f);
self.rebuild();
}
}
impl<T, D: Arity> DaryHeap<T, D> {
pub fn iter(&self) -> Iter<'_, T> {
Iter {
iter: self.data.iter(),
}
}
#[cfg(feature = "into_iter_sorted")]
#[cfg_attr(docsrs, doc(cfg(feature = "into_iter_sorted")))]
pub fn into_iter_sorted(self) -> IntoIterSorted<T, D> {
IntoIterSorted { inner: self }
}
pub fn peek(&self) -> Option<&T> {
self.data.get(0)
}
pub fn capacity(&self) -> usize {
self.data.capacity()
}
pub fn reserve_exact(&mut self, additional: usize) {
self.data.reserve_exact(additional);
}
pub fn reserve(&mut self, additional: usize) {
self.data.reserve(additional);
}
pub fn shrink_to_fit(&mut self) {
self.data.shrink_to_fit();
}
#[inline]
#[cfg(feature = "shrink_to")]
#[cfg_attr(docsrs, doc(cfg(feature = "shrink_to")))]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.data.shrink_to(min_capacity)
}
pub fn into_vec(self) -> Vec<T> {
self.into()
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
pub fn drain(&mut self) -> Drain<'_, T> {
Drain {
iter: self.data.drain(..),
}
}
pub fn clear(&mut self) {
self.drain();
}
}
struct Hole<'a, T: 'a> {
data: &'a mut [T],
elt: ManuallyDrop<T>,
pos: usize,
}
impl<'a, T> Hole<'a, T> {
#[inline]
unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
debug_assert!(pos < data.len());
let elt = ptr::read(data.get_unchecked(pos));
Hole {
data,
elt: ManuallyDrop::new(elt),
pos,
}
}
#[inline]
fn pos(&self) -> usize {
self.pos
}
#[inline]
fn element(&self) -> &T {
&self.elt
}
#[inline]
unsafe fn get(&self, index: usize) -> &T {
debug_assert!(index != self.pos);
debug_assert!(index < self.data.len());
self.data.get_unchecked(index)
}
#[inline]
unsafe fn move_to(&mut self, index: usize) {
debug_assert!(index != self.pos);
debug_assert!(index < self.data.len());
let index_ptr: *const _ = self.data.get_unchecked(index);
let hole_ptr = self.data.get_unchecked_mut(self.pos);
ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
self.pos = index;
}
}
impl<T> Drop for Hole<'_, T> {
#[inline]
fn drop(&mut self) {
unsafe {
let pos = self.pos;
ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
}
}
}
pub struct Iter<'a, T: 'a> {
iter: slice::Iter<'a, T>,
}
impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
}
}
impl<T> Clone for Iter<'_, T> {
fn clone(&self) -> Self {
Iter {
iter: self.iter.clone(),
}
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
#[inline]
fn next(&mut self) -> Option<&'a T> {
self.iter.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
#[inline]
fn last(self) -> Option<&'a T> {
self.iter.last()
}
}
impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<&'a T> {
self.iter.next_back()
}
}
impl<T> ExactSizeIterator for Iter<'_, T> {
#[cfg(feature = "exact_size_is_empty")]
fn is_empty(&self) -> bool {
self.iter.is_empty()
}
}
impl<T> FusedIterator for Iter<'_, T> {}
#[derive(Clone)]
pub struct IntoIter<T> {
iter: vec::IntoIter<T>,
}
impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("IntoIter")
.field(&self.iter.as_slice())
.finish()
}
}
impl<T> Iterator for IntoIter<T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
self.iter.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<T> DoubleEndedIterator for IntoIter<T> {
#[inline]
fn next_back(&mut self) -> Option<T> {
self.iter.next_back()
}
}
impl<T> ExactSizeIterator for IntoIter<T> {
#[cfg(feature = "exact_size_is_empty")]
fn is_empty(&self) -> bool {
self.iter.is_empty()
}
}
impl<T> FusedIterator for IntoIter<T> {}
#[cfg(feature = "into_iter_sorted")]
#[derive(Clone, Debug)]
pub struct IntoIterSorted<T, D: Arity> {
inner: DaryHeap<T, D>,
}
#[cfg(feature = "into_iter_sorted")]
impl<T: Ord, D: Arity> Iterator for IntoIterSorted<T, D> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
self.inner.pop()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let exact = self.inner.len();
(exact, Some(exact))
}
}
#[cfg(feature = "into_iter_sorted")]
impl<T: Ord, D: Arity> ExactSizeIterator for IntoIterSorted<T, D> {}
#[cfg(feature = "into_iter_sorted")]
impl<T: Ord, D: Arity> FusedIterator for IntoIterSorted<T, D> {}
#[cfg(all(feature = "into_iter_sorted", feature = "trusted_len"))]
unsafe impl<T: Ord, D: Arity> core::iter::TrustedLen for IntoIterSorted<T, D> {}
#[derive(Debug)]
pub struct Drain<'a, T: 'a> {
iter: vec::Drain<'a, T>,
}
impl<T> Iterator for Drain<'_, T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
self.iter.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<T> DoubleEndedIterator for Drain<'_, T> {
#[inline]
fn next_back(&mut self) -> Option<T> {
self.iter.next_back()
}
}
impl<T> ExactSizeIterator for Drain<'_, T> {
#[cfg(feature = "exact_size_is_empty")]
fn is_empty(&self) -> bool {
self.iter.is_empty()
}
}
impl<T> FusedIterator for Drain<'_, T> {}
#[cfg(feature = "drain_sorted")]
#[derive(Debug)]
pub struct DrainSorted<'a, T: Ord, D: Arity> {
inner: &'a mut DaryHeap<T, D>,
}
#[cfg(feature = "drain_sorted")]
impl<'a, T: Ord, D: Arity> Drop for DrainSorted<'a, T, D> {
fn drop(&mut self) {
use core::mem::forget;
struct DropGuard<'r, 'a, T: Ord, D: Arity>(&'r mut DrainSorted<'a, T, D>);
impl<'r, 'a, T: Ord, D: Arity> Drop for DropGuard<'r, 'a, T, D> {
fn drop(&mut self) {
while self.0.inner.pop().is_some() {}
}
}
while let Some(item) = self.inner.pop() {
let guard = DropGuard(self);
drop(item);
forget(guard);
}
}
}
#[cfg(feature = "drain_sorted")]
impl<T: Ord, D: Arity> Iterator for DrainSorted<'_, T, D> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
self.inner.pop()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let exact = self.inner.len();
(exact, Some(exact))
}
}
#[cfg(feature = "drain_sorted")]
impl<T: Ord, D: Arity> ExactSizeIterator for DrainSorted<'_, T, D> {}
#[cfg(feature = "drain_sorted")]
impl<T: Ord, D: Arity> FusedIterator for DrainSorted<'_, T, D> {}
#[cfg(all(feature = "drain_sorted", feature = "trusted_len"))]
unsafe impl<T: Ord, D: Arity> core::iter::TrustedLen for DrainSorted<'_, T, D> {}
impl<T: Ord, D: Arity> From<Vec<T>> for DaryHeap<T, D> {
fn from(vec: Vec<T>) -> DaryHeap<T, D> {
let mut heap = DaryHeap {
data: vec,
marker: PhantomData,
};
heap.rebuild();
heap
}
}
impl<T, D: Arity> From<DaryHeap<T, D>> for Vec<T> {
fn from(heap: DaryHeap<T, D>) -> Vec<T> {
heap.data
}
}
impl<T: Ord, D: Arity> FromIterator<T> for DaryHeap<T, D> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> DaryHeap<T, D> {
DaryHeap::from(iter.into_iter().collect::<Vec<_>>())
}
}
impl<T, D: Arity> IntoIterator for DaryHeap<T, D> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
IntoIter {
iter: self.data.into_iter(),
}
}
}
impl<'a, T, D: Arity> IntoIterator for &'a DaryHeap<T, D> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
impl<T: Ord, D: Arity> Extend<T> for DaryHeap<T, D> {
#[inline]
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
self.extend_desugared(iter.into_iter());
}
#[inline]
#[cfg(feature = "extend_one")]
fn extend_one(&mut self, item: T) {
self.push(item);
}
#[inline]
#[cfg(feature = "extend_one")]
fn extend_reserve(&mut self, additional: usize) {
self.reserve(additional);
}
}
impl<T: Ord, D: Arity> DaryHeap<T, D> {
fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
let iterator = iter.into_iter();
let (lower, _) = iterator.size_hint();
self.reserve(lower);
iterator.for_each(move |elem| self.push(elem));
}
}
impl<'a, T: 'a + Ord + Copy, D: Arity> Extend<&'a T> for DaryHeap<T, D> {
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned());
}
#[inline]
#[cfg(feature = "extend_one")]
fn extend_one(&mut self, &item: &'a T) {
self.push(item);
}
#[inline]
#[cfg(feature = "extend_one")]
fn extend_reserve(&mut self, additional: usize) {
self.reserve(additional);
}
}
#[cfg(any(test, fuzzing))]
impl<T: Ord + fmt::Debug, D: Arity> DaryHeap<T, D> {
#[track_caller]
pub fn assert_valid_state(&self) {
for (i, v) in self.iter().enumerate() {
let children = D::D * i + 1..D::D * i + D::D;
if children.start > self.len() {
break;
}
for j in children {
if let Some(x) = self.data.get(j) {
assert!(v >= x);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::{seq::SliceRandom, thread_rng};
fn pop<D: Arity>() {
let mut rng = thread_rng();
let ntest = 10;
let nelem = 1000;
for _ in 0..ntest {
let mut data: Vec<_> = (0..nelem).collect();
data.shuffle(&mut rng);
let mut heap = DaryHeap::<_, D>::from(data);
heap.assert_valid_state();
for i in (0..nelem).rev() {
assert_eq!(heap.pop(), Some(i));
heap.assert_valid_state();
}
assert_eq!(heap.pop(), None);
}
}
#[test]
fn pop_d2() {
pop::<D2>();
}
#[test]
fn pop_d3() {
pop::<D3>();
}
#[test]
fn pop_d4() {
pop::<D4>();
}
#[test]
fn pop_d5() {
pop::<D5>();
}
#[test]
fn pop_d6() {
pop::<D6>();
}
#[test]
fn pop_d7() {
pop::<D7>();
}
#[test]
fn pop_d8() {
pop::<D8>();
}
}