chj_rustbin/util/
map_trait.rs1use std::{
4 collections::{BTreeMap, HashMap},
5 hash::Hash,
6};
7
8pub trait MapTrait<K, V> {
9 fn new() -> Self;
10 fn clear(&mut self);
11 fn insert(&mut self, k: K, v: V) -> Option<V>;
12 fn get(&self, k: &K) -> Option<&V>;
13 fn get_mut(&mut self, k: &K) -> Option<&mut V>;
14}
15
16#[macro_export]
22macro_rules! implement_map_trait_for {
23 { $MapTypeName:ident, impl $($impl_line_tokens:tt)* } =>
24 {
25 impl $($impl_line_tokens)* {
26 fn new() -> Self {
27 $MapTypeName::new()
28 }
29
30 fn clear(&mut self) {
31 $MapTypeName::clear(self);
32 }
33
34 fn insert(&mut self, k: K, v: V) -> Option<V> {
35 $MapTypeName::insert(self, k, v)
36 }
37
38 fn get(&self, k: &K) -> Option<&V> {
39 $MapTypeName::get(self, k)
40 }
41
42 fn get_mut(&mut self, k: &K) -> Option<&mut V> {
43 $MapTypeName::get_mut(self, k)
44 }
45 }
46 }
47}
48
49implement_map_trait_for! {HashMap, impl<K: Eq + Hash, V: Eq> MapTrait<K, V> for HashMap<K, V>}
50
51implement_map_trait_for! {BTreeMap, impl<K: Eq + Ord, V: Eq> MapTrait<K, V> for BTreeMap<K, V>}