1//! A variant of `SortedMap` that preserves insertion order.
23use std::hash::{Hash, Hasher};
45use rustc_index::{Idx, IndexVec};
6use rustc_macros::HashStable_NoContext;
78/// An indexed multi-map that preserves insertion order while permitting both *O*(log *n*) lookup of
9/// an item by key and *O*(1) lookup by index.
10///
11/// This data structure is a hybrid of an [`IndexVec`] and a [`SortedMap`]. Like `IndexVec`,
12/// `SortedIndexMultiMap` assigns a typed index to each item while preserving insertion order.
13/// Like `SortedMap`, `SortedIndexMultiMap` has efficient lookup of items by key. However, this
14/// is accomplished by sorting an array of item indices instead of the items themselves.
15///
16/// Unlike `SortedMap`, this data structure can hold multiple equivalent items at once, so the
17/// `get_by_key` method and its variants return an iterator instead of an `Option`. Equivalent
18/// items will be yielded in insertion order.
19///
20/// Unlike a general-purpose map like `BTreeSet` or `HashSet`, `SortedMap` and
21/// `SortedIndexMultiMap` require *O*(*n*) time to insert a single item. This is because we may need
22/// to insert into the middle of the sorted array. Users should avoid mutating this data structure
23/// in-place.
24///
25/// [`SortedMap`]: super::SortedMap
26#[derive(#[automatically_derived]
impl<I: ::core::clone::Clone + Idx, K: ::core::clone::Clone,
V: ::core::clone::Clone> ::core::clone::Clone for
SortedIndexMultiMap<I, K, V> {
#[inline]
fn clone(&self) -> SortedIndexMultiMap<I, K, V> {
SortedIndexMultiMap {
items: ::core::clone::Clone::clone(&self.items),
idx_sorted_by_item_key: ::core::clone::Clone::clone(&self.idx_sorted_by_item_key),
}
}
}Clone, #[automatically_derived]
impl<I: ::core::fmt::Debug + Idx, K: ::core::fmt::Debug,
V: ::core::fmt::Debug> ::core::fmt::Debug for SortedIndexMultiMap<I, K, V>
{
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"SortedIndexMultiMap", "items", &self.items,
"idx_sorted_by_item_key", &&self.idx_sorted_by_item_key)
}
}Debug, const _: () =
{
impl<I: Idx, K, V, __CTX>
::rustc_data_structures::stable_hasher::HashStable<__CTX> for
SortedIndexMultiMap<I, K, V> where
IndexVec<I,
(K,
V)>: ::rustc_data_structures::stable_hasher::HashStable<__CTX>,
Vec<I>: ::rustc_data_structures::stable_hasher::HashStable<__CTX>
{
#[inline]
fn hash_stable(&self, __hcx: &mut __CTX,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
match *self {
SortedIndexMultiMap {
items: ref __binding_0,
idx_sorted_by_item_key: ref __binding_1 } => {
{ __binding_0.hash_stable(__hcx, __hasher); }
{}
}
}
}
}
};HashStable_NoContext)]
27pub struct SortedIndexMultiMap<I: Idx, K, V> {
28/// The elements of the map in insertion order.
29items: IndexVec<I, (K, V)>,
3031// We can ignore this field because it is not observable from the outside.
32#[stable_hasher(ignore)]
33/// Indices of the items in the set, sorted by the item's key.
34idx_sorted_by_item_key: Vec<I>,
35}
3637impl<I: Idx, K: Ord, V> SortedIndexMultiMap<I, K, V> {
38#[inline]
39pub fn new() -> Self {
40SortedIndexMultiMap { items: IndexVec::new(), idx_sorted_by_item_key: Vec::new() }
41 }
4243#[inline]
44pub fn len(&self) -> usize {
45self.items.len()
46 }
4748#[inline]
49pub fn is_empty(&self) -> bool {
50self.items.is_empty()
51 }
5253/// Returns an iterator over the items in the map in insertion order.
54#[inline]
55pub fn into_iter(self) -> impl DoubleEndedIterator<Item = (K, V)> {
56self.items.into_iter()
57 }
5859/// Returns an iterator over the items in the map in insertion order along with their indices.
60#[inline]
61pub fn into_iter_enumerated(self) -> impl DoubleEndedIterator<Item = (I, (K, V))> {
62self.items.into_iter_enumerated()
63 }
6465/// Returns an iterator over the items in the map in insertion order.
66#[inline]
67pub fn iter(&self) -> impl '_ + DoubleEndedIterator<Item = (&K, &V)> {
68self.items.iter().map(|(k, v)| (k, v))
69 }
7071/// Returns an iterator over the items in the map in insertion order along with their indices.
72#[inline]
73pub fn iter_enumerated(&self) -> impl '_ + DoubleEndedIterator<Item = (I, (&K, &V))> {
74self.items.iter_enumerated().map(|(i, (k, v))| (i, (k, v)))
75 }
7677/// Returns the item in the map with the given index.
78#[inline]
79pub fn get(&self, idx: I) -> Option<&(K, V)> {
80self.items.get(idx)
81 }
8283/// Returns an iterator over the items in the map that are equal to `key`.
84 ///
85 /// If there are multiple items that are equivalent to `key`, they will be yielded in
86 /// insertion order.
87#[inline]
88pub fn get_by_key(&self, key: K) -> impl Iterator<Item = &V> {
89self.get_by_key_enumerated(key).map(|(_, v)| v)
90 }
9192/// Returns an iterator over the items in the map that are equal to `key` along with their
93 /// indices.
94 ///
95 /// If there are multiple items that are equivalent to `key`, they will be yielded in
96 /// insertion order.
97#[inline]
98pub fn get_by_key_enumerated(&self, key: K) -> impl Iterator<Item = (I, &V)> {
99let lower_bound = self.idx_sorted_by_item_key.partition_point(|&i| self.items[i].0 < key);
100self.idx_sorted_by_item_key[lower_bound..].iter().map_while(move |&i| {
101let (k, v) = &self.items[i];
102 (k == &key).then_some((i, v))
103 })
104 }
105106#[inline]
107pub fn contains_key(&self, key: K) -> bool {
108self.get_by_key(key).next().is_some()
109 }
110}
111112impl<I: Idx, K: Eq, V: Eq> Eqfor SortedIndexMultiMap<I, K, V> {}
113impl<I: Idx, K: PartialEq, V: PartialEq> PartialEqfor SortedIndexMultiMap<I, K, V> {
114fn eq(&self, other: &Self) -> bool {
115// No need to compare the sorted index. If the items are the same, the index will be too.
116self.items == other.items
117 }
118}
119120impl<I: Idx, K, V> Hashfor SortedIndexMultiMap<I, K, V>
121where
122K: Hash,
123 V: Hash,
124{
125fn hash<H: Hasher>(&self, hasher: &mut H) {
126self.items.hash(hasher)
127 }
128}
129130impl<I: Idx, K: Ord, V> FromIterator<(K, V)> for SortedIndexMultiMap<I, K, V> {
131fn from_iter<J>(iter: J) -> Self
132where
133J: IntoIterator<Item = (K, V)>,
134 {
135let items = IndexVec::<I, _>::from_iter(iter);
136let mut idx_sorted_by_item_key: Vec<_> = items.indices().collect();
137138// `sort_by_key` is stable, so insertion order is preserved for duplicate items.
139idx_sorted_by_item_key.sort_by_key(|&idx| &items[idx].0);
140141SortedIndexMultiMap { items, idx_sorted_by_item_key }
142 }
143}
144145impl<I: Idx, K, V> std::ops::Index<I> for SortedIndexMultiMap<I, K, V> {
146type Output = V;
147148fn index(&self, idx: I) -> &Self::Output {
149&self.items[idx].1
150}
151}