1//! A variant of `SortedMap` that preserves insertion order.
23use std::hash::{Hash, Hasher};
45use rustc_index::{Idx, IndexVec};
67use crate::stable_hasher::{HashStable, StableHasher};
89/// An indexed multi-map that preserves insertion order while permitting both *O*(log *n*) lookup of
10/// an item by key and *O*(1) lookup by index.
11///
12/// This data structure is a hybrid of an [`IndexVec`] and a [`SortedMap`]. Like `IndexVec`,
13/// `SortedIndexMultiMap` assigns a typed index to each item while preserving insertion order.
14/// Like `SortedMap`, `SortedIndexMultiMap` has efficient lookup of items by key. However, this
15/// is accomplished by sorting an array of item indices instead of the items themselves.
16///
17/// Unlike `SortedMap`, this data structure can hold multiple equivalent items at once, so the
18/// `get_by_key` method and its variants return an iterator instead of an `Option`. Equivalent
19/// items will be yielded in insertion order.
20///
21/// Unlike a general-purpose map like `BTreeSet` or `HashSet`, `SortedMap` and
22/// `SortedIndexMultiMap` require *O*(*n*) time to insert a single item. This is because we may need
23/// to insert into the middle of the sorted array. Users should avoid mutating this data structure
24/// in-place.
25///
26/// [`SortedMap`]: super::SortedMap
27#[derive(Clone, Debug)]
28pub struct SortedIndexMultiMap<I: Idx, K, V> {
29/// The elements of the map in insertion order.
30items: IndexVec<I, (K, V)>,
3132/// Indices of the items in the set, sorted by the item's key.
33idx_sorted_by_item_key: Vec<I>,
34}
3536impl<I: Idx, K: Ord, V> SortedIndexMultiMap<I, K, V> {
37#[inline]
38pub fn new() -> Self {
39SortedIndexMultiMap { items: IndexVec::new(), idx_sorted_by_item_key: Vec::new() }
40 }
4142#[inline]
43pub fn len(&self) -> usize {
44self.items.len()
45 }
4647#[inline]
48pub fn is_empty(&self) -> bool {
49self.items.is_empty()
50 }
5152/// Returns an iterator over the items in the map in insertion order.
53#[inline]
54pub fn into_iter(self) -> impl DoubleEndedIterator<Item = (K, V)> {
55self.items.into_iter()
56 }
5758/// Returns an iterator over the items in the map in insertion order along with their indices.
59#[inline]
60pub fn into_iter_enumerated(self) -> impl DoubleEndedIterator<Item = (I, (K, V))> {
61self.items.into_iter_enumerated()
62 }
6364/// Returns an iterator over the items in the map in insertion order.
65#[inline]
66pub fn iter(&self) -> impl '_ + DoubleEndedIterator<Item = (&K, &V)> {
67self.items.iter().map(|(k, v)| (k, v))
68 }
6970/// Returns an iterator over the items in the map in insertion order along with their indices.
71#[inline]
72pub fn iter_enumerated(&self) -> impl '_ + DoubleEndedIterator<Item = (I, (&K, &V))> {
73self.items.iter_enumerated().map(|(i, (k, v))| (i, (k, v)))
74 }
7576/// Returns the item in the map with the given index.
77#[inline]
78pub fn get(&self, idx: I) -> Option<&(K, V)> {
79self.items.get(idx)
80 }
8182/// Returns an iterator over the items in the map that are equal to `key`.
83 ///
84 /// If there are multiple items that are equivalent to `key`, they will be yielded in
85 /// insertion order.
86#[inline]
87pub fn get_by_key(&self, key: K) -> impl Iterator<Item = &V> {
88self.get_by_key_enumerated(key).map(|(_, v)| v)
89 }
9091/// Returns an iterator over the items in the map that are equal to `key` along with their
92 /// indices.
93 ///
94 /// If there are multiple items that are equivalent to `key`, they will be yielded in
95 /// insertion order.
96#[inline]
97pub fn get_by_key_enumerated(&self, key: K) -> impl Iterator<Item = (I, &V)> {
98let lower_bound = self.idx_sorted_by_item_key.partition_point(|&i| self.items[i].0 < key);
99self.idx_sorted_by_item_key[lower_bound..].iter().map_while(move |&i| {
100let (k, v) = &self.items[i];
101 (k == &key).then_some((i, v))
102 })
103 }
104105#[inline]
106pub fn contains_key(&self, key: K) -> bool {
107self.get_by_key(key).next().is_some()
108 }
109}
110111impl<I: Idx, K: Eq, V: Eq> Eqfor SortedIndexMultiMap<I, K, V> {}
112impl<I: Idx, K: PartialEq, V: PartialEq> PartialEqfor SortedIndexMultiMap<I, K, V> {
113fn eq(&self, other: &Self) -> bool {
114// No need to compare the sorted index. If the items are the same, the index will be too.
115self.items == other.items
116 }
117}
118119impl<I: Idx, K, V> Hashfor SortedIndexMultiMap<I, K, V>
120where
121K: Hash,
122 V: Hash,
123{
124fn hash<H: Hasher>(&self, hasher: &mut H) {
125self.items.hash(hasher)
126 }
127}
128129impl<I: Idx, K, V, C> HashStable<C> for SortedIndexMultiMap<I, K, V>
130where
131K: HashStable<C>,
132 V: HashStable<C>,
133{
134fn hash_stable(&self, ctx: &mut C, hasher: &mut StableHasher) {
135let SortedIndexMultiMap {
136 items,
137// We can ignore this field because it is not observable from the outside.
138idx_sorted_by_item_key: _,
139 } = self;
140141items.hash_stable(ctx, hasher)
142 }
143}
144145impl<I: Idx, K: Ord, V> FromIterator<(K, V)> for SortedIndexMultiMap<I, K, V> {
146fn from_iter<J>(iter: J) -> Self
147where
148J: IntoIterator<Item = (K, V)>,
149 {
150let items = IndexVec::<I, _>::from_iter(iter);
151let mut idx_sorted_by_item_key: Vec<_> = items.indices().collect();
152153// `sort_by_key` is stable, so insertion order is preserved for duplicate items.
154idx_sorted_by_item_key.sort_by_key(|&idx| &items[idx].0);
155156SortedIndexMultiMap { items, idx_sorted_by_item_key }
157 }
158}
159160impl<I: Idx, K, V> std::ops::Index<I> for SortedIndexMultiMap<I, K, V> {
161type Output = V;
162163fn index(&self, idx: I) -> &Self::Output {
164&self.items[idx].1
165}
166}