chj_rustbin/util/
map_trait.rs

1//! A trait to represent maps (like HashMap or BTreeMap).
2
3use 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 that defines code to delegate trait methods to the
17/// same-named and -typed original methods. This requires the map type
18/// name to be given twice, and to use K and V as type names, or the
19/// macro wouldn't work (macros by example do not appear to have the
20/// features necessay to do this properly).
21#[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>}