scsys_traits/
store.rs

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