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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#![allow(dead_code)]

use std::borrow::Borrow;

pub struct AssocList<K, V>(Vec<(K, V)>);
pub enum Entry<'a, K, V> {
    Vacant(VacantEntry<'a, K, V>),
    Occupied(OccupiedEntry<'a, K, V>),
}
pub struct VacantEntry<'a, K, V> {
    key: K,
    map: &'a mut AssocList<K, V>,
}
pub struct OccupiedEntry<'a, K, V> {
    key: K,
    map: &'a mut AssocList<K, V>,
}

impl<K: Eq, V> AssocList<K, V> {
    pub fn new() -> Self { Self(vec![]) }

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

    pub fn get<Q>(&self, key: Q) -> Option<&V>
    where
        Q: Borrow<K>,
        K: PartialEq<Q>,
    {
        self.0.iter().find(|(k, _)| k == &key).map(|(_, v)| v)
    }

    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        if let Some((_, v)) = self.0.iter_mut().find(|(k, _)| k == &key) {
            Some(std::mem::replace(v, value))
        } else {
            self.0.push((key, value));
            None
        }
    }

    pub fn remove<Q>(&mut self, key: Q) -> Option<V>
    where
        Q: Borrow<K>,
        K: PartialEq<Q>,
    {
        (0..self.0.len())
            .find(|&i| self.0[i].0 == key)
            .map(|i| self.0.remove(i).1)
    }

    pub fn entry(&mut self, key: K) -> Entry<K, V> {
        if self.0.iter().any(|(k, _)| k == &key) {
            Entry::occupied(key, self)
        } else {
            Entry::vacant(key, self)
        }
    }
}

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

impl<'a, K: Eq, V> Entry<'a, K, V> {
    pub(crate) fn vacant(key: K, map: &'a mut AssocList<K, V>) -> Self {
        Self::Vacant(VacantEntry { key, map })
    }
    pub(crate) fn occupied(key: K, map: &'a mut AssocList<K, V>) -> Self {
        Self::Occupied(OccupiedEntry { key, map })
    }

    pub fn and_modify<F: FnOnce(&mut V)>(self, f: F) -> Entry<'a, K, V> {
        match self {
            Self::Occupied(mut entry) => {
                f(entry.get_mut());
                Self::Occupied(entry)
            }
            Self::Vacant(entry) => Self::Vacant(entry),
        }
    }

    pub fn key(&self) -> &K {
        match *self {
            Self::Occupied(ref entry) => entry.key(),
            Self::Vacant(ref entry) => entry.key(),
        }
    }
    pub fn or_default(self) -> &'a mut V
    where
        V: Default,
    {
        match self {
            Self::Occupied(entry) => entry.into_mut(),
            Self::Vacant(entry) => entry.insert(Default::default()),
        }
    }
    pub fn or_insert(self, default: V) -> &'a mut V {
        match self {
            Self::Occupied(entry) => entry.into_mut(),
            Self::Vacant(entry) => entry.insert(default),
        }
    }
    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
        match self {
            Self::Occupied(entry) => entry.into_mut(),
            Self::Vacant(entry) => entry.insert(default()),
        }
    }
    pub fn or_insert_with_key<F: FnOnce(&K) -> V>(
        self,
        default: F,
    ) -> &'a mut V {
        match self {
            Self::Occupied(entry) => entry.into_mut(),
            Self::Vacant(entry) => {
                let value = default(entry.key());
                entry.insert(value)
            }
        }
    }
}

impl<'a, K: Eq, V> VacantEntry<'a, K, V> {
    pub fn into_key(self) -> K { self.key }
    pub fn key(&self) -> &K { &self.key }
    pub fn insert(self, value: V) -> &'a mut V {
        let Self { key, map } = self;
        map.0.push((key, value));
        &mut map.0.last_mut().unwrap().1
    }
}

impl<'a, K: Eq, V> OccupiedEntry<'a, K, V> {
    pub fn insert(&mut self, value: V) -> V {
        std::mem::replace(self.get_mut(), value)
    }
    pub fn get(&self) -> &V {
        let Self { key, map } = self;
        map.0.iter().find(|(k, _)| k == key).map(|(_, v)| v).unwrap()
    }
    pub fn get_mut(&mut self) -> &mut V {
        let Self { key, map } = self;
        map.0.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v).unwrap()
    }
    pub fn into_mut(self) -> &'a mut V {
        let Self { key, map } = self;
        map.0.iter_mut().find(|(k, _)| k == &key).map(|(_, v)| v).unwrap()
    }
    pub fn key(&self) -> &K { &self.key }
    pub fn remove(self) -> V { self.remove_entry().1 }
    pub fn remove_entry(self) -> (K, V) {
        let Self { key, map } = self;
        let i = (0..map.len()).find(|&i| key == map.0[i].0).unwrap();
        map.0.remove(i)
    }
}

#[test]
fn sanity_check() {
    let mut alist = AssocList::new();

    assert_eq!(alist.entry(0).key(), &0);

    alist.entry(0).or_insert("zero");
    assert_eq!(alist.get(0).unwrap(), &"zero");
    assert_eq!(alist.len(), 1);

    alist.entry(0).or_insert_with(|| "xxx");
    assert_eq!(alist.get(0).unwrap(), &"zero");
    assert_eq!(alist.len(), 1);

    alist.entry(2).or_insert_with_key(|_| "two");
    assert!(alist.get(1).is_none());
    assert_eq!(alist.get(2).unwrap(), &"two");
    assert_eq!(alist.len(), 2);

    alist.entry(2).and_modify(|v| *v = "second");
    assert_eq!(alist.len(), 2);

    if let Entry::Occupied(o) = alist.entry(2) {
        assert_eq!(o.get(), &"second");
        assert_eq!(o.remove(), "second");
        assert_eq!(alist.len(), 1);
    }

    alist.entry(1).or_default();
    assert_eq!(alist.len(), 2);
    assert!(alist.get(1).unwrap().is_empty());
    if let Entry::Occupied(mut o) = alist.entry(1) {
        o.insert("first");
        assert_eq!(o.get(), &"first");
    }
}