1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// SPDX-License-Identifier: AGPL-3.0-or-later
//! This module defines [HashMapWithDefault].

use std::{borrow::Borrow, collections::HashMap, hash::Hash, ops::Index};

/// A newtype wrapping a [HashMap] which allows
/// a default value to be defined.
/// When a key is not found in the [HashMap] the default value is returned, instead of [None].
pub struct HashMapWithDefault<K, V> {
    hash_map: HashMap<K, V>,
    default: V,
}

impl<K, V> HashMapWithDefault<K, V> {
    /// Create a new hash map with the given default value.
    pub fn new(default: V) -> Self {
        Self {
            hash_map: HashMap::new(),
            default,
        }
    }

    /// Get a reference to the inner [HashMap].
    pub fn get_ref(&self) -> &HashMap<K, V> {
        &self.hash_map
    }

    /// Get a mutable reference to the inner [HashMap].
    pub fn get_mut(&mut self) -> &mut HashMap<K, V> {
        &mut self.hash_map
    }

    /// Returns a reference to the default value.
    pub fn default(&self) -> &V {
        &self.default
    }

    /// Returns a mutable reference to the default value.
    pub fn mut_default(&mut self) -> &mut V {
        &mut self.default
    }
}

impl<K: Hash + Eq, V> HashMapWithDefault<K, V> {
    /// Lookup up the item with the given key in the hash table. If no value is found then the
    /// default is returned.
    pub fn get<Q: ?Sized + Hash + Eq>(&self, index: &Q) -> &V
    where
        K: Borrow<Q>,
    {
        self.hash_map.get(index).unwrap_or(&self.default)
    }
}

impl<Q: ?Sized + Hash + Eq, K: Borrow<Q> + Hash + Eq, V> Index<&Q> for HashMapWithDefault<K, V> {
    type Output = V;
    fn index(&self, index: &Q) -> &Self::Output {
        self.get(index)
    }
}