Struct typedmap::hashmap::TypedMap

source ·
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> TypedMap<Marker>

source

pub fn new() -> Self

Creates a new TypedMap with specified marker type.

§Examples:
use typedmap::TypedMap;

struct Configs;
let map = TypedMap::<Configs>::new();
source

pub fn with_capacity(capacity: usize) -> Self

Creates a new TypedMap with a specified capacity and specified marker type

source§

impl<Marker, KB, VB> TypedMap<Marker, KB, VB>
where KB: 'static + Bounds, VB: 'static + Bounds,

source

pub fn new_with_bounds() -> Self

source§

impl<Marker, KB, VB, S> TypedMap<Marker, KB, VB, S>
where S: BuildHasher, KB: 'static + Bounds, VB: 'static + Bounds,

source

pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self

Creates a new TypedMap with specified capacity, hasher and marker type.

source

pub fn with_hasher(hash_builder: S) -> Self

Creates a new TypedMap with specified hasher and marker type.

source

pub fn insert<K>(&mut self, key: K, value: K::Value) -> Option<K::Value>
where KB: HasBounds<K>, VB: HasBounds<K::Value>, K: 'static + TypedMapKey<Marker>,

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);
source

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);
source

pub fn get<K>(&self, key: &K) -> Option<&K::Value>
where KB: HasBounds<K>, VB: HasBounds<K::Value>, K: 'static + TypedMapKey<Marker>,

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);
source

pub fn get_mut<K>(&mut self, key: &K) -> Option<&mut K::Value>
where KB: HasBounds<K>, VB: HasBounds<K::Value>, K: 'static + TypedMapKey<Marker>,

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));
source

pub fn get_key_value<K>(&self, key: &K) -> Option<(&K, &K::Value)>
where KB: HasBounds<K>, VB: HasBounds<K::Value>, K: 'static + TypedMapKey<Marker>,

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);
source

pub fn remove<K>(&mut self, key: &K) -> Option<K::Value>
where KB: HasBounds<K>, VB: HasBounds<K::Value>, K: 'static + TypedMapKey<Marker>,

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);
source

pub fn remove_entry<K>(&mut self, key: &K) -> Option<(K, K::Value)>
where KB: HasBounds<K>, VB: HasBounds<K::Value>, K: 'static + TypedMapKey<Marker>,

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);
source

pub fn entry<K>(&mut self, key: K) -> Entry<'_, K, KB, VB, Marker>
where KB: HasBounds<K>, VB: HasBounds<K::Value>, K: 'static + TypedMapKey<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);
source

pub fn contains_key<K>(&self, key: &K) -> bool
where KB: HasBounds<K>, VB: HasBounds<K::Value>, K: 'static + TypedMapKey<Marker>,

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)));
source

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);
source

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);
source

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());
source

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());
source

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);
source

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);
source

pub fn hasher(&self) -> &S

Returns a reference to the map’s BuildHasher.

source

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);
}
source

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);
}
source

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);
source

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);
        }
    }
}
source

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);
    }
}
source

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);
source

pub fn retain<F>(&mut self, f: F)
where F: FnMut(TypedKeyValueMutRef<'_, Marker, KB, VB>) -> bool,

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)));

Trait Implementations§

source§

impl<M, KB: 'static + Bounds, VB: 'static + Bounds> Clone for TypedMap<M, KB, VB>

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<Marker, KB, VB> Debug for TypedMap<Marker, KB, VB>
where KB: 'static + Bounds, VB: 'static + Bounds,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<Marker, KB, VB> Default for TypedMap<Marker, KB, VB>
where KB: 'static + Bounds, VB: 'static + Bounds,

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<M, KB: Bounds, VB: Bounds> FromIterator<TypedKeyValue<M, KB, VB>> for TypedMap<M, KB, VB>

source§

fn from_iter<T: IntoIterator<Item = TypedKeyValue<M, KB, VB>>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl<Marker, K, S, KB, VB> Index<&K> for TypedMap<Marker, KB, VB, S>
where K: 'static + TypedMapKey<Marker>, S: BuildHasher, KB: 'static + Bounds + HasBounds<K>, VB: 'static + Bounds + HasBounds<K::Value>,

§

type Output = <K as TypedMapKey<Marker>>::Value

The returned type after indexing.
source§

fn index(&self, key: &K) -> &K::Value

Performs the indexing (container[index]) operation. Read more
source§

impl<Marker, KB, VB, S> IntoIterator for TypedMap<Marker, KB, VB, S>
where KB: 'static + Bounds, VB: 'static + Bounds, S: BuildHasher,

§

type Item = TypedKeyValue<Marker, KB, VB>

The type of the elements being iterated over.
§

type IntoIter = IntoIter<Marker, KB, VB>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<Marker, KB, VB, S> Freeze for TypedMap<Marker, KB, VB, S>
where S: Freeze,

§

impl<Marker, KB, VB, S> RefUnwindSafe for TypedMap<Marker, KB, VB, S>

§

impl<Marker, KB, VB, S> Send for TypedMap<Marker, KB, VB, S>
where Marker: Send, S: Send, <VB as Bounds>::Container: Send, <KB as Bounds>::KeyContainer: Send,

§

impl<Marker, KB, VB, S> Sync for TypedMap<Marker, KB, VB, S>
where Marker: Sync, S: Sync, <VB as Bounds>::Container: Sync, <KB as Bounds>::KeyContainer: Sync,

§

impl<Marker, KB, VB, S> Unpin for TypedMap<Marker, KB, VB, S>
where Marker: Unpin, S: Unpin,

§

impl<Marker, KB, VB, S> UnwindSafe for TypedMap<Marker, KB, VB, S>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneAny for T
where T: Clone + Any,

source§

fn as_any(&self) -> &(dyn Any + 'static)

source§

fn as_mut_any(&mut self) -> &mut (dyn Any + 'static)

source§

fn as_any_box(self: Box<T>) -> Box<dyn Any>

source§

impl<T> DynClone for T
where T: Clone,

source§

fn __clone_box(&self, _: Private) -> *mut ()

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.