pub struct TypedDashMap<Marker = (), KB: Bounds = SyncAnyBounds, VB: Bounds = SyncAnyBounds, S = RandomState> { /* private fields */ }
Expand description

A concurrent hash 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 DashMap is used. Note: that it will deadlock whenever DashMap will.

§Examples

use std::sync::Arc;
use typedmap::TypedDashMap;
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 configs: Arc<TypedDashMap<Configs>> = Arc::new(TypedDashMap::new());
let services: Arc<TypedDashMap<Services>> = Arc::new(TypedDashMap::new());
let default: Arc<TypedDashMap> = Arc::new(TypedDashMap::new());

let configs1 = Arc::clone(&configs);
let services1 = Arc::clone(&services);
let t1 = std::thread::spawn(move ||{
    configs1.insert(ServiceA(0), 1);
    services1.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");

let configs2 = Arc::clone(&configs);
let services2 = Arc::clone(&services);
let default2 = Arc::clone(&default);
let t2 = std::thread::spawn(move || {
    configs2.insert(ServiceB("zero"), vec!["one"]);
    services2.insert(ServiceB("zero"), 32);
    default2.insert(ServiceB("zero"), "one".to_owned());
});

t1.join().unwrap();
t2.join().unwrap();

assert_eq!(*configs.get(&ServiceB("zero")).unwrap(), vec!["one"]);
assert_eq!(*services.get(&ServiceB("zero")).unwrap(), 32);
assert_eq!(*default.get(&ServiceB("zero")).unwrap(), "one".to_owned());

Implementations§

source§

impl<Marker> TypedDashMap<Marker>

source

pub fn new() -> Self

Creates a new TypedDashMap 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 TypedDashMap with a specified capacity and specified marker type

source§

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

source

pub fn new_with_bounds() -> Self

source§

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

source

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

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

source

pub fn with_hasher(hash_builder: S) -> Self

Creates a new TypedDashMap with specified hasher and marker type.

source

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

Inserts a key and a value 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 old value is returned.

§Examples
use typedmap::TypedDashMap;
use typedmap::TypedMapKey;

#[derive(Debug, Hash, PartialEq, Eq)]
struct Key(usize);

impl TypedMapKey for Key {
    type Value = usize;
}

let mut map: TypedDashMap = TypedDashMap::with_capacity(10);
assert!(map.insert(Key(3), 4).is_none());
assert_eq!(map.insert(Key(3), 5), Some(4));
assert_eq!(*map.get(&Key(3)).unwrap(), 5);
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::{TypedDashMap};
use typedmap::TypedMapKey;

#[derive(Hash, PartialEq, Eq)]
struct Key(usize);

impl TypedMapKey for Key {
    type Value = usize;
}

let mut map: TypedDashMap = TypedDashMap::with_capacity(10);
let kv = TypedKeyValue::new(Key(3), 4);
map.insert_key_value(kv);
assert_eq!(*map.get(&Key(3)).unwrap().value(), 4);
source

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

Get the entry of a key if it exists in the map.

§Examples
use typedmap::TypedDashMap;
use typedmap::TypedMapKey;

#[derive(Hash, PartialEq, Eq)]
struct Key(usize);

impl TypedMapKey for Key {
    type Value = usize;
}

let mut map: TypedDashMap = TypedDashMap::with_capacity(10);
assert!(map.get(&Key(3)).is_none());
map.insert(Key(3), 4);
assert_eq!(*map.get(&Key(3)).unwrap(), 4);
source

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

Get mutable entry of a key if it exists in the map.

§Examples
use typedmap::TypedDashMap;
use typedmap::TypedMapKey;

#[derive(Hash, PartialEq, Eq)]
struct Key(usize);

impl TypedMapKey for Key {
    type Value = usize;
}

let mut map: TypedDashMap = TypedDashMap::with_capacity(10);
assert!(map.get_mut(&Key(3)).is_none());
map.insert(Key(3), 4);
*map.get_mut(&Key(3)).unwrap() = 5;
assert_eq!(*map.get(&Key(3)).unwrap().value(), 5);
source

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

Check if the map contains a specific key.

§Examples
use typedmap::TypedDashMap;
use typedmap::TypedMapKey;

#[derive(Hash, PartialEq, Eq)]
struct Key(usize);

impl TypedMapKey for Key {
    type Value = usize;
}

let mut map: TypedDashMap = TypedDashMap::with_capacity(10);
assert!(!map.contains_key(&Key(3)));
map.insert(Key(3), 4);
assert!(map.contains_key(&Key(3)));
source

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

Removes an entry from the map.

Returns both key and value if the key existed and the entry was removed. Otherwise returns None.

§Examples
use typedmap::TypedDashMap;
use typedmap::TypedMapKey;

#[derive(Debug, Hash, PartialEq, Eq)]
struct Key(usize);

impl TypedMapKey for Key {
    type Value = usize;
}

let mut map: TypedDashMap = TypedDashMap::with_capacity(10);
assert!(map.remove(&Key(3)).is_none());
map.insert(Key(3), 4);
assert!(map.contains_key(&Key(3)));
assert_eq!(map.remove(&Key(3)), Some((Key(3), 4)));
assert!(!map.contains_key(&Key(3)));
source

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

Removes an entry from the map the provided conditional function returned true.

Returns both key and value if the key existed and the entry was removed. Otherwise returns None.

§Examples
use typedmap::TypedDashMap;
use typedmap::TypedMapKey;

#[derive(Debug, Hash, PartialEq, Eq)]
struct Key(usize);

impl TypedMapKey for Key {
    type Value = usize;
}

let mut map: TypedDashMap = TypedDashMap::with_capacity(10);
assert!(map.remove(&Key(3)).is_none());
map.insert(Key(3), 4);
assert!(map.contains_key(&Key(3)));
assert_eq!(map.remove_if(&Key(3), |k, v| false), None);
assert!(map.contains_key(&Key(3)));
assert_eq!(map.remove_if(&Key(3), |k, v| true), Some((Key(3), 4)));
assert!(!map.contains_key(&Key(3)));
source

pub fn len(&self) -> usize

Get the amount of entries in the map.

§Examples
use typedmap::TypedDashMap;
use typedmap::TypedMapKey;

#[derive(Hash, PartialEq, Eq, Debug)]
struct Key(usize);

impl TypedMapKey for Key {
    type Value = usize;
}

let mut map: TypedDashMap = TypedDashMap::with_capacity(10);
assert_eq!(map.len(), 0);
map.insert(Key(3), 4);
assert_eq!(map.len(), 1);
source

pub fn is_empty(&self) -> bool

Returns true if the map contains no elements.

§Examples
use typedmap::TypedDashMap;
use typedmap::TypedMapKey;

#[derive(Hash, PartialEq, Eq)]
struct Key(usize);

impl TypedMapKey for Key {
    type Value = f32;
}

let mut map: TypedDashMap = TypedDashMap::with_capacity(10);
assert!(map.is_empty());
map.insert(Key(3), 4.0);
assert!(!map.is_empty());
source

pub fn clear(&self)

Clears the map, removing all key-value pairs.

§Examples:
use typedmap::TypedDashMap;
use typedmap::TypedMapKey;

#[derive(Hash, PartialEq, Eq)]
struct Key(usize);

impl TypedMapKey for Key {
    type Value = f32;
}

let mut map: TypedDashMap = TypedDashMap::new();
map.insert(Key(3), 4.0);
map.clear();
assert!(map.get(&Key(3)).is_none())
// assert!(map.is_empty()); // for some reason this fails
source

pub fn iter(&self) -> Iter<'_, Marker, KB, VB, S>

An iterator visiting all key-value pairs in arbitrary order.

§Examples
use typedmap::TypedDashMap;
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: TypedDashMap = TypedDashMap::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(&self) -> IterMut<'_, Marker, KB, VB, S>

An iterator visiting all key-value pairs in arbitrary order yielding mutable references.

§Examples
use typedmap::TypedDashMap;
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: TypedDashMap = TypedDashMap::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));
        assert_eq!(value, &3u32);
        *value = 4u32;
    }

    if let Some((key, value)) = key_value.downcast_pair_mut::<SKey>() {
        assert_eq!(key, &SKey("four"));
        assert_eq!(value, &4);
    }
}
source

