1 //! This module defines a `DynMap` -- a container for heterogeneous maps.
3 //! This means that `DynMap` stores a bunch of hash maps inside, and those maps
4 //! can be of different types.
6 //! It is used like this:
9 //! // keys define submaps of a `DynMap`
10 //! const STRING_TO_U32: Key<String, u32> = Key::new();
11 //! const U32_TO_VEC: Key<u32, Vec<bool>> = Key::new();
13 //! // Note: concrete type, no type params!
14 //! let mut map = DynMap::new();
16 //! // To access a specific map, index the `DynMap` by `Key`:
17 //! map[STRING_TO_U32].insert("hello".to_string(), 92);
18 //! let value = map[U32_TO_VEC].get(92);
19 //! assert!(value.is_none());
22 //! This is a work of fiction. Any similarities to Kotlin's `BindingContext` are
27 ops::{Index, IndexMut},
31 use rustc_hash::FxHashMap;
33 pub struct Key<K, V, P = (K, V)> {
34 _phantom: PhantomData<(K, V, P)>,
37 impl<K, V, P> Key<K, V, P> {
38 pub(crate) const fn new() -> Key<K, V, P> {
39 Key { _phantom: PhantomData }
43 impl<K, V, P> Copy for Key<K, V, P> {}
45 impl<K, V, P> Clone for Key<K, V, P> {
46 fn clone(&self) -> Key<K, V, P> {
55 fn insert(map: &mut DynMap, key: Self::K, value: Self::V);
56 fn get<'a>(map: &'a DynMap, key: &Self::K) -> Option<&'a Self::V>;
59 impl<K: Hash + Eq + 'static, V: 'static> Policy for (K, V) {
62 fn insert(map: &mut DynMap, key: K, value: V) {
63 map.map.entry::<FxHashMap<K, V>>().or_insert_with(Default::default).insert(key, value);
65 fn get<'a>(map: &'a DynMap, key: &K) -> Option<&'a V> {
66 map.map.get::<FxHashMap<K, V>>()?.get(key)
74 impl Default for DynMap {
75 fn default() -> Self {
76 DynMap { map: Map::new() }
81 pub struct KeyMap<KEY> {
83 _phantom: PhantomData<KEY>,
86 impl<P: Policy> KeyMap<Key<P::K, P::V, P>> {
87 pub fn insert(&mut self, key: P::K, value: P::V) {
88 P::insert(&mut self.map, key, value)
90 pub fn get(&self, key: &P::K) -> Option<&P::V> {
91 P::get(&self.map, key)
95 impl<P: Policy> Index<Key<P::K, P::V, P>> for DynMap {
96 type Output = KeyMap<Key<P::K, P::V, P>>;
97 fn index(&self, _key: Key<P::K, P::V, P>) -> &Self::Output {
98 // Safe due to `#[repr(transparent)]`.
99 unsafe { std::mem::transmute::<&DynMap, &KeyMap<Key<P::K, P::V, P>>>(self) }
103 impl<P: Policy> IndexMut<Key<P::K, P::V, P>> for DynMap {
104 fn index_mut(&mut self, _key: Key<P::K, P::V, P>) -> &mut Self::Output {
105 // Safe due to `#[repr(transparent)]`.
106 unsafe { std::mem::transmute::<&mut DynMap, &mut KeyMap<Key<P::K, P::V, P>>>(self) }