use crate::{Heap, MeldableHeap};
use super::soft_heap_core::{SoftHeapCore, SoftHeapError, SoftMeldError};
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BinaryTreeSoftHeap<K> {
core: SoftHeapCore<K, ()>,
}
impl<K: Ord + Clone> BinaryTreeSoftHeap<K> {
pub fn new(error_rate: f64) -> Result<Self, SoftHeapError> {
Ok(Self {
core: SoftHeapCore::new(error_rate)?,
})
}
}
impl<K: Ord + Clone> BinaryTreeSoftHeap<K> {
#[must_use]
pub const fn rank_limit(&self) -> usize {
self.core.rank_limit()
}
pub fn push(&mut self, key: K) {
self.core.insert(key, ());
}
#[must_use]
pub fn peek(&self) -> Option<&K> {
self.core.peek_entry().map(|(_, key, _)| key)
}
pub fn pop(&mut self) -> Option<K> {
self.core.pop_item().map(|item| item.into_pair().0)
}
#[must_use]
pub const fn len(&self) -> usize {
self.core.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.core.len() == 0
}
pub fn clear(&mut self) {
self.core.clear();
}
}
impl<K: Ord + Clone> BinaryTreeSoftHeap<K> {
pub fn meld(&mut self, other: Self) -> Result<(), SoftMeldError> {
if self.rank_limit() != other.rank_limit() {
return Err(SoftMeldError::IncompatibleErrorRate);
}
self.core.meld_from(other.core);
Ok(())
}
}
impl<T: Ord + Clone> Heap<T> for BinaryTreeSoftHeap<T> {
fn push(&mut self, value: T) {
Self::push(self, value);
}
fn peek(&self) -> Option<&T> {
Self::peek(self)
}
fn pop(&mut self) -> Option<T> {
Self::pop(self)
}
fn len(&self) -> usize {
Self::len(self)
}
fn clear(&mut self) {
Self::clear(self);
}
}
impl<T: Ord + Clone> MeldableHeap<T> for BinaryTreeSoftHeap<T> {
type MeldError = SoftMeldError;
fn meld(&mut self, other: Self) -> Result<(), Self::MeldError> {
Self::meld(self, other)
}
}