use slab::Slab;
use std::borrow::Borrow;
use std::mem;
use crate::store::item::{Key, Value};
use crate::store::{Store, StoreMut, StoreMutRef};
mod iter;
pub use iter::{Iter, IterMut, Keys, Values};
impl<K, V> Store<K, V> for Slab<(K, V)> {
#[inline]
fn get<Q>(&self, key: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Key,
{
Slab::iter(self).find_map(|(_, (check, value))| {
(check.borrow() == key).then_some(value)
})
}
#[inline]
fn contains_key<Q>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Key,
{
Slab::iter(self).any(|(_, (check, _))| check.borrow() == key)
}
#[inline]
fn len(&self) -> usize {
Slab::len(self)
}
}
impl<K, V> StoreMut<K, V> for Slab<(K, V)>
where
K: Key,
V: Value,
{
#[inline]
fn insert(&mut self, key: K, value: V) -> Option<V> {
let opt = Slab::iter_mut(self).find(|(_, (check, _))| check == &key);
if let Some((_, (_, prior))) = opt {
(prior != &value).then(|| mem::replace(prior, value))
} else {
self.insert((key, value));
None
}
}
#[inline]
fn remove<Q>(&mut self, key: &Q) -> Option<V>
where
K: Borrow<Q>,
Q: Key,
{
self.remove_entry(key).map(|(_, value)| value)
}
#[inline]
fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
where
K: Borrow<Q>,
Q: Key,
{
Slab::iter(self)
.position(|(_, (check, _))| check.borrow() == key)
.map(|index| self.remove(index))
}
#[inline]
fn clear(&mut self) {
Slab::clear(self);
}
}
impl<K, V> StoreMutRef<K, V> for Slab<(K, V)>
where
K: Key,
{
#[inline]
fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
where
K: Borrow<Q>,
Q: Key,
{
Slab::iter_mut(self).find_map(|(_, (check, value))| {
((*check).borrow() == key).then_some(value)
})
}
#[inline]
fn get_or_insert_default(&mut self, key: &K) -> &mut V
where
V: Default,
{
let index = Slab::iter(self)
.position(|(_, (check, _))| check == key)
.unwrap_or_else(|| Slab::insert(self, (key.clone(), V::default())));
&mut self[index].1
}
}