use super::core::{MutableNodeMap, ValueAdapter};
#[derive(Debug)]
pub enum Entry<'a, K, V, A: ValueAdapter<K, V>>
where
K: PartialEq + Eq + Clone + Copy + std::hash::Hash,
V: Clone,
{
Occupied(OccupiedEntry<'a, K, V, A>),
Vacant(VacantEntry<'a, K, V, A>),
}
impl<'a, K, V, A: ValueAdapter<K, V>> Entry<'a, K, V, A>
where
K: PartialEq + Eq + Clone + Copy + std::hash::Hash,
V: Clone,
{
pub fn or_insert(self, default: V) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(default),
}
}
pub fn or_insert_with<F: FnOnce() -> V>(self, call: F) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(call()),
}
}
pub fn key(&self) -> &K {
match self {
Entry::Occupied(entry) => entry.key(),
Entry::Vacant(entry) => entry.key(),
}
}
pub fn and_modify<F>(self, f: F) -> Self
where
F: FnOnce(&mut V),
{
match self {
Entry::Occupied(mut entry) => {
f(entry.get_mut());
Entry::Occupied(entry)
}
Entry::Vacant(entry) => Entry::Vacant(entry),
}
}
pub fn or_default(self) -> &'a mut V
where
V: Default,
{
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(V::default()),
}
}
}
#[derive(Debug)]
pub struct OccupiedEntry<'a, K, V, A: ValueAdapter<K, V>>
where
K: PartialEq + Eq + Clone + Copy + std::hash::Hash,
V: Clone,
{
map: &'a mut MutableNodeMap<'a, K, V, A>,
key: K,
}
impl<'a, K, V, A> OccupiedEntry<'a, K, V, A>
where
K: PartialEq + Eq + Clone + Copy + std::hash::Hash,
V: Clone,
A: ValueAdapter<K, V>,
{
pub(crate) fn new(map: &'a mut MutableNodeMap<'a, K, V, A>, key: K) -> Self {
Self { map, key }
}
pub fn get(&self) -> &V {
self.map.get(self.key).unwrap()
}
pub fn get_mut(&mut self) -> &mut V {
self.map.get_mut(self.key).unwrap()
}
pub fn into_mut(self) -> &'a mut V {
self.map.get_mut(self.key).unwrap()
}
pub fn insert(&mut self, value: V) -> V {
self.map.insert(self.key, value).unwrap()
}
pub fn remove(self) -> V {
self.map.remove(self.key).unwrap()
}
pub fn key(&self) -> &K {
&self.key
}
}
#[derive(Debug)]
pub struct VacantEntry<'a, K, V, A: ValueAdapter<K, V>>
where
K: PartialEq + Eq + Clone + Copy,
V: Clone,
{
map: &'a mut MutableNodeMap<'a, K, V, A>,
key: K,
}
impl<'a, K, V, A> VacantEntry<'a, K, V, A>
where
K: PartialEq + Eq + Clone + Copy + std::hash::Hash,
V: Clone,
A: ValueAdapter<K, V>,
{
pub(crate) fn new(map: &'a mut MutableNodeMap<'a, K, V, A>, key: K) -> Self {
Self { map, key }
}
pub fn insert(self, value: V) -> &'a mut V {
self.map.insert(self.key, value);
self.map.get_mut(self.key).unwrap()
}
pub fn key(&self) -> &K {
&self.key
}
}