concision_core/traits/misc/
store.rs1pub trait Entry<'a> {
6 type Key;
7 type Value;
8
9 fn key(&self) -> &Self::Key;
10
11 fn or_insert(self, default: Self::Value) -> &'a mut Self::Value;
12}
13
14pub trait OrInsert<K, V> {
15 fn or_insert(&mut self, key: K, value: V) -> &mut V;
16}
17
18pub trait Store<K, V> {
19 fn get(&self, key: &K) -> Option<&V>;
20
21 fn get_mut(&mut self, key: &K) -> Option<&mut V>;
22
23 fn insert(&mut self, key: K, value: V) -> Option<V>;
24
25 fn remove(&mut self, key: &K) -> Option<V>;
26}
27
28macro_rules! entry {
29 ($($prefix:ident)::* -> $call:ident($($arg:tt),*)) => {
30 $($prefix)::*::Entry::$call($($arg),*)
31 };
32
33}
34
35macro_rules! impl_entry {
36 ($($prefix:ident)::* where $($preds:tt)* ) => {
37
38 impl<'a, K, V> Entry<'a> for $($prefix)::*::Entry<'a, K, V> where $($preds)* {
39 type Key = K;
40 type Value = V;
41
42 fn key(&self) -> &Self::Key {
43 entry!($($prefix)::* -> key(self))
44 }
45
46 fn or_insert(self, default: Self::Value) -> &'a mut Self::Value {
47 entry!($($prefix)::* -> or_insert(self, default))
48 }
49 }
50
51 };
52
53}
54
55macro_rules! impl_store {
56 ($t:ty, where $($preds:tt)* ) => {
57
58 impl<K, V> Store<K, V> for $t where $($preds)* {
59 fn get(&self, key: &K) -> Option<&V> {
60 <$t>::get(self, &key)
61 }
62
63 fn get_mut(&mut self, key: &K) -> Option<&mut V> {
64 <$t>::get_mut(self, &key)
65 }
66
67 fn insert(&mut self, key: K, value: V) -> Option<V> {
68 <$t>::insert(self, key, value)
69 }
70
71 fn remove(&mut self, key: &K) -> Option<V> {
72 <$t>::remove(self, &key)
73 }
74 }
75
76 };
77}
78
79#[cfg(all(feature = "alloc", no_std))]
80impl_entry!(alloc::collections::btree_map where K: Ord);
81#[cfg(all(feature = "alloc", no_std))]
82impl_store!(alloc::collections::BTreeMap<K, V>, where K: Ord);
83#[cfg(feature = "std")]
84impl_entry!(std::collections::btree_map where K: Ord);
85#[cfg(feature = "std")]
86impl_store!(std::collections::BTreeMap<K, V>, where K: Ord);
87#[cfg(feature = "std")]
88impl_entry!(std::collections::hash_map where K: Eq + core::hash::Hash);
89#[cfg(feature = "std")]
90impl_store!(std::collections::HashMap<K, V>, where K: Eq + core::hash::Hash);