use super::EcoMap;
pub enum Entry<'a, K: Clone + PartialEq, V: Clone> {
Occupied(OccupiedEntry<'a, K, V>),
Vacant(VacantEntry<'a, K, V>),
}
pub struct OccupiedEntry<'a, K: Clone + PartialEq, V: Clone> {
map: &'a mut EcoMap<K, V>,
index: usize,
}
pub struct VacantEntry<'a, K: Clone + PartialEq, V: Clone> {
map: &'a mut EcoMap<K, V>,
key: K,
}
impl<'a, K: Clone + PartialEq, V: Clone> Entry<'a, K, V> {
#[inline]
pub fn key(&self) -> &K {
match self {
Entry::Occupied(o) => o.key(),
Entry::Vacant(v) => v.key(),
}
}
#[inline]
pub fn or_insert(self, default: V) -> &'a mut V {
match self {
Entry::Occupied(o) => o.into_mut(),
Entry::Vacant(v) => v.insert(default),
}
}
#[inline]
pub fn or_insert_with(self, f: impl FnOnce() -> V) -> &'a mut V {
match self {
Entry::Occupied(o) => o.into_mut(),
Entry::Vacant(v) => v.insert(f()),
}
}
#[inline]
pub fn or_insert_with_key(self, f: impl FnOnce(&K) -> V) -> &'a mut V {
match self {
Entry::Occupied(o) => o.into_mut(),
Entry::Vacant(v) => {
let value = f(v.key());
v.insert(value)
}
}
}
#[inline]
pub fn or_default(self) -> &'a mut V
where
V: Default,
{
self.or_insert_with(Default::default)
}
#[inline]
pub fn and_modify(self, f: impl FnOnce(&mut V)) -> Self {
match self {
Entry::Occupied(mut o) => {
f(o.get_mut());
Entry::Occupied(o)
}
Entry::Vacant(v) => Entry::Vacant(v),
}
}
}
impl<'a, K: Clone + PartialEq, V: Clone> OccupiedEntry<'a, K, V> {
pub(super) fn new(map: &'a mut EcoMap<K, V>, index: usize) -> Self {
Self { map, index }
}
#[inline]
pub fn key(&self) -> &K {
&self.map.keys[self.index]
}
#[inline]
pub fn get(&self) -> &V {
&self.map.vals[self.index]
}
#[inline]
pub fn get_mut(&mut self) -> &mut V {
&mut self.map.vals.make_mut()[self.index]
}
#[inline]
pub fn into_mut(self) -> &'a mut V {
&mut self.map.vals.make_mut()[self.index]
}
#[inline]
pub fn insert(&mut self, value: V) -> V {
let old = self.map.vals[self.index].clone();
self.map.vals.make_mut()[self.index] = value;
old
}
#[inline]
pub fn remove(self) -> V {
self.remove_entry().1
}
#[inline]
pub fn remove_entry(self) -> (K, V) {
let last = self.map.len() - 1;
let keys = self.map.keys.make_mut();
let vals = self.map.vals.make_mut();
keys.swap(self.index, last);
vals.swap(self.index, last);
let k = self.map.keys.pop().unwrap();
let v = self.map.vals.pop().unwrap();
(k, v)
}
}
impl<'a, K: Clone + PartialEq, V: Clone> VacantEntry<'a, K, V> {
pub(super) fn new(map: &'a mut EcoMap<K, V>, key: K) -> Self {
Self { map, key }
}
#[inline]
pub fn key(&self) -> &K {
&self.key
}
#[inline]
pub fn into_key(self) -> K {
self.key
}
#[inline]
pub fn insert(self, value: V) -> &'a mut V {
self.map.keys.push(self.key);
self.map.vals.push(value);
let last = self.map.vals.len() - 1;
&mut self.map.vals.make_mut()[last]
}
}