ron/value/
map.rs

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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use std::{
    cmp::{Eq, Ordering},
    hash::{Hash, Hasher},
    iter::FromIterator,
    ops::{Index, IndexMut},
};

use serde_derive::{Deserialize, Serialize};

use super::Value;

/// A [`Value`] to [`Value`] map.
///
/// This structure either uses a [`BTreeMap`](std::collections::BTreeMap) or the
/// [`IndexMap`](indexmap::IndexMap) internally.
/// The latter can be used by enabling the `indexmap` feature. This can be used
/// to preserve the order of the parsed map.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(transparent)]
pub struct Map(pub(crate) MapInner);

#[cfg(not(feature = "indexmap"))]
type MapInner = std::collections::BTreeMap<Value, Value>;
#[cfg(feature = "indexmap")]
type MapInner = indexmap::IndexMap<Value, Value>;

impl Map {
    /// Creates a new, empty [`Map`].
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the number of elements in the map.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns `true` if `self.len() == 0`, `false` otherwise.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Immutably looks up an element by its `key`.
    #[must_use]
    pub fn get(&self, key: &Value) -> Option<&Value> {
        self.0.get(key)
    }

    /// Mutably looks up an element by its `key`.
    pub fn get_mut(&mut self, key: &Value) -> Option<&mut Value> {
        self.0.get_mut(key)
    }

    /// Inserts a new element, returning the previous element with this `key` if
    /// there was any.
    pub fn insert(&mut self, key: impl Into<Value>, value: impl Into<Value>) -> Option<Value> {
        self.0.insert(key.into(), value.into())
    }

    /// Removes an element by its `key`.
    pub fn remove(&mut self, key: &Value) -> Option<Value> {
        #[cfg(feature = "indexmap")]
        {
            self.0.shift_remove(key)
        }
        #[cfg(not(feature = "indexmap"))]
        {
            self.0.remove(key)
        }
    }

    /// Iterate all key-value pairs.
    #[must_use]
    pub fn iter(&self) -> impl DoubleEndedIterator<Item = (&Value, &Value)> {
        self.0.iter()
    }

    /// Iterate all key-value pairs mutably.
    #[must_use]
    pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = (&Value, &mut Value)> {
        self.0.iter_mut()
    }

    /// Iterate all keys.
    #[must_use]
    pub fn keys(&self) -> impl DoubleEndedIterator<Item = &Value> {
        self.0.keys()
    }

    /// Iterate all values.
    #[must_use]
    pub fn values(&self) -> impl DoubleEndedIterator<Item = &Value> {
        self.0.values()
    }

    /// Iterate all values mutably.
    #[must_use]
    pub fn values_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut Value> {
        self.0.values_mut()
    }

    /// Retains only the elements specified by the `keep` predicate.
    ///
    /// In other words, remove all pairs `(k, v)` for which `keep(&k, &mut v)`
    /// returns `false`.
    ///
    /// The elements are visited in iteration order.
    pub fn retain<F>(&mut self, keep: F)
    where
        F: FnMut(&Value, &mut Value) -> bool,
    {
        self.0.retain(keep);
    }
}

impl Index<&Value> for Map {
    type Output = Value;

    #[allow(clippy::expect_used)]
    fn index(&self, index: &Value) -> &Self::Output {
        self.get(index).expect("no entry found for key")
    }
}

impl IndexMut<&Value> for Map {
    #[allow(clippy::expect_used)]
    fn index_mut(&mut self, index: &Value) -> &mut Self::Output {
        self.get_mut(index).expect("no entry found for key")
    }
}

impl IntoIterator for Map {
    type Item = (Value, Value);

    type IntoIter = <MapInner as IntoIterator>::IntoIter;

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

impl<K: Into<Value>, V: Into<Value>> FromIterator<(K, V)> for Map {
    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
        Map(iter
            .into_iter()
            .map(|(key, value)| (key.into(), value.into()))
            .collect())
    }
}

/// Note: equality is only given if both values and order of values match
impl PartialEq for Map {
    fn eq(&self, other: &Map) -> bool {
        self.cmp(other).is_eq()
    }
}

/// Note: equality is only given if both values and order of values match
impl Eq for Map {}

impl PartialOrd for Map {
    fn partial_cmp(&self, other: &Map) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Map {
    fn cmp(&self, other: &Map) -> Ordering {
        self.iter().cmp(other.iter())
    }
}

impl Hash for Map {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.iter().for_each(|x| x.hash(state));
    }
}

#[cfg(test)]
mod tests {
    use super::{Map, Value};

    #[test]
    fn map_usage() {
        let mut map = Map::new();
        assert_eq!(map.len(), 0);
        assert!(map.is_empty());

        map.insert("a", 42);
        assert_eq!(map.len(), 1);
        assert!(!map.is_empty());

        assert_eq!(map.keys().collect::<Vec<_>>(), vec![&Value::from("a")]);
        assert_eq!(map.values().collect::<Vec<_>>(), vec![&Value::from(42)]);
        assert_eq!(
            map.iter().collect::<Vec<_>>(),
            vec![(&Value::from("a"), &Value::from(42))]
        );

        assert_eq!(map.get(&Value::from("a")), Some(&Value::from(42)));
        assert_eq!(map.get(&Value::from("b")), None);
        assert_eq!(map.get_mut(&Value::from("a")), Some(&mut Value::from(42)));
        assert_eq!(map.get_mut(&Value::from("b")), None);

        map[&Value::from("a")] = Value::from(24);
        assert_eq!(&map[&Value::from("a")], &Value::from(24));

        for (key, value) in map.iter_mut() {
            if key == &Value::from("a") {
                *value = Value::from(42);
            }
        }
        assert_eq!(&map[&Value::from("a")], &Value::from(42));

        map.values_mut().for_each(|value| *value = Value::from(24));
        assert_eq!(&map[&Value::from("a")], &Value::from(24));

        map.insert("b", 42);
        assert_eq!(map.len(), 2);
        assert!(!map.is_empty());
        assert_eq!(map.get(&Value::from("a")), Some(&Value::from(24)));
        assert_eq!(map.get(&Value::from("b")), Some(&Value::from(42)));

        map.retain(|key, value| {
            if key == &Value::from("a") {
                *value = Value::from(42);
                true
            } else {
                false
            }
        });
        assert_eq!(map.len(), 1);
        assert_eq!(map.get(&Value::from("a")), Some(&Value::from(42)));
        assert_eq!(map.get(&Value::from("b")), None);

        assert_eq!(map.remove(&Value::from("b")), None);
        assert_eq!(map.remove(&Value::from("a")), Some(Value::from(42)));
        assert_eq!(map.remove(&Value::from("a")), None);
    }

    #[test]
    fn map_hash() {
        assert_same_hash(&Map::new(), &Map::new());
        assert_same_hash(
            &[("a", 42)].into_iter().collect(),
            &[("a", 42)].into_iter().collect(),
        );
        assert_same_hash(
            &[("b", 24), ("c", 42)].into_iter().collect(),
            &[("b", 24), ("c", 42)].into_iter().collect(),
        );
    }

    fn assert_same_hash(a: &Map, b: &Map) {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        assert_eq!(a, b);
        assert!(a.cmp(b).is_eq());
        assert_eq!(a.partial_cmp(b), Some(std::cmp::Ordering::Equal));

        let mut hasher = DefaultHasher::new();
        a.hash(&mut hasher);
        let h1 = hasher.finish();

        let mut hasher = DefaultHasher::new();
        b.hash(&mut hasher);
        let h2 = hasher.finish();

        assert_eq!(h1, h2);
    }

    #[test]
    #[should_panic(expected = "no entry found for key")]
    fn map_index_panic() {
        let _ = &Map::new()[&Value::Unit];
    }

    #[test]
    #[should_panic(expected = "no entry found for key")]
    fn map_index_mut_panic() {
        let _ = &mut Map::new()[&Value::Unit];
    }
}