pub fn entry<K>(&self, key: K) -> Entry<'_, K, KB, VB, Marker, S>
where K: 'static + TypedMapKey<Marker>, KB: HasBounds<K>, VB: HasBounds<K::Value>,

Gets the given key’s corresponding entry in the map for in-place manipulation.

§Examples
use typedmap::TypedDashMap;
use typedmap::TypedMapKey;

#[derive(Hash, PartialEq, Eq)]
struct Key(char);

impl TypedMapKey for Key {
    type Value = usize;
}

let letters: TypedDashMap = TypedDashMap::new();
for ch in "a short treatise on fungi".chars() {
   let mut counter = letters.entry(Key(ch)).or_insert(0);
   *counter += 1;
}
assert_eq!(letters.get(&Key('s')).unwrap().value(), &2);
assert_eq!(letters.get(&Key('t')).unwrap().value(), &3);
assert_eq!(letters.get(&Key('u')).unwrap().value(), &1);
assert!(letters.get(&Key('y')).is_none());
source

pub fn retain( &self, predicate: impl FnMut(TypedKeyValueRef<'_, Marker, KB, VB>) -> bool )

Retain elements that the filter closure returns true for.

§Examples
use typedmap::TypedDashMap;
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: TypedDashMap = TypedDashMap::new();
map.insert(Key(3), 3);
map.insert(SKey("four"), 4);

map.retain(|kv| kv.downcast_key_ref::<Key>().is_some());
assert!(map.contains_key(&Key(3)));

Trait Implementations§

source§

impl<M, KB: 'static + Bounds, VB: 'static + Bounds> Clone for TypedDashMap<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, S> Debug for TypedDashMap<Marker, KB, VB, S>
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> Default for TypedDashMap<Marker>

source§

fn default() -> Self

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

impl<M, KB: Bounds, VB: Bounds, S: BuildHasher + Clone + Default> FromIterator<TypedKeyValue<M, KB, VB>> for TypedDashMap<M, KB, VB, S>

source§

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

Creates a value from an iterator. Read more

Auto Trait Implementations§

§

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

§

impl<Marker = (), KB = SyncAnyBounds, VB = SyncAnyBounds, S = RandomState> !RefUnwindSafe for TypedDashMap<Marker, KB, VB, S>

§

impl<Marker, KB, VB, S> Send for TypedDashMap<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 TypedDashMap<Marker, KB, VB, S>
where Marker: Sync, S: Sync + Send, <VB as Bounds>::Container: Sync + Send, <KB as Bounds>::KeyContainer: Sync + Send,

§

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

§

impl<Marker, KB, VB, S> UnwindSafe for TypedDashMap<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.