#![deny(unsafe_op_in_unsafe_fn, clippy::undocumented_unsafe_blocks)]
use std::ops::Deref;
use std::ptr::NonNull;
use crate::guard::GuardHandle;
use crate::key::AsBytes;
use crate::node::Leaf;
use crate::tree::Tree;
pub struct EntryRef<'a, K, V> {
pub(crate) leaf: NonNull<Leaf<K, V>>,
pub(crate) tree: &'a Tree<K, V>,
pub(crate) guard: GuardHandle<'a>,
}
impl<'a, K, V> EntryRef<'a, K, V> {
#[inline]
pub(crate) fn new(
leaf: NonNull<Leaf<K, V>>,
tree: &'a Tree<K, V>,
guard: GuardHandle<'a>,
) -> Self {
Self { leaf, tree, guard }
}
#[inline]
fn leaf(&self) -> &Leaf<K, V> {
unsafe { self.leaf.as_ref() }
}
#[inline]
pub fn key(&self) -> &K {
&self.leaf().key
}
#[inline]
pub fn value(&self) -> &V {
&self.leaf().value
}
#[inline]
pub fn is_removed(&self) -> bool {
self.leaf().is_removed()
}
#[inline]
pub fn to_owned(&self) -> (K, V)
where
K: Clone,
V: Clone,
{
(self.key().clone(), self.value().clone())
}
#[inline]
pub fn value_cloned(&self) -> V
where
V: Clone,
{
self.value().clone()
}
}
impl<K: AsBytes + Send + 'static, V: Send + 'static> EntryRef<'_, K, V> {
#[inline]
pub fn remove(&self) -> bool {
self.tree.remove_leaf(self.leaf, self.guard.guard())
}
}
impl<K, V> Clone for EntryRef<'_, K, V> {
#[inline]
fn clone(&self) -> Self {
Self {
leaf: self.leaf,
tree: self.tree,
guard: self.guard.duplicate(),
}
}
}
impl<K, V> Deref for EntryRef<'_, K, V> {
type Target = V;
#[inline]
fn deref(&self) -> &V {
self.value()
}
}
impl<K: std::fmt::Debug, V: std::fmt::Debug> std::fmt::Debug for EntryRef<'_, K, V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EntryRef")
.field("key", self.key())
.field("value", self.value())
.field("is_removed", &self.is_removed())
.finish()
}
}
impl<K: PartialEq, V: PartialEq> PartialEq for EntryRef<'_, K, V> {
fn eq(&self, other: &Self) -> bool {
self.key() == other.key() && self.value() == other.value()
}
}
impl<K: Eq, V: Eq> Eq for EntryRef<'_, K, V> {}