#![deny(unsafe_op_in_unsafe_fn)]
#![allow(clippy::needless_doctest_main)]
#![allow(missing_docs)]
use std::cmp::Ordering;
use std::iter::FromIterator;
use std::slice;
use compare::Compare;
use core::fmt;
use core::mem::{swap, ManuallyDrop};
use core::ptr;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::ops::Deref;
use std::ops::DerefMut;
use std::vec;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BinaryHeap<T, C = MaxComparator> {
data: Vec<T>,
cmp: C,
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
pub struct MaxComparator;
impl<T: Ord> Compare<T> for MaxComparator {
fn compare(&self, a: &T, b: &T) -> Ordering {
a.cmp(b)
}
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
pub struct MinComparator;
impl<T: Ord> Compare<T> for MinComparator {
fn compare(&self, a: &T, b: &T) -> Ordering {
b.cmp(a)
}
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
pub struct FnComparator<F>(pub F);
impl<T, F> Compare<T> for FnComparator<F>
where
F: Fn(&T, &T) -> Ordering,
{
fn compare(&self, a: &T, b: &T) -> Ordering {
self.0(a, b)
}
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
pub struct KeyComparator<F>(pub F);
impl<K: Ord, T, F> Compare<T> for KeyComparator<F>
where
F: Fn(&T) -> K,
{
fn compare(&self, a: &T, b: &T) -> Ordering {
self.0(a).cmp(&self.0(b))
}
}
pub struct PeekMut<'a, T: 'a, C: 'a + Compare<T>> {
heap: &'a mut BinaryHeap<T, C>,
sift: bool,
}
impl<T: fmt::Debug, C: Compare<T>> fmt::Debug for PeekMut<'_, T, C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish()
}
}
impl<T, C: Compare<T>> Drop for PeekMut<'_, T, C> {
fn drop(&mut self) {
if self.sift {
unsafe { self.heap.sift_down(0) };
}
}
}
impl<T, C: Compare<T>> Deref for PeekMut<'_, T, C> {
type Target = T;
fn deref(&self) -> &T {
debug_assert!(!self.heap.is_empty());
unsafe { self.heap.data.get_unchecked(0) }
}
}
impl<T, C: Compare<T>> DerefMut for PeekMut<'_, T, C> {
fn deref_mut(&mut self) -> &mut T {
debug_assert!(!self.heap.is_empty());
self.sift = true;
unsafe { self.heap.data.get_unchecked_mut(0) }
}
}
impl<'a, T, C: Compare<T>> PeekMut<'a, T, C> {
pub fn pop(mut this: PeekMut<'a, T, C>) -> T {
let value = this.heap.pop().unwrap();
this.sift = false;
value
}
}
impl<T: Clone, C: Clone> Clone for BinaryHeap<T, C> {
fn clone(&self) -> Self {
BinaryHeap {
data: self.data.clone(),
cmp: self.cmp.clone(),
}
}
fn clone_from(&mut self, source: &Self) {
self.data.clone_from(&source.data);
}
}
impl<T: Ord> Default for BinaryHeap<T> {
#[inline]
fn default() -> BinaryHeap<T> {
BinaryHeap::new()
}
}
impl<T: fmt::Debug, C> fmt::Debug for BinaryHeap<T, C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl<T, C: Compare<T> + Default> BinaryHeap<T, C> {
pub fn from_vec(vec: Vec<T>) -> Self {
BinaryHeap::from_vec_cmp(vec, C::default())
}
}
impl<T, C: Compare<T>> BinaryHeap<T, C> {
pub fn from_vec_cmp(vec: Vec<T>, cmp: C) -> Self {
unsafe { BinaryHeap::from_vec_cmp_raw(vec, cmp, true) }
}
pub unsafe fn from_vec_cmp_raw(vec: Vec<T>, cmp: C, rebuild: bool) -> Self {
let mut heap = BinaryHeap { data: vec, cmp };
if rebuild && !heap.data.is_empty() {
heap.rebuild();
}
heap
}
}
impl<T: Ord> BinaryHeap<T> {
#[must_use]
pub fn new() -> Self {
BinaryHeap::from_vec(vec![])
}
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
BinaryHeap::from_vec(Vec::with_capacity(capacity))
}
}
impl<T: Ord> BinaryHeap<T, MinComparator> {
#[must_use]
pub fn new_min() -> Self {
BinaryHeap::from_vec(vec![])
}
#[must_use]
pub fn with_capacity_min(capacity: usize) -> Self {
BinaryHeap::from_vec(Vec::with_capacity(capacity))
}
}
impl<T, F> BinaryHeap<T, FnComparator<F>>
where
F: Fn(&T, &T) -> Ordering,
{
#[must_use]
pub fn new_by(f: F) -> Self {
BinaryHeap::from_vec_cmp(vec![], FnComparator(f))
}
#[must_use]
pub fn with_capacity_by(capacity: usize, f: F) -> Self {
BinaryHeap::from_vec_cmp(Vec::with_capacity(capacity), FnComparator(f))
}
}
impl<T, F, K: Ord> BinaryHeap<T, KeyComparator<F>>
where
F: Fn(&T) -> K,
{
#[must_use]
pub fn new_by_key(f: F) -> Self {
BinaryHeap::from_vec_cmp(vec![], KeyComparator(f))
}
#[must_use]
pub fn with_capacity_by_key(capacity: usize, f: F) -> Self {
BinaryHeap::from_vec_cmp(Vec::with_capacity(capacity), KeyComparator(f))
}
}
impl<T, C: Compare<T>> BinaryHeap<T, C> {
#[inline]
pub fn replace_cmp(&mut self, cmp: C) {
unsafe {
self.replace_cmp_raw(cmp, true);
}
}
pub unsafe fn replace_cmp_raw(&mut self, cmp: C, rebuild: bool) {
self.cmp = cmp;
if rebuild && !self.data.is_empty() {
self.rebuild();
}
}
pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, C>> {
if self.is_empty() {
None
} else {
Some(PeekMut {
heap: self,
sift: false,
})
}
}
pub fn pop(&mut self) -> Option<T> {
self.data.pop().map(|mut item| {
if !self.is_empty() {
swap(&mut item, &mut self.data[0]);
unsafe { self.sift_down_to_bottom(0) };
}
item
})
}
pub fn push(&mut self, item: T) {
let old_len = self.len();
self.data.push(item);
unsafe { self.sift_up(0, old_len) };
}
#[must_use = "`self` will be dropped if the result is not used"]
pub fn into_sorted_vec(mut self) -> Vec<T> {
let mut end = self.len();
while end > 1 {
end -= 1;
unsafe {
let ptr = self.data.as_mut_ptr();
ptr::swap(ptr, ptr.add(end));
}
unsafe { self.sift_down_range(0, end) };
}
self.into_vec()
}
unsafe fn sift_up(&mut self, start: usize, pos: usize) -> usize {
let mut hole = unsafe { Hole::new(&mut self.data, pos) };
while hole.pos() > start {
let parent = (hole.pos() - 1) / 2;
if self
.cmp
.compares_le(hole.element(), unsafe { hole.get(parent) })
{
break;
}
unsafe { hole.move_to(parent) };
}
hole.pos()
}
unsafe fn sift_down_range(&mut self, pos: usize, end: usize) {
let mut hole = unsafe { Hole::new(&mut self.data, pos) };
let mut child = 2 * hole.pos() + 1;
while child <= end.saturating_sub(2) {
child += unsafe { self.cmp.compares_le(hole.get(child), hole.get(child + 1)) } as usize;
if self
.cmp
.compares_ge(hole.element(), unsafe { hole.get(child) })
{
return;
}
unsafe { hole.move_to(child) };
child = 2 * hole.pos() + 1;
}
if child == end - 1
&& self
.cmp
.compares_lt(hole.element(), unsafe { hole.get(child) })
{
unsafe { hole.move_to(child) };
}
}
unsafe fn sift_down(&mut self, pos: usize) {
let len = self.len();
unsafe { self.sift_down_range(pos, len) };
}
unsafe fn sift_down_to_bottom(&mut self, mut pos: usize) {
let end = self.len();
let start = pos;
let mut hole = unsafe { Hole::new(&mut self.data, pos) };
let mut child = 2 * hole.pos() + 1;
while child <= end.saturating_sub(2) {
child += unsafe { self.cmp.compares_le(hole.get(child), hole.get(child + 1)) } as usize;
unsafe { hole.move_to(child) };
child = 2 * hole.pos() + 1;
}
if child == end - 1 {
unsafe { hole.move_to(child) };
}
pos = hole.pos();
drop(hole);
unsafe { self.sift_up(start, pos) };
}
fn rebuild_tail(&mut self, start: usize) {
if start == self.len() {
return;
}
let tail_len = self.len() - start;
#[inline(always)]
fn log2_fast(x: usize) -> usize {
(usize::BITS - x.leading_zeros() - 1) as usize
}
let better_to_rebuild = if start < tail_len {
true
} else if self.len() <= 2048 {
2 * self.len() < tail_len * log2_fast(start)
} else {
2 * self.len() < tail_len * 11
};
if better_to_rebuild {
self.rebuild();
} else {
for i in start..self.len() {
unsafe { self.sift_up(0, i) };
}
}
}
fn rebuild(&mut self) {
let mut n = self.len() / 2;
while n > 0 {
n -= 1;
unsafe { self.sift_down(n) };
}
}
pub fn append(&mut self, other: &mut Self) {
if self.len() < other.len() {
swap(self, other);
}
let start = self.data.len();
self.data.append(&mut other.data);
self.rebuild_tail(start);
}
}
impl<T, C> BinaryHeap<T, C> {
pub fn iter(&self) -> Iter<'_, T> {
Iter {
iter: self.data.iter(),
}
}
pub fn into_iter_sorted(self) -> IntoIterSorted<T, C> {
IntoIterSorted { inner: self }
}
#[must_use]
pub fn peek(&self) -> Option<&T> {
self.data.get(0)
}
#[must_use]
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]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.data.shrink_to(min_capacity)
}
#[must_use = "`self` will be dropped if the result is not used"]
pub fn into_vec(self) -> Vec<T> {
self.into()
}
#[must_use]
pub fn len(&self) -> usize {
self.data.len()
}
#[must_use]
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 = unsafe { 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());
unsafe { 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());
unsafe {
let ptr = self.data.as_mut_ptr();
let index_ptr: *const _ = ptr.add(index);
let hole_ptr = ptr.add(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);
}
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
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()
}
}
#[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()
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[derive(Clone, Debug)]
pub struct IntoIterSorted<T, C> {
inner: BinaryHeap<T, C>,
}
impl<T, C: Compare<T>> Iterator for IntoIterSorted<T, C> {
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))
}
}
#[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: Ord> From<Vec<T>> for BinaryHeap<T> {
fn from(vec: Vec<T>) -> Self {
BinaryHeap::from_vec(vec)
}
}
impl<T: Ord, const N: usize> From<[T; N]> for BinaryHeap<T> {
fn from(arr: [T; N]) -> Self {
Self::from_iter(arr)
}
}
impl<T, C> From<BinaryHeap<T, C>> for Vec<T> {
fn from(heap: BinaryHeap<T, C>) -> Vec<T> {
heap.data
}
}
impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
}
}
impl<T, C> IntoIterator for BinaryHeap<T, C> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
IntoIter {
iter: self.data.into_iter(),
}
}
}
impl<'a, T, C> IntoIterator for &'a BinaryHeap<T, C> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
impl<T, C: Compare<T>> Extend<T> for BinaryHeap<T, C> {
#[inline]
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
self.extend_desugared(iter);
}
}
impl<T, C: Compare<T>> BinaryHeap<T, C> {
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 + Copy, C: Compare<T>> Extend<&'a T> for BinaryHeap<T, C> {
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned());
}
}