pub use fixed_map_derive::Key;
pub trait Key<K: 'static, V: 'static> {
type Storage: Storage<K, V>;
}
pub trait Storage<K: 'static, V: 'static>: Default {
fn insert(&mut self, key: K, value: V) -> Option<V>;
fn get(&self, key: &K) -> Option<&V>;
fn get_mut(&mut self, key: &K) -> Option<&mut V>;
fn remove(&mut self, key: &K) -> Option<V>;
fn clear(&mut self);
fn iter<'a, F>(&'a self, f: F)
where
F: FnMut((&'a K, &'a V));
fn iter_mut<'a, F>(&'a mut self, f: F)
where
F: FnMut((&'a K, &'a mut V));
}
pub struct Map<K: 'static, V: 'static>
where
K: Key<K, V>,
{
storage: K::Storage,
}
impl<K: 'static, V: 'static> Map<K, V>
where
K: Key<K, V>,
{
pub fn new() -> Map<K, V> {
Map {
storage: K::Storage::default(),
}
}
pub fn keys<'a, F>(&'a self, mut f: F)
where
F: FnMut(&'a K),
{
self.iter(|(k, _)| f(k));
}
pub fn values<'a, F>(&'a self, mut f: F)
where
F: FnMut(&'a V),
{
self.iter(|(_, v)| f(v));
}
pub fn values_mut<'a, F>(&'a mut self, mut f: F)
where
F: FnMut(&'a mut V),
{
self.iter_mut(|(_, v)| f(v));
}
pub fn iter<'a, F>(&'a self, f: F)
where
F: FnMut((&'a K, &'a V)),
{
self.storage.iter(f)
}
pub fn iter_mut<'a, F>(&'a mut self, f: F)
where
F: FnMut((&'a K, &'a mut V)),
{
self.storage.iter_mut(f)
}
pub fn get(&self, key: &K) -> Option<&V> {
self.storage.get(key)
}
pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
self.storage.get_mut(key)
}
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
self.storage.insert(key, value)
}
pub fn remove(&mut self, key: &K) -> Option<V> {
self.storage.remove(key)
}
pub fn clear(&mut self) {
self.storage.clear()
}
pub fn is_empty(&self) -> bool {
let mut empty = true;
self.storage.iter(|_| {
empty = false;
});
empty
}
pub fn len(&self) -> usize {
let mut len = 0;
self.storage.iter(|_| {
len += 1;
});
len
}
}
impl<K, V> Clone for Map<K, V>
where
K: Key<K, V>,
K::Storage: Clone,
{
fn clone(&self) -> Map<K, V> {
Map {
storage: self.storage.clone(),
}
}
}