use std::marker::PhantomData;
use super::{Index, Slab};
#[derive(Debug)]
pub struct SecondaryMap<K, V>(Slab<Index, V>, PhantomData<K>);
impl<K, V> SecondaryMap<K, V>
where
K: Into<Index>,
{
pub fn empty() -> Self {
Self(Slab::empty(), PhantomData)
}
pub fn insert(&mut self, key: K, value: V) {
self.0.insert_at(key.into(), value);
}
pub fn get(&self, key: K) -> Option<&V> {
self.0.get(key.into())
}
pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
self.0.get_mut(key.into())
}
pub fn remove(&mut self, key: K) -> V {
self.0.remove(key.into())
}
pub fn try_remove(&mut self, key: K) -> Option<V> {
self.0.try_remove(key.into())
}
pub fn remove_if<F>(&mut self, key: K, f: F) -> Option<V>
where
F: Fn(&V) -> bool,
{
self.0.remove_if(key.into(), f)
}
pub fn iter(&self) -> impl Iterator<Item = &V> {
self.0.iter().map(|(_, v)| v)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn insert_and_get() {
let mut map = SecondaryMap::empty();
map.insert(0usize, 1);
assert_eq!(*map.get(0usize).unwrap(), 1);
}
#[test]
fn remove_if_cond() {
let mut map = SecondaryMap::empty();
map.insert(0usize, 1);
map.insert(1usize, 2);
map.insert(2usize, 4);
for i in 0usize..3 {
map.remove_if(i, |val| *val % 2 == 0);
}
}
}