pub struct TypedMap<Marker = (), KB: Bounds = AnyBounds, VB: Bounds = AnyBounds, S = RandomState> { /* private fields */ }
Expand description
A map that can store keys of any type that implements TypedMapKey
and values
of type defined by TypedMapKey::Value
. One can use Marker to define multiple
“key-value” type mappings. Under the hood the std::collections::HashMap
is used.
KB
and VB
type parameters may be used to add additional bounds for accepted either key types
or value types. This crate provides crate::bounds::AnyBounds
, crate::bounds::SyncAnyBounds
and if clone
feature is enabled crate::clone::CloneBounds
and crate::clone::SyncCloneBounds
. However, it is possible
to implement custom bounds as shown in crate::bounds
example.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
struct Configs;
struct Services;
#[derive(Hash, PartialEq, Eq)]
struct ServiceA(usize);
// Implement key-value mapping for Configs marker
impl TypedMapKey<Configs> for ServiceA {
type Value = usize;
}
// Implement key-value mapping for Services marker
impl TypedMapKey<Services> for ServiceA {
type Value = &'static str;
}
#[derive(Hash, PartialEq, Eq)]
struct ServiceB(&'static str);
// Implement key-value mapping for Configs marker
impl TypedMapKey<Configs> for ServiceB {
type Value = Vec<&'static str>;
}
// Implement key-value mapping for Services marker
impl TypedMapKey<Services> for ServiceB {
type Value = usize;
}
// Implement key-value mapping for default (i.e. ()) marker
impl TypedMapKey for ServiceB {
type Value = String;
}
let mut configs: TypedMap<Configs> = TypedMap::new();
let mut services: TypedMap<Services> = TypedMap::new();
let mut default: TypedMap = TypedMap::new();
configs.insert(ServiceA(0), 1);
services.insert(ServiceA(0), "one");
// Line below would not compile, because TypeMapKey<Marker=()>
// is not implemented for Key.
// default.insert(Key(0), 1);
// Line below would not compile, because SerivceA key defines
// type value as usize for Configs marker (not &'static str)
// configs.insert(ServiceA(0), "one");
configs.insert(ServiceB("zero"), vec!["one"]);
services.insert(ServiceB("zero"), 32);
default.insert(ServiceB("zero"), "one".to_owned());
assert_eq!(configs[&ServiceB("zero")], vec!["one"]);
assert_eq!(services[&ServiceB("zero")], 32);
assert_eq!(default[&ServiceB("zero")], "one".to_owned());
Implementations§
source§impl<Marker, KB, VB> TypedMap<Marker, KB, VB>
impl<Marker, KB, VB> TypedMap<Marker, KB, VB>
pub fn new_with_bounds() -> Self
source§impl<Marker, KB, VB, S> TypedMap<Marker, KB, VB, S>
impl<Marker, KB, VB, S> TypedMap<Marker, KB, VB, S>
sourcepub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self
Creates a new TypedMap with specified capacity, hasher and marker type.
sourcepub fn with_hasher(hash_builder: S) -> Self
pub fn with_hasher(hash_builder: S) -> Self
Creates a new TypedMap with specified hasher and marker type.
sourcepub fn insert<K>(&mut self, key: K, value: K::Value) -> Option<K::Value>
pub fn insert<K>(&mut self, key: K, value: K::Value) -> Option<K::Value>
Inserts a key-value pair into the map.
If the map did not have this key present, None is returned.
If the map did have this key present, the value is updated, and the old value is returned.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq)]
struct Key(usize);
impl TypedMapKey for Key {
type Value = usize;
}
let mut map: TypedMap = TypedMap::with_capacity(10);
map.insert(Key(3), 4);
assert_eq!(map[&Key(3)], 4);
sourcepub fn insert_key_value(
&mut self,
key_value: TypedKeyValue<Marker, KB, VB>
) -> Option<TypedKeyValue<Marker, KB, VB>>
pub fn insert_key_value( &mut self, key_value: TypedKeyValue<Marker, KB, VB> ) -> Option<TypedKeyValue<Marker, KB, VB>>
Inserts a TypedKeyValue into the map from .
If the map did not have this key present, None is returned.
If the map did have this key present, the value is updated, and the old value is returned.
§Examples
use typedmap::hashmap::TypedKeyValue;
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq)]
struct Key(usize);
impl TypedMapKey for Key {
type Value = usize;
}
let mut map: TypedMap = TypedMap::with_capacity(10);
let kv = TypedKeyValue::new(Key(3), 4);
map.insert_key_value(kv);
assert_eq!(map[&Key(3)], 4);
sourcepub fn get<K>(&self, key: &K) -> Option<&K::Value>
pub fn get<K>(&self, key: &K) -> Option<&K::Value>
Returns a reference to the value corresponding to the key.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq)]
struct Key(usize);
impl TypedMapKey for Key {
type Value = usize;
}
let mut map: TypedMap = TypedMap::with_capacity(10);
map.insert(Key(3), 4);
assert_eq!(map.get(&Key(3)), Some(&4));
assert_eq!(map.get(&Key(4)), None);
sourcepub fn get_mut<K>(&mut self, key: &K) -> Option<&mut K::Value>
pub fn get_mut<K>(&mut self, key: &K) -> Option<&mut K::Value>
Returns a mutable reference to the value corresponding to the key.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq)]
struct Key(usize);
impl TypedMapKey for Key {
type Value = usize;
}
let mut map: TypedMap = TypedMap::with_capacity(10);
map.insert(Key(3), 4);
let key = Key(3);
if let Some(value) = map.get_mut(&key) {
*value += 1;
}
assert_eq!(map.get(&key), Some(&5));
sourcepub fn get_key_value<K>(&self, key: &K) -> Option<(&K, &K::Value)>
pub fn get_key_value<K>(&self, key: &K) -> Option<(&K, &K::Value)>
Returns the key-value pair corresponding to the supplied key.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq, Debug)]
struct Key(usize);
impl TypedMapKey for Key {
type Value = usize;
}
let mut map: TypedMap = TypedMap::with_capacity(10);
map.insert(Key(3), 4);
assert_eq!(map.get_key_value(&Key(3)), Some((&Key(3), &4)));
assert_eq!(map.get(&Key(4)), None);
sourcepub fn remove<K>(&mut self, key: &K) -> Option<K::Value>
pub fn remove<K>(&mut self, key: &K) -> Option<K::Value>
Removes a key from the map, returning the value at the key if the key was previously in the map.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq)]
struct Key(usize);
impl TypedMapKey for Key {
type Value = usize;
}
let mut map: TypedMap = TypedMap::with_capacity(10);
map.insert(Key(3), 4);
assert_eq!(map.remove(&Key(3)), Some(4));
assert_eq!(map.get(&Key(3)), None);
sourcepub fn remove_entry<K>(&mut self, key: &K) -> Option<(K, K::Value)>
pub fn remove_entry<K>(&mut self, key: &K) -> Option<(K, K::Value)>
Removes a key from the map, returning the stored key and value if the key was previously in the map.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq, Debug)]
struct Key(usize);
impl TypedMapKey for Key {
type Value = usize;
}
let mut map: TypedMap = TypedMap::with_capacity(10);
map.insert(Key(3), 4);
assert_eq!(map.remove_entry(&Key(3)), Some((Key(3), 4)));
assert_eq!(map.remove(&Key(3)), None);
sourcepub fn entry<K>(&mut self, key: K) -> Entry<'_, K, KB, VB, Marker>
pub fn entry<K>(&mut self, key: K) -> Entry<'_, K, KB, VB, Marker>
Gets the given key’s corresponding entry in the map for in-place manipulation.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq)]
struct Key(char);
impl TypedMapKey for Key {
type Value = usize;
}
let mut letters: TypedMap = TypedMap::new();
for ch in "a short treatise on fungi".chars() {
let counter = letters.entry(Key(ch)).or_insert(0);
*counter += 1;
}
assert_eq!(letters.get(&Key('s')), Some(&2));
assert_eq!(letters.get(&Key('t')), Some(&3));
assert_eq!(letters.get(&Key('u')), Some(&1));
assert_eq!(letters.get(&Key('y')), None);
sourcepub fn contains_key<K>(&self, key: &K) -> bool
pub fn contains_key<K>(&self, key: &K) -> bool
Returns true if the map contains a value for the specified key.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq, Debug)]
struct Key(usize);
impl TypedMapKey for Key {
type Value = usize;
}
let mut map: TypedMap = TypedMap::with_capacity(10);
map.insert(Key(3), 4);
assert!(map.contains_key(&Key(3)));
assert!(!map.contains_key(&Key(4)));
sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of elements in the map.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq, Debug)]
struct Key(usize);
impl TypedMapKey for Key {
type Value = usize;
}
let mut map: TypedMap = TypedMap::with_capacity(10);
assert_eq!(map.len(), 0);
map.insert(Key(3), 4);
assert_eq!(map.len(), 1);
sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the number of elements the map can hold without reallocating.
§Examples
use typedmap::TypedMap;
let map: TypedMap = TypedMap::with_capacity(10);
assert!(map.capacity() >= 10);
sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true if the map contains no elements.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq)]
struct Key(usize);
impl TypedMapKey for Key {
type Value = f32;
}
let mut map: TypedMap = TypedMap::with_capacity(10);
assert!(map.is_empty());
map.insert(Key(3), 4.0);
assert!(!map.is_empty());
sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.
§Examples:
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq)]
struct Key(usize);
impl TypedMapKey for Key {
type Value = f32;
}
let mut map: TypedMap = TypedMap::new();
map.insert(Key(3), 4.0);
map.clear();
assert!(map.is_empty());
sourcepub fn reserve(&mut self, additional: usize)
pub fn reserve(&mut self, additional: usize)
Reserves capacity for at least additional more elements to be inserted in the HashMap. The collection may reserve more space to avoid frequent reallocations.
§Panics
Panics if the new allocation size overflows usize
§Examples
use typedmap::TypedMap;
let mut map: TypedMap = TypedMap::new();
map.reserve(1000);
assert!(map.capacity() >= 1000);
sourcepub fn shrink_to_fit(&mut self)
pub fn shrink_to_fit(&mut self)
Shrinks the capacity of the underlying hash map as much as possible.
§Examples
use typedmap::TypedMap;
let mut map: TypedMap = TypedMap::with_capacity(1000);
map.shrink_to_fit();
assert!(map.capacity() <= 16);
sourcepub fn keys(&self) -> Keys<'_, KB, VB> ⓘ
pub fn keys(&self) -> Keys<'_, KB, VB> ⓘ
An iterator visiting all keys in arbitrary order. The iterator element type is &'a dyn Any
.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq, Debug)]
struct Key(usize);
#[derive(Hash, PartialEq, Eq, Debug)]
struct SKey(&'static str);
impl TypedMapKey for Key {
type Value = u32;
}
impl TypedMapKey for SKey {
type Value = usize;
}
let mut map: TypedMap = TypedMap::new();
map.insert(Key(3), 3);
map.insert(SKey("four"), 4);
for key in map.keys() {
let mut found = false;
if let Some(Key(number)) = key.downcast_ref::<Key>() {
assert_eq!(*number, 3);
found = true;
}
if let Some(SKey(a_str)) = key.downcast_ref::<SKey>() {
assert_eq!(*a_str, "four");
found = true;
}
assert!(found);
}
sourcepub fn values(&self) -> Values<'_, KB, VB> ⓘ
pub fn values(&self) -> Values<'_, KB, VB> ⓘ
An iterator visiting all values in arbitrary order. The iterator element type is &’a dyn Any.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq, Debug)]
struct Key(usize);
#[derive(Hash, PartialEq, Eq, Debug)]
struct SKey(&'static str);
impl TypedMapKey for Key {
type Value = u32;
}
impl TypedMapKey for SKey {
type Value = usize;
}
let mut map: TypedMap = TypedMap::new();
map.insert(Key(3), 3);
map.insert(SKey("four"), 4);
for value in map.values() {
let mut found = false;
if let Some(number) = value.downcast_ref::<u32>() {
assert_eq!(*number, 3);
found = true;
}
if let Some(number) = value.downcast_ref::<usize>() {
assert_eq!(*number, 4);
found = true;
}
assert!(found);
}
sourcepub fn values_mut(&mut self) -> ValuesMut<'_, KB, VB> ⓘ
pub fn values_mut(&mut self) -> ValuesMut<'_, KB, VB> ⓘ
An iterator visiting all values mutably in arbitrary order. The iterator element type is &’a mut dyn Any.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq, Debug)]
struct Key(usize);
#[derive(Hash, PartialEq, Eq, Debug)]
struct SKey(&'static str);
impl TypedMapKey for Key {
type Value = u32;
}
impl TypedMapKey for SKey {
type Value = usize;
}
let mut map: TypedMap = TypedMap::new();
map.insert(Key(3), 3);
map.insert(SKey("four"), 4);
for value in map.values_mut() {
let mut found = false;
if let Some(number) = value.downcast_mut::<u32>() {
*number += 1;
found = true;
}
if let Some(number) = value.downcast_mut::<usize>() {
*number += 2;
found = true;
}
assert!(found);
}
assert_eq!(map[&Key(3)], 4);
assert_eq!(map[&SKey("four")], 6);
sourcepub fn drain(&mut self) -> Drain<'_, Marker, KB, VB> ⓘ
pub fn drain(&mut self) -> Drain<'_, Marker, KB, VB> ⓘ
Clears the map, returning all key-value pairs as an iterator. Keeps the allocated memory for reuse.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq, Debug)]
struct Key(usize);
#[derive(Hash, PartialEq, Eq, Debug)]
struct SKey(&'static str);
impl TypedMapKey for Key {
type Value = u32;
}
impl TypedMapKey for SKey {
type Value = usize;
}
let mut map: TypedMap = TypedMap::new();
map.insert(Key(3), 3);
map.insert(SKey("four"), 4);
for key_value in map.drain() {
match key_value.downcast_pair::<Key>() {
Ok((key, value)) => {
assert_eq!(key, Key(3));
assert_eq!(value, 3u32);
}
Err(key_value) => {
let (key, value) = key_value.downcast_pair::<SKey>().unwrap();
assert_eq!(key, SKey("four"));
assert_eq!(value, 4usize);
}
}
}
sourcepub fn iter(&self) -> Iter<'_, Marker, KB, VB> ⓘ
pub fn iter(&self) -> Iter<'_, Marker, KB, VB> ⓘ
An iterator visiting all key-value pairs in arbitrary order.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq, Debug)]
struct Key(usize);
#[derive(Hash, PartialEq, Eq, Debug)]
struct SKey(&'static str);
impl TypedMapKey for Key {
type Value = u32;
}
impl TypedMapKey for SKey {
type Value = usize;
}
let mut map: TypedMap = TypedMap::new();
map.insert(Key(3), 3);
map.insert(SKey("four"), 4);
for key_value in map.iter() {
if let Some((key, value)) = key_value.downcast_pair_ref::<Key>() {
assert_eq!(key, &Key(3));
assert_eq!(value, &3u32);
}
if let Some((key, value)) = key_value.downcast_pair_ref::<SKey>() {
assert_eq!(key, &SKey("four"));
assert_eq!(value, &4);
}
}
sourcepub fn iter_mut(&mut self) -> IterMut<'_, Marker, KB, VB> ⓘ
pub fn iter_mut(&mut self) -> IterMut<'_, Marker, KB, VB> ⓘ
An iterator visiting all key-value pairs in arbitrary order, with mutable references to the values.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq, Debug)]
struct Key(usize);
#[derive(Hash, PartialEq, Eq, Debug)]
struct SKey(&'static str);
impl TypedMapKey for Key {
type Value = u32;
}
impl TypedMapKey for SKey {
type Value = usize;
}
let mut map: TypedMap = TypedMap::new();
map.insert(Key(3), 3);
map.insert(SKey("four"), 4);
for mut key_value in map.iter_mut() {
if let Some((key, value)) = key_value.downcast_pair_mut::<Key>() {
assert_eq!(key, &Key(3));
*value += 1;
assert_eq!(value, &4u32);
}
if let Some((key, value)) = key_value.downcast_pair_mut::<SKey>() {
assert_eq!(key, &SKey("four"));
*value += 1;
assert_eq!(value, &5);
}
}
assert_eq!(map[&Key(3)], 4);
assert_eq!(map[&SKey("four")], 5);
sourcepub fn retain<F>(&mut self, f: F)
pub fn retain<F>(&mut self, f: F)
Retains only the elements specified by the predicate.
§Examples
use typedmap::TypedMap;
use typedmap::TypedMapKey;
#[derive(Hash, PartialEq, Eq, Debug)]
struct Key(usize);
impl TypedMapKey for Key {
type Value = u32;
}
let mut map: TypedMap = TypedMap::new();
map.insert(Key(3), 3);
map.insert(Key(4), 4);
map.insert(Key(5), 5);
map.retain(|mut kv| *kv.downcast_value::<u32>().unwrap_or(&mut 0) % 2 == 1);
assert_eq!(map.len(), 2);
assert!(map.contains_key(&Key(5)));
assert!(!map.contains_key(&Key(4)));
map.retain(|mut kv| kv.downcast_key_ref::<Key>().unwrap().0 <= 3);
assert!(map.contains_key(&Key(3)));
assert!(!map.contains_key(&Key(5)));