pub trait Map<'m, K, V: 'm> {
type GetGuard<'a>: Deref<Target = V>
where Self: 'a;
// Required methods
fn get<'a, Q>(&'a self, k: &Q) -> Option<Self::GetGuard<'a>>
where K: Borrow<Q>,
Q: Hash + Eq + Ord + ?Sized;
fn insert(&mut self, k: K, v: V) -> Option<V>;
}Expand description
A generic Map trait
§Examples
This is a toy example of a map which reexposes an inner map and stores the most recent key and value to be inserted. Because the LastInsertMap implements Map, it can be seamlessly used as a replacement for other maps.
use std::borrow::Borrow;
use std::hash::Hash;
use std::collections::HashMap;
use map_trait::map::Map;
struct LastInsertMap<M, K, V> {
inner_map: M,
last_key: K,
last_value: V,
}
impl<'m, K, V, M> LastInsertMap<M, K, V>
where
K: Copy,
V: 'm + Copy,
M: Map<'m, K, V>,
{
fn new(mut map: M, key: K, value: V) -> Self {
map.insert(key, value);
LastInsertMap {
inner_map: map,
last_key: key,
last_value: value,
}
}
fn get_last_insert(&self) -> (&K, &V) {
(&self.last_key, &self.last_value)
}
}
impl<'m, K, V, M> Map<'m, K, V> for LastInsertMap<M, K, V>
where
K: Copy,
V: 'm + Copy,
M: Map<'m, K, V>,
{
type GetGuard<'a> = M::GetGuard<'a> where Self: 'a;
#[inline]
fn get<'a, Q: ?Sized>(&'a self, k: &Q) -> Option<Self::GetGuard<'a>>
where
K: Borrow<Q>,
Q: Hash + Eq + Ord,
{
self.inner_map.get(k)
}
#[inline]
fn insert(&mut self, k: K, v: V) -> Option<V> {
self.last_key = k;
self.last_value = v;
self.inner_map.insert(k, v)
}
}
let mut map = LastInsertMap::new(HashMap::new(), 0, 1);
assert_eq!(map.get_last_insert(), (&0, &1));
assert_eq!(map.get(&0), Some(&1));
assert_eq!(map.insert(1, 2), None);
assert_eq!(map.get(&1), Some(&2));
assert_eq!(map.get_last_insert(), (&1, &2));Required Associated Types§
Required Methods§
fn get<'a, Q>(&'a self, k: &Q) -> Option<Self::GetGuard<'a>>
fn insert(&mut self, k: K, v: V) -> Option<V>
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.