sugar/
hashmap_ext.rs

1use std::hash::{BuildHasher, Hash};
2use std::collections::HashMap;
3use std::borrow::Borrow;
4
5pub trait SHashMapExt<K, V> {
6    fn get_clone<Q: ?Sized>(&self, k: &Q) -> Option<V>
7    where
8        K: Borrow<Q>,
9        Q: Hash + Eq,
10        V: Clone;
11}
12
13impl<K, V, S> SHashMapExt<K, V> for HashMap<K, V, S>
14where
15    K: Eq + Hash,
16    S: BuildHasher,
17{
18    fn get_clone<Q: ?Sized>(&self, k: &Q) -> Option<V>
19    where
20        K: Borrow<Q>,
21        Q: Hash + Eq,
22        V: Clone,
23    {
24        self.get(k).map(|v| (*v).clone())
25    }
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31
32    #[test]
33    fn it_works() {
34        // In plain Rust, the code below can't build
35        // let _ = {
36        //     let mut map = HashMap::new();
37        //     map.insert(1, "1");
38        //     map.get(&1)
39        // };
40
41        // After using the SHashmapExt, we can build these code below.
42        let _ = {
43            let mut map = HashMap::new();
44            map.insert(1, "1");
45            map.get_clone(&1)
46        };
47    }
48}