use std::ops::{Deref, DerefMut};
use crate::{ConstDefault, ordering::Ordering, RawHeap, raw_heap};
pub use std::slice::Iter;
#[derive(Clone)]
pub struct VecHeap<T, O> {
data: Vec<T>,
ord: O,
}
impl<T, O: Default> Default for VecHeap<T, O> {
fn default() -> Self {
Self { data: Default::default(), ord: Default::default() }
}
}
impl<T, O> VecHeap<T, O> {
pub const fn new() -> Self
where
O: ConstDefault,
{
Self {
data: Vec::new(),
ord: O::DEFAULT,
}
}
pub fn with_capacity(capacity: usize) -> Self
where
O: Default,
{
Self {
data: Vec::with_capacity(capacity),
ord: O::default(),
}
}
pub const fn with_ordering(ord: O) -> Self {
Self {
data: Vec::new(),
ord,
}
}
pub fn with_capacity_and_ordering(capacity: usize, ord: O) -> Self {
Self {
data: Vec::with_capacity(capacity),
ord,
}
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn capacity(&self) -> usize {
self.data.capacity()
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
pub fn iter(&self) -> Iter<'_, T> {
self.data.iter()
}
}
impl<T, O: Ordering<T>> VecHeap<T, O> {
pub fn peek(&self) -> Option<&T> {
self.data.peek()
}
pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, O>> {
RawHeap::peek_mut(&mut self.data).map(|raw| PeekMut {
raw,
ord: &self.ord,
})
}
pub fn push(&mut self, item: T) {
let pos = self.data.len();
self.data.push(item);
self.data.sift_up(pos, &self.ord);
}
pub fn pop(&mut self) -> Option<T> {
let item = self.data.pop()?;
Some(self.data.pop_swap(item, &self.ord))
}
pub fn reserve(&mut self, additional: usize) {
self.data.reserve(additional);
}
pub fn reserve_exact(&mut self, additional: usize) {
self.data.reserve_exact(additional);
}
pub fn shrink_to_fit(&mut self) {
self.data.shrink_to_fit();
}
pub fn shrink_to(&mut self, min_capacity: usize) {
self.data.shrink_to(min_capacity);
}
pub fn append(&mut self, other: &mut Self) {
if self.len() < other.len() {
std::mem::swap(self, other);
}
let start = self.len();
self.data.append(&mut other.data);
self.data.rebuild_tail(start, &self.ord);
}
}
pub struct PeekMut<'a, T, O: Ordering<T>> {
raw: raw_heap::PeekMut<'a, Vec<T>>,
ord: &'a O,
}
impl<'a, T, O: Ordering<T>> Drop for PeekMut<'a, T, O> {
fn drop(&mut self) {
self.restore();
}
}
impl<'a, T, O: Ordering<T>> Deref for PeekMut<'a, T, O> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.raw.as_ref()
}
}
impl<'a, T, O: Ordering<T>> DerefMut for PeekMut<'a, T, O> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.raw.as_mut()
}
}
impl<'a, T, O: Ordering<T>> PeekMut<'a, T, O> {
fn restore(&mut self) {
self.raw.restore(self.ord);
}
pub fn pop(mut self) -> T {
self.raw.ignore_mutation();
let heap = self.raw.heap_mut();
let item = heap.pop().unwrap();
heap.pop_swap(item, self.ord)
}
}