Skip to main content

mln_style/
collections.rs

1//! [`VecMap`] and [`VecSet`]: ordered maps and sets kept as sorted vectors,
2//! for small maps.
3//!
4//! They iterate in key order, as [`BTreeMap`](std::collections::BTreeMap)
5//! and [`BTreeSet`](std::collections::BTreeSet) do, and have the part of
6//! their API mln-rs uses. A `BTreeMap` is a lot of code for each key and
7//! value type it is used with; these are a binary search over a slice and a
8//! `Vec` insert or remove. The keys are a vector of their own, so the search
9//! is one function for each key type, whatever the values. Insert and remove
10//! move the entries after the position, so a map that grows large by inserts
11//! in no particular order is still better off as a `BTreeMap`. An insert past
12//! the last key is a push.
13
14use std::borrow::Borrow;
15use std::fmt;
16use std::ops::Index;
17
18/// The position of `key` in the sorted `keys`, or where it would go.
19fn search<K: Borrow<Q>, Q: Ord + ?Sized>(keys: &[K], key: &Q) -> Result<usize, usize> {
20    // An insert past the last key is the common case of building a map in
21    // order, so check that first.
22    match keys.last() {
23        None => return Err(0),
24        Some(last) if last.borrow() < key => return Err(keys.len()),
25        _ => {}
26    }
27    keys.binary_search_by(|k| k.borrow().cmp(key))
28}
29
30/// An ordered map kept as sorted vectors of keys and of values (module docs).
31#[derive(Clone, PartialEq, Eq, Hash)]
32pub struct VecMap<K, V> {
33    keys: Vec<K>,
34    values: Vec<V>,
35}
36
37/// [`VecMap::iter`].
38pub(crate) type Iter<'a, K, V> = std::iter::Zip<std::slice::Iter<'a, K>, std::slice::Iter<'a, V>>;
39/// [`VecMap::iter_mut`].
40pub(crate) type IterMut<'a, K, V> = std::iter::Zip<std::slice::Iter<'a, K>, std::slice::IterMut<'a, V>>;
41/// [`VecMap::into_iter`].
42pub type IntoIter<K, V> = std::iter::Zip<std::vec::IntoIter<K>, std::vec::IntoIter<V>>;
43
44impl<K, V> Default for VecMap<K, V> {
45    fn default() -> Self {
46        Self::new()
47    }
48}
49
50impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for VecMap<K, V> {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        f.debug_map().entries(self.iter()).finish()
53    }
54}
55
56impl<K, V> VecMap<K, V> {
57    #[must_use]
58    pub const fn new() -> Self {
59        VecMap { keys: Vec::new(), values: Vec::new() }
60    }
61
62    #[must_use]
63    pub fn len(&self) -> usize {
64        self.keys.len()
65    }
66
67    #[must_use]
68    pub fn is_empty(&self) -> bool {
69        self.keys.is_empty()
70    }
71
72    pub fn clear(&mut self) {
73        self.keys.clear();
74        self.values.clear();
75    }
76
77    pub fn iter(&self) -> Iter<'_, K, V> {
78        self.keys.iter().zip(self.values.iter())
79    }
80
81    pub(crate) fn iter_mut(&mut self) -> IterMut<'_, K, V> {
82        self.keys.iter().zip(self.values.iter_mut())
83    }
84
85    pub fn keys(&self) -> std::slice::Iter<'_, K> {
86        self.keys.iter()
87    }
88
89    pub fn values(&self) -> std::slice::Iter<'_, V> {
90        self.values.iter()
91    }
92
93    /// The entry at `index` in key order.
94    #[must_use]
95    pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
96        Some((self.keys.get(index)?, self.values.get(index)?))
97    }
98
99    /// The entry at `index` in key order.
100    pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
101        Some((self.keys.get(index)?, self.values.get_mut(index)?))
102    }
103
104    pub fn values_mut(&mut self) -> std::slice::IterMut<'_, V> {
105        self.values.iter_mut()
106    }
107
108    /// Keeps the entries for which `f` returns true, visiting them in key
109    /// order.
110    pub fn retain(&mut self, mut f: impl FnMut(&K, &mut V) -> bool) {
111        let mut kept = 0;
112        for i in 0..self.keys.len() {
113            if f(&self.keys[i], &mut self.values[i]) {
114                self.keys.swap(kept, i);
115                self.values.swap(kept, i);
116                kept += 1;
117            }
118        }
119        self.keys.truncate(kept);
120        self.values.truncate(kept);
121    }
122}
123
124impl<K: Ord, V> VecMap<K, V> {
125    fn search<Q: Ord + ?Sized>(&self, key: &Q) -> Result<usize, usize>
126    where
127        K: Borrow<Q>,
128    {
129        search(&self.keys, key)
130    }
131
132    pub fn get<Q: Ord + ?Sized>(&self, key: &Q) -> Option<&V>
133    where
134        K: Borrow<Q>,
135    {
136        self.search(key).ok().map(|i| &self.values[i])
137    }
138
139    pub fn get_mut<Q: Ord + ?Sized>(&mut self, key: &Q) -> Option<&mut V>
140    where
141        K: Borrow<Q>,
142    {
143        self.search(key).ok().map(|i| &mut self.values[i])
144    }
145
146    /// The position of `key`'s entry in key order, which stays its position
147    /// until an entry is inserted or removed.
148    #[must_use]
149    pub fn index_of<Q: Ord + ?Sized>(&self, key: &Q) -> Option<usize>
150    where
151        K: Borrow<Q>,
152    {
153        self.search(key).ok()
154    }
155
156    pub fn contains_key<Q: Ord + ?Sized>(&self, key: &Q) -> bool
157    where
158        K: Borrow<Q>,
159    {
160        self.search(key).is_ok()
161    }
162
163    /// Like `BTreeMap::insert`, keeps the key already in the map when there
164    /// is one.
165    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
166        match self.search(&key) {
167            Ok(i) => Some(std::mem::replace(&mut self.values[i], value)),
168            Err(i) => {
169                self.insert_at(i, key, value);
170                None
171            }
172        }
173    }
174
175    fn insert_at(&mut self, i: usize, key: K, value: V) {
176        if i == self.keys.len() {
177            self.keys.push(key);
178            self.values.push(value);
179        } else {
180            self.keys.insert(i, key);
181            self.values.insert(i, value);
182        }
183    }
184
185    pub fn remove<Q: Ord + ?Sized>(&mut self, key: &Q) -> Option<V>
186    where
187        K: Borrow<Q>,
188    {
189        self.remove_entry(key).map(|(_, v)| v)
190    }
191
192    pub(crate) fn remove_entry<Q: Ord + ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
193    where
194        K: Borrow<Q>,
195    {
196        let i = self.search(key).ok()?;
197        Some((self.keys.remove(i), self.values.remove(i)))
198    }
199
200    /// The value of `key`, which is `value()`, under `key.to_owned()`, where
201    /// the map has none. Unlike [`entry`](Self::entry), it makes an owned
202    /// key only for an entry it inserts.
203    pub fn get_or_insert_with<Q>(&mut self, key: &Q, value: impl FnOnce() -> V) -> &mut V
204    where
205        K: Borrow<Q>,
206        Q: Ord + ToOwned<Owned = K> + ?Sized,
207    {
208        let i = match self.search(key) {
209            Ok(i) => i,
210            Err(i) => {
211                self.insert_at(i, key.to_owned(), value());
212                i
213            }
214        };
215        &mut self.values[i]
216    }
217
218    pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
219        match self.search(&key) {
220            Ok(index) => Entry::Occupied(OccupiedEntry { map: self, index }),
221            Err(index) => Entry::Vacant(VacantEntry { map: self, index, key }),
222        }
223    }
224}
225
226impl<K: Ord, V> Extend<(K, V)> for VecMap<K, V> {
227    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
228        let iter = iter.into_iter();
229        let (additional, _) = iter.size_hint();
230        self.keys.reserve(additional);
231        self.values.reserve(additional);
232        for (k, v) in iter {
233            self.insert(k, v);
234        }
235    }
236}
237
238impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for VecMap<K, V> {
239    fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
240        self.extend(iter.into_iter().map(|(k, v)| (*k, *v)));
241    }
242}
243
244/// [`VecMap::entry`].
245pub enum Entry<'a, K, V> {
246    Occupied(OccupiedEntry<'a, K, V>),
247    Vacant(VacantEntry<'a, K, V>),
248}
249
250/// An [`Entry`] whose key is in the map.
251pub struct OccupiedEntry<'a, K, V> {
252    map: &'a mut VecMap<K, V>,
253    index: usize,
254}
255
256/// An [`Entry`] whose key is not in the map.
257pub struct VacantEntry<'a, K, V> {
258    map: &'a mut VecMap<K, V>,
259    index: usize,
260    key: K,
261}
262
263impl<'a, K: Ord, V> Entry<'a, K, V> {
264    pub fn or_insert_with(self, f: impl FnOnce() -> V) -> &'a mut V {
265        match self {
266            Entry::Occupied(e) => e.into_mut(),
267            Entry::Vacant(e) => e.insert(f()),
268        }
269    }
270
271    pub fn or_insert(self, value: V) -> &'a mut V {
272        self.or_insert_with(|| value)
273    }
274
275    pub fn or_default(self) -> &'a mut V
276    where
277        V: Default,
278    {
279        self.or_insert_with(V::default)
280    }
281}
282
283impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
284    pub(crate) fn get_mut(&mut self) -> &mut V {
285        &mut self.map.values[self.index]
286    }
287
288    #[must_use]
289    pub(crate) fn into_mut(self) -> &'a mut V {
290        &mut self.map.values[self.index]
291    }
292
293    pub fn insert(&mut self, value: V) -> V {
294        std::mem::replace(self.get_mut(), value)
295    }
296}
297
298impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
299    pub fn insert(self, value: V) -> &'a mut V {
300        self.map.insert_at(self.index, self.key, value);
301        &mut self.map.values[self.index]
302    }
303}
304
305impl<K: Ord, V> FromIterator<(K, V)> for VecMap<K, V> {
306    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
307        let mut map = VecMap::new();
308        map.extend(iter);
309        map
310    }
311}
312
313impl<K: Ord, V, const N: usize> From<[(K, V); N]> for VecMap<K, V> {
314    fn from(entries: [(K, V); N]) -> Self {
315        entries.into_iter().collect()
316    }
317}
318
319impl<K, V> IntoIterator for VecMap<K, V> {
320    type Item = (K, V);
321    type IntoIter = IntoIter<K, V>;
322
323    fn into_iter(self) -> Self::IntoIter {
324        self.keys.into_iter().zip(self.values)
325    }
326}
327
328impl<'a, K, V> IntoIterator for &'a VecMap<K, V> {
329    type Item = (&'a K, &'a V);
330    type IntoIter = Iter<'a, K, V>;
331
332    fn into_iter(self) -> Self::IntoIter {
333        self.iter()
334    }
335}
336
337impl<'a, K, V> IntoIterator for &'a mut VecMap<K, V> {
338    type Item = (&'a K, &'a mut V);
339    type IntoIter = IterMut<'a, K, V>;
340
341    fn into_iter(self) -> Self::IntoIter {
342        self.iter_mut()
343    }
344}
345
346/// Panics when `key` is not in the map, as `BTreeMap`'s `Index` does.
347impl<K: Ord + Borrow<Q>, Q: Ord + ?Sized, V> Index<&Q> for VecMap<K, V> {
348    type Output = V;
349
350    /// Panics on a missing key, as `BTreeMap`'s `Index` does (with its
351    /// message): the panic site those lookups had inside std, now here.
352    #[expect(clippy::expect_used, reason = "Index::index's contract is to panic when the key is missing")]
353    fn index(&self, key: &Q) -> &V {
354        self.get(key).expect("no entry found for key")
355    }
356}
357
358impl<K: mln_wire::Wire + Ord, V: mln_wire::Wire> mln_wire::Wire for VecMap<K, V> {
359    fn write(&self, w: &mut mln_wire::Writer<'_>) {
360        self.len().write(w);
361        for (k, v) in self {
362            k.write(w);
363            v.write(w);
364        }
365    }
366
367    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
368        let len = r.length()?;
369        let mut map = VecMap::new();
370        for _ in 0..len {
371            let k = K::read(r)?;
372            map.insert(k, V::read(r)?);
373        }
374        Some(map)
375    }
376}
377
378/// An ordered set kept as a sorted vector (module docs).
379#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
380pub struct VecSet<T> {
381    items: Vec<T>,
382}
383
384impl<T> Default for VecSet<T> {
385    fn default() -> Self {
386        Self::new()
387    }
388}
389
390impl<T: fmt::Debug> fmt::Debug for VecSet<T> {
391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392        f.debug_set().entries(self.iter()).finish()
393    }
394}
395
396impl<T> VecSet<T> {
397    #[must_use]
398    pub const fn new() -> Self {
399        VecSet { items: Vec::new() }
400    }
401
402    #[must_use]
403    pub fn len(&self) -> usize {
404        self.items.len()
405    }
406
407    #[must_use]
408    pub fn is_empty(&self) -> bool {
409        self.items.is_empty()
410    }
411
412    pub fn clear(&mut self) {
413        self.items.clear();
414    }
415
416    pub fn iter(&self) -> std::slice::Iter<'_, T> {
417        self.items.iter()
418    }
419}
420
421impl<T: Ord> VecSet<T> {
422    pub fn contains<Q: Ord + ?Sized>(&self, value: &Q) -> bool
423    where
424        T: Borrow<Q>,
425    {
426        search(&self.items, value).is_ok()
427    }
428
429    /// Like `BTreeSet::insert`, keeps the item already in the set when there
430    /// is one, and returns whether `value` was new.
431    pub fn insert(&mut self, value: T) -> bool {
432        match search(&self.items, &value) {
433            Ok(_) => false,
434            Err(i) if i == self.items.len() => {
435                self.items.push(value);
436                true
437            }
438            Err(i) => {
439                self.items.insert(i, value);
440                true
441            }
442        }
443    }
444
445    pub fn remove<Q: Ord + ?Sized>(&mut self, value: &Q) -> bool
446    where
447        T: Borrow<Q>,
448    {
449        self.take(value).is_some()
450    }
451
452    pub(crate) fn take<Q: Ord + ?Sized>(&mut self, value: &Q) -> Option<T>
453    where
454        T: Borrow<Q>,
455    {
456        let i = search(&self.items, value).ok()?;
457        Some(self.items.remove(i))
458    }
459}
460
461impl<T: Ord> Extend<T> for VecSet<T> {
462    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
463        for item in iter {
464            self.insert(item);
465        }
466    }
467}
468
469impl<'a, T: Ord + Copy + 'a> Extend<&'a T> for VecSet<T> {
470    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
471        self.extend(iter.into_iter().copied());
472    }
473}
474
475impl<T: Ord> FromIterator<T> for VecSet<T> {
476    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
477        let mut set = VecSet::new();
478        set.extend(iter);
479        set
480    }
481}
482
483impl<T: Ord, const N: usize> From<[T; N]> for VecSet<T> {
484    fn from(items: [T; N]) -> Self {
485        items.into_iter().collect()
486    }
487}
488
489impl<T> IntoIterator for VecSet<T> {
490    type Item = T;
491    type IntoIter = std::vec::IntoIter<T>;
492
493    fn into_iter(self) -> Self::IntoIter {
494        self.items.into_iter()
495    }
496}
497
498impl<'a, T> IntoIterator for &'a VecSet<T> {
499    type Item = &'a T;
500    type IntoIter = std::slice::Iter<'a, T>;
501
502    fn into_iter(self) -> Self::IntoIter {
503        self.iter()
504    }
505}
506
507impl<T: mln_wire::Wire + Ord> mln_wire::Wire for VecSet<T> {
508    fn write(&self, w: &mut mln_wire::Writer<'_>) {
509        mln_wire::write_seq(w, &self.items);
510    }
511
512    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
513        Some(mln_wire::read_seq::<T>(r)?.into_iter().collect())
514    }
515}
516
517#[cfg(test)]
518mod tests {
519    use std::collections::{BTreeMap, BTreeSet};
520
521    use super::*;
522
523    // A small deterministic generator, so the tests need no dependency.
524    fn keys(n: usize, seed: u64) -> Vec<u32> {
525        let mut x = seed;
526        (0..n)
527            .map(|_| {
528                x ^= x << 13;
529                x ^= x >> 7;
530                x ^= x << 17;
531                (x % 64) as u32
532            })
533            .collect()
534    }
535
536    #[test]
537    fn map_matches_btree_map() {
538        for seed in 1..20 {
539            let mut vec_map = VecMap::new();
540            let mut btree_map = BTreeMap::new();
541            for (i, k) in keys(200, seed).into_iter().enumerate() {
542                match i % 5 {
543                    0..=2 => assert_eq!(vec_map.insert(k, i), btree_map.insert(k, i)),
544                    3 => assert_eq!(vec_map.remove(&k), btree_map.remove(&k)),
545                    _ => {
546                        *vec_map.entry(k).or_insert(0) += i;
547                        *btree_map.entry(k).or_insert(0) += i;
548                    }
549                }
550                assert_eq!(vec_map.get(&k), btree_map.get(&k));
551            }
552            assert!(vec_map.iter().eq(btree_map.iter()));
553            vec_map.retain(|k, v| !(k + *v as u32).is_multiple_of(3));
554            btree_map.retain(|k, v| !(k + *v as u32).is_multiple_of(3));
555            vec_map.extend(keys(30, seed + 100).into_iter().map(|k| (k, 7)));
556            btree_map.extend(keys(30, seed + 100).into_iter().map(|k| (k, 7)));
557            assert!(vec_map.into_iter().eq(btree_map));
558        }
559    }
560
561    #[test]
562    fn set_matches_btree_set() {
563        for seed in 1..20 {
564            let mut vec_set = VecSet::new();
565            let mut btree_set = BTreeSet::new();
566            for (i, k) in keys(200, seed).into_iter().enumerate() {
567                if i % 3 == 2 {
568                    assert_eq!(vec_set.remove(&k), btree_set.remove(&k));
569                } else {
570                    assert_eq!(vec_set.insert(k), btree_set.insert(k));
571                }
572                assert_eq!(vec_set.contains(&k), btree_set.contains(&k));
573            }
574            assert!(vec_set.into_iter().eq(btree_set));
575        }
576    }
577
578    #[test]
579    fn get_or_insert_with_inserts_only_a_missing_key() {
580        let mut map: VecMap<String, u32> = [("b".to_owned(), 2)].into();
581        *map.get_or_insert_with("b", || unreachable!()) += 1;
582        *map.get_or_insert_with("a", || 10) += 1;
583        assert!(map.iter().eq([(&"a".to_owned(), &11), (&"b".to_owned(), &3)]));
584    }
585
586    #[test]
587    fn index_finds_the_value() {
588        let map: VecMap<String, u32> = [("a".to_owned(), 1), ("b".to_owned(), 2)].into();
589        assert_eq!(map["a"], 1);
590        assert_eq!(map["b"], 2);
591    }
592
593    #[test]
594    #[should_panic(expected = "no entry found for key")]
595    fn index_panics_on_a_missing_key() {
596        let map: VecMap<String, u32> = [("a".to_owned(), 1)].into();
597        let _ = map["c"];
598    }
599
600    #[test]
601    fn insert_keeps_the_first_key() {
602        // Keys that compare equal but differ: BTreeMap keeps the first.
603        #[derive(Debug)]
604        struct K(u32, &'static str);
605        impl PartialEq for K {
606            fn eq(&self, other: &Self) -> bool {
607                self.0 == other.0
608            }
609        }
610        impl Eq for K {}
611        impl PartialOrd for K {
612            fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
613                Some(self.cmp(other))
614            }
615        }
616        impl Ord for K {
617            fn cmp(&self, other: &Self) -> std::cmp::Ordering {
618                self.0.cmp(&other.0)
619            }
620        }
621        let mut map = VecMap::new();
622        map.insert(K(1, "first"), 1);
623        assert_eq!(map.insert(K(1, "second"), 2), Some(1));
624        assert_eq!(map.iter().next().map(|(k, v)| (k.1, *v)), Some(("first", 2)));
625        let mut set = VecSet::new();
626        assert!(set.insert(K(1, "first")));
627        assert!(!set.insert(K(1, "second")));
628        assert_eq!(set.iter().next().map(|k| k.1), Some("first"));
629    }
630}