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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
use serde::de::{MapAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::borrow::Borrow;
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::iter::FromIterator;
use std::marker::PhantomData;

#[derive(Clone, Eq, Hash, PartialOrd, PartialEq)]
pub struct FakeMap<K, V> {
    items: Vec<(K, V)>,
}

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

impl<K, V> FakeMap<K, V> {
    pub fn new() -> Self {
        FakeMap { items: Vec::new() }
    }

    pub fn with_capacity(cap: usize) -> Self {
        FakeMap {
            items: Vec::with_capacity(cap),
        }
    }

    #[inline]
    pub fn insert(&mut self, k: K, v: V)
    where
        K: Eq,
    {
        match self.get_idx_of_key(&k) {
            None => {
                self.items.push((k, v));
            }
            Some(x) => {
                self.items[x].1 = v;
            }
        }
    }

    fn get_idx_of_key<Q: ?Sized>(&self, key: &Q) -> Option<usize>
    where
        Q: PartialEq,
        K: Borrow<Q>,
    {
        self.items.iter().position(|item| item.0.borrow() == key)
    }

    #[inline]
    pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
    where
        Q: PartialEq,
        K: Borrow<Q>,
    {
        self.get_idx_of_key(key).map(|idx| &self.items[idx].1)
    }

    #[inline]
    pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
    where
        Q: PartialEq,
        K: Borrow<Q>,
    {
        self.get_idx_of_key(key).map(|idx| self.items.remove(idx).1)
    }

    pub fn iter(&self) -> impl Iterator<Item = &(K, V)> {
        self.items.iter()
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&mut K, &mut V)> {
        self.items.iter_mut().map(|kv| (&mut kv.0, &mut kv.1))
    }

    pub fn keys(&self) -> impl Iterator<Item = &K> {
        self.items.iter().map(|kv| &kv.0)
    }

    pub fn keys_mut(&self) -> impl Iterator<Item = &K> {
        self.items.iter().map(|kv| &kv.0)
    }

    pub fn values(&self) -> impl Iterator<Item = &V> {
        self.items.iter().map(|kv| &kv.1)
    }

    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
        self.items.iter_mut().map(|kv| &mut kv.1)
    }
}

impl<K, V> Debug for FakeMap<K, V>
where
    K: Debug,
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{{")?;
        for (i, (key, value)) in self.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{:?}: {:?}", key, value)?;
        }
        write!(f, "}}")?;

        Ok(())
    }
}

impl<K, V> IntoIterator for FakeMap<K, V> {
    type Item = (K, V);
    type IntoIter = std::vec::IntoIter<(K, V)>;

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

impl<K, V> FromIterator<(K, V)> for FakeMap<K, V> {
    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
        FakeMap {
            items: iter.into_iter().collect(),
        }
    }
}

// A Visitor is a type that holds methods that a Deserializer can drive
// depending on what is contained in the input data.
//
// In the case of a map we need generic type parameters K and V to be
// able to set the output type correctly, but don't require any state.
// This is an example of a "zero sized type" in Rust. The PhantomData
// keeps the compiler from complaining about unused generic type
// parameters.
struct FakeMapVisitor<K, V> {
    marker: PhantomData<fn() -> FakeMap<K, V>>,
}

impl<K, V> FakeMapVisitor<K, V> {
    fn new() -> Self {
        FakeMapVisitor {
            marker: PhantomData,
        }
    }
}

// This is the trait that Deserializers are going to be driving. There
// is one method for each type of data that our type knows how to
// deserialize from. There are many other methods that are not
// implemented here, for example deserializing from integers or strings.
// By default those methods will return an error, which makes sense
// because we cannot deserialize a MyMap from an integer or string.
impl<'de, K, V> Visitor<'de> for FakeMapVisitor<K, V>
where
    K: Deserialize<'de> + Eq,
    V: Deserialize<'de>,
{
    // The type that our Visitor is going to produce.
    type Value = FakeMap<K, V>;

    // Format a message stating what data this Visitor expects to receive.
    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a map")
    }

    // Deserialize MyMap from an abstract "map" provided by the
    // Deserializer. The MapAccess input is a callback provided by
    // the Deserializer to let us see each entry in the map.
    fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
    where
        M: MapAccess<'de>,
    {
        let mut map = FakeMap::with_capacity(access.size_hint().unwrap_or(0));

        // While there are entries remaining in the input, add them
        // into our map.
        while let Some((key, value)) = access.next_entry()? {
            map.insert(key, value);
        }

        Ok(map)
    }
}

impl<'de, K, V> Deserialize<'de> for FakeMap<K, V>
where
    K: Deserialize<'de> + Eq,
    V: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_map(FakeMapVisitor::new())
    }
}

impl<K, V> Serialize for FakeMap<K, V>
where
    K: Serialize,
    V: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
    where
        S: Serializer,
    {
        let mut serializer = serializer.serialize_map(Some(self.items.len()))?;

        for (key, value) in self.iter() {
            serializer.serialize_entry(key, value)?;
        }

        serializer.end()
    }
}