Skip to main content

rustc_data_structures/sorted_map/
index_map.rs

1//! A variant of `SortedMap` that preserves insertion order.
2
3use std::hash::{Hash, Hasher};
4
5use rustc_index::{Idx, IndexVec};
6use rustc_macros::HashStable_NoContext;
7
8/// 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.
29    items: IndexVec<I, (K, V)>,
30
31    // 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.
34    idx_sorted_by_item_key: Vec<I>,
35}
36
37impl<I: Idx, K: Ord, V> SortedIndexMultiMap<I, K, V> {
38    #[inline]
39    pub fn new() -> Self {
40        SortedIndexMultiMap { items: IndexVec::new(), idx_sorted_by_item_key: Vec::new() }
41    }
42
43    #[inline]
44    pub fn len(&self) -> usize {
45        self.items.len()
46    }
47
48    #[inline]
49    pub fn is_empty(&self) -> bool {
50        self.items.is_empty()
51    }
52
53    /// Returns an iterator over the items in the map in insertion order.
54    #[inline]
55    pub fn into_iter(self) -> impl DoubleEndedIterator<Item = (K, V)> {
56        self.items.into_iter()
57    }
58
59    /// Returns an iterator over the items in the map in insertion order along with their indices.
60    #[inline]
61    pub fn into_iter_enumerated(self) -> impl DoubleEndedIterator<Item = (I, (K, V))> {
62        self.items.into_iter_enumerated()
63    }
64
65    /// Returns an iterator over the items in the map in insertion order.
66    #[inline]
67    pub fn iter(&self) -> impl '_ + DoubleEndedIterator<Item = (&K, &V)> {
68        self.items.iter().map(|(k, v)| (k, v))
69    }
70
71    /// Returns an iterator over the items in the map in insertion order along with their indices.
72    #[inline]
73    pub fn iter_enumerated(&self) -> impl '_ + DoubleEndedIterator<Item = (I, (&K, &V))> {
74        self.items.iter_enumerated().map(|(i, (k, v))| (i, (k, v)))
75    }
76
77    /// Returns the item in the map with the given index.
78    #[inline]
79    pub fn get(&self, idx: I) -> Option<&(K, V)> {
80        self.items.get(idx)
81    }
82
83    /// 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]
88    pub fn get_by_key(&self, key: K) -> impl Iterator<Item = &V> {
89        self.get_by_key_enumerated(key).map(|(_, v)| v)
90    }
91
92    /// 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]
98    pub fn get_by_key_enumerated(&self, key: K) -> impl Iterator<Item = (I, &V)> {
99        let lower_bound = self.idx_sorted_by_item_key.partition_point(|&i| self.items[i].0 < key);
100        self.idx_sorted_by_item_key[lower_bound..].iter().map_while(move |&i| {
101            let (k, v) = &self.items[i];
102            (k == &key).then_some((i, v))
103        })
104    }
105
106    #[inline]
107    pub fn contains_key(&self, key: K) -> bool {
108        self.get_by_key(key).next().is_some()
109    }
110}
111
112impl<I: Idx, K: Eq, V: Eq> Eq for SortedIndexMultiMap<I, K, V> {}
113impl<I: Idx, K: PartialEq, V: PartialEq> PartialEq for SortedIndexMultiMap<I, K, V> {
114    fn eq(&self, other: &Self) -> bool {
115        // No need to compare the sorted index. If the items are the same, the index will be too.
116        self.items == other.items
117    }
118}
119
120impl<I: Idx, K, V> Hash for SortedIndexMultiMap<I, K, V>
121where
122    K: Hash,
123    V: Hash,
124{
125    fn hash<H: Hasher>(&self, hasher: &mut H) {
126        self.items.hash(hasher)
127    }
128}
129
130impl<I: Idx, K: Ord, V> FromIterator<(K, V)> for SortedIndexMultiMap<I, K, V> {
131    fn from_iter<J>(iter: J) -> Self
132    where
133        J: IntoIterator<Item = (K, V)>,
134    {
135        let items = IndexVec::<I, _>::from_iter(iter);
136        let mut idx_sorted_by_item_key: Vec<_> = items.indices().collect();
137
138        // `sort_by_key` is stable, so insertion order is preserved for duplicate items.
139        idx_sorted_by_item_key.sort_by_key(|&idx| &items[idx].0);
140
141        SortedIndexMultiMap { items, idx_sorted_by_item_key }
142    }
143}
144
145impl<I: Idx, K, V> std::ops::Index<I> for SortedIndexMultiMap<I, K, V> {
146    type Output = V;
147
148    fn index(&self, idx: I) -> &Self::Output {
149        &self.items[idx].1
150    }
151}