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
use indexmap::map::{IntoIter, Keys};
use std::cmp::Eq;
use std::hash::Hash;

/// HashMap which provides
/// 1. Immutable APIs
/// 2. Preserving insertion order
pub struct IndexMap<K, V>(indexmap::IndexMap<K, V>);

impl<K: Hash + Eq, V> IndexMap<K, V> {
    pub fn new() -> Self {
        Self(indexmap::IndexMap::new())
    }

    pub fn insert(mut self, key: K, value: V) -> (Self, Option<V>) {
        let existing = self.0.insert(key, value);

        (self, existing)
    }

    pub fn get(&self, key: &K) -> Option<&V> {
        self.0.get(key)
    }

    pub fn keys(&self) -> Keys<K, V> {
        self.0.keys()
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl<K: Hash + Eq, V> Default for IndexMap<K, V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<K: Hash + Eq, V> IntoIterator for IndexMap<K, V> {
    type Item = (K, V);
    type IntoIter = IntoIter<K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}