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>;
57 fn is_empty(map: &DynMap) -> bool;
60 impl<K: Hash + Eq + 'static, V: 'static> Policy for (K, V) {
63 fn insert(map: &mut DynMap, key: K, value: V) {
64 map.map.entry::<FxHashMap<K, V>>().or_insert_with(Default::default).insert(key, value);
66 fn get<'a>(map: &'a DynMap, key: &K) -> Option<&'a V> {
67 map.map.get::<FxHashMap<K, V>>()?.get(key)
69 fn is_empty(map: &DynMap) -> bool {
70 map.map.get::<FxHashMap<K, V>>().map_or(true, |it| it.is_empty())
78 impl Default for DynMap {
79 fn default() -> Self {
80 DynMap { map: Map::new() }
85 pub struct KeyMap<KEY> {
87 _phantom: PhantomData<KEY>,
90 impl<P: Policy> KeyMap<Key<P::K, P::V, P>> {
91 pub fn insert(&mut self, key: P::K, value: P::V) {
92 P::insert(&mut self.map, key, value)
94 pub fn get(&self, key: &P::K) -> Option<&P::V> {
95 P::get(&self.map, key)
98 pub fn is_empty(&self) -> bool {
99 P::is_empty(&self.map)
103 impl<P: Policy> Index<Key<P::K, P::V, P>> for DynMap {
104 type Output = KeyMap<Key<P::K, P::V, P>>;
105 fn index(&self, _key: Key<P::K, P::V, P>) -> &Self::Output {
106 // Safe due to `#[repr(transparent)]`.
107 unsafe { std::mem::transmute::<&DynMap, &KeyMap<Key<P::K, P::V, P>>>(self) }
111 impl<P: Policy> IndexMut<Key<P::K, P::V, P>> for DynMap {
112 fn index_mut(&mut self, _key: Key<P::K, P::V, P>) -> &mut Self::Output {
113 // Safe due to `#[repr(transparent)]`.
114 unsafe { std::mem::transmute::<&mut DynMap, &mut KeyMap<Key<P::K, P::V, P>>>(self) }