vecmap/map/
impls.rs

1use super::VecMap;
2use alloc::vec::Vec;
3use core::borrow::Borrow;
4use core::ops::{Index, IndexMut};
5
6impl<K, V> Default for VecMap<K, V> {
7    fn default() -> Self {
8        VecMap::new()
9    }
10}
11
12impl<K, V, Q> Index<&Q> for VecMap<K, V>
13where
14    K: Borrow<Q>,
15    Q: Eq + ?Sized,
16{
17    type Output = V;
18
19    fn index(&self, key: &Q) -> &V {
20        self.get(key).expect("VecMap: key not found")
21    }
22}
23
24impl<K, V, Q> IndexMut<&Q> for VecMap<K, V>
25where
26    K: Borrow<Q>,
27    Q: Eq + ?Sized,
28{
29    fn index_mut(&mut self, key: &Q) -> &mut V {
30        self.get_mut(key).expect("VecMap: key not found")
31    }
32}
33
34impl<K, V> Index<usize> for VecMap<K, V> {
35    type Output = V;
36
37    fn index(&self, index: usize) -> &V {
38        self.get_index(index)
39            .expect("VecMap: index out of bounds")
40            .1
41    }
42}
43
44impl<K, V> IndexMut<usize> for VecMap<K, V> {
45    fn index_mut(&mut self, index: usize) -> &mut V {
46        self.get_index_mut(index)
47            .expect("VecMap: index out of bounds")
48            .1
49    }
50}
51
52impl<K, V> Extend<(K, V)> for VecMap<K, V>
53where
54    K: Eq,
55{
56    fn extend<I>(&mut self, iterable: I)
57    where
58        I: IntoIterator<Item = (K, V)>,
59    {
60        let iter = iterable.into_iter();
61        let reserve = if self.is_empty() {
62            iter.size_hint().0
63        } else {
64            // Round up but make sure we don’t overflow when size_hint ==
65            // usize::MAX.
66            let size_hint = iter.size_hint().0;
67            size_hint / 2 + size_hint % 2
68        };
69        self.reserve(reserve);
70        iter.for_each(move |(k, v)| {
71            self.insert(k, v);
72        });
73    }
74}
75
76impl<'a, K: Clone + Eq, V: Clone> Extend<(&'a K, &'a V)> for VecMap<K, V> {
77    fn extend<I>(&mut self, iterable: I)
78    where
79        I: IntoIterator<Item = (&'a K, &'a V)>,
80    {
81        self.extend(
82            iterable
83                .into_iter()
84                .map(|(key, value)| (key.clone(), value.clone())),
85        );
86    }
87}
88
89impl<'a, K: Clone + Eq, V: Clone> Extend<&'a (K, V)> for VecMap<K, V> {
90    fn extend<I>(&mut self, iterable: I)
91    where
92        I: IntoIterator<Item = &'a (K, V)>,
93    {
94        self.extend(
95            iterable
96                .into_iter()
97                .map(|(key, value)| (key.clone(), value.clone())),
98        );
99    }
100}
101
102impl<Item, K, V> FromIterator<Item> for VecMap<K, V>
103where
104    Self: Extend<Item>,
105{
106    fn from_iter<I: IntoIterator<Item = Item>>(iter: I) -> Self {
107        let mut map = VecMap::new();
108        map.extend(iter);
109        map
110    }
111}
112
113impl<K, V> From<Vec<(K, V)>> for VecMap<K, V>
114where
115    K: Eq,
116{
117    /// Constructs map from a vector of `(key → value)` pairs.
118    ///
119    /// **Note**: This conversion has a quadratic complexity because the
120    /// conversion preserves order of elements while at the same time having to
121    /// make sure no duplicate keys exist. To avoid it, sort and deduplicate
122    /// the vector and use [`VecMap::from_vec_unchecked`] instead.
123    fn from(mut vec: Vec<(K, V)>) -> Self {
124        crate::dedup(&mut vec, |rhs, lhs| rhs.0 == lhs.0);
125        // SAFETY: We've just deduplicated the elements.
126        unsafe { Self::from_vec_unchecked(vec) }
127    }
128}
129
130impl<K, V> From<&[(K, V)]> for VecMap<K, V>
131where
132    K: Clone + Eq,
133    V: Clone,
134{
135    fn from(slice: &[(K, V)]) -> Self {
136        VecMap::from_iter(slice)
137    }
138}
139
140impl<K, V> From<&mut [(K, V)]> for VecMap<K, V>
141where
142    K: Clone + Eq,
143    V: Clone,
144{
145    fn from(slice: &mut [(K, V)]) -> Self {
146        // False-positive, we're re-slicing on purpose to go from `&mut [(K, V)]` to `&[(K, V)]`.
147        #[allow(clippy::redundant_slicing)]
148        VecMap::from_iter(&slice[..])
149    }
150}
151
152impl<K, V, const N: usize> From<[(K, V); N]> for VecMap<K, V>
153where
154    K: Eq,
155{
156    fn from(arr: [(K, V); N]) -> Self {
157        VecMap::from_iter(arr)
158    }
159}
160
161impl<K, V> PartialEq for VecMap<K, V>
162where
163    K: Eq,
164    V: PartialEq,
165{
166    fn eq(&self, other: &Self) -> bool {
167        if self.len() != other.len() {
168            return false;
169        }
170
171        self.iter()
172            .all(|(key, value)| other.get(key).is_some_and(|v| *value == *v))
173    }
174}
175
176impl<K, V> Eq for VecMap<K, V>
177where
178    K: Eq,
179    V: Eq,
180{
181}
182
183#[cfg(test)]
184mod test {
185    use super::*;
186
187    #[test]
188    fn eq() {
189        assert_ne!(VecMap::from([("a", 1)]), VecMap::from([]));
190        assert_ne!(VecMap::from([("a", 1)]), VecMap::from([("b", 2)]));
191        assert_eq!(VecMap::from([("a", 1)]), VecMap::from([("a", 1)]));
192        assert_ne!(VecMap::from([("a", 1)]), VecMap::from([("a", 1), ("b", 2)]));
193        assert_eq!(
194            VecMap::from([("a", 1), ("b", 2)]),
195            VecMap::from([("a", 1), ("b", 2)])
196        );
197        assert_eq!(
198            VecMap::from([("a", 1), ("b", 2)]),
199            VecMap::from([("b", 2), ("a", 1)])
200        );
201    }
202}