Skip to main content

rustc_index/
vec.rs

1use std::borrow::{Borrow, BorrowMut};
2use std::hash::Hash;
3use std::marker::PhantomData;
4use std::ops::{Deref, DerefMut, RangeBounds};
5use std::{fmt, slice, vec};
6
7#[cfg(feature = "nightly")]
8use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
9
10use crate::{Idx, IndexSlice};
11
12/// An owned contiguous collection of `T`s, indexed by `I` rather than by `usize`.
13///
14/// ## Why use this instead of a `Vec`?
15///
16/// An `IndexVec` allows element access only via a specific associated index type, meaning that
17/// trying to use the wrong index type (possibly accessing an invalid element) will fail at
18/// compile time.
19///
20/// It also documents what the index is indexing: in a `HashMap<usize, Something>` it's not
21/// immediately clear what the `usize` means, while a `HashMap<FieldIdx, Something>` makes it obvious.
22///
23/// ```compile_fail
24/// use rustc_index::{Idx, IndexVec};
25///
26/// fn f<I1: Idx, I2: Idx>(vec1: IndexVec<I1, u8>, idx1: I1, idx2: I2) {
27///   &vec1[idx1]; // Ok
28///   &vec1[idx2]; // Compile error!
29/// }
30/// ```
31///
32/// While it's possible to use `u32` or `usize` directly for `I`,
33/// you almost certainly want to use a [`newtype_index!`]-generated type instead.
34///
35/// This allows to index the IndexVec with the new index type.
36///
37/// [`newtype_index!`]: ../macro.newtype_index.html
38#[derive(#[automatically_derived]impl<I: ::core::clone::Clone + Idx,
    T: ::core::clone::Clone> ::core::clone::Clone for IndexVec<I, T> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        IndexVec {
            raw: ::core::clone::Clone::clone(&self.raw),
            _marker: ::core::clone::Clone::clone(&self._marker),
        }
    }
}Clone, #[automatically_derived]impl<I: ::core::cmp::PartialEq + Idx,
    T: ::core::cmp::PartialEq> ::core::marker::StructuralPartialEq for
    IndexVec<I, T> {
}
#[automatically_derived]impl<I: ::core::cmp::PartialEq + Idx,
    T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for IndexVec<I, T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.raw == other.raw && self._marker == other._marker
    }
}PartialEq, #[automatically_derived]impl<I: ::core::cmp::Eq + Idx, T: ::core::cmp::Eq>
    ::core::cmp::Eq for IndexVec<I, T> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Vec<T>>;
        let _: ::core::cmp::AssertParamIsEq<PhantomData<fn(&I)>>;
    }
}Eq, #[automatically_derived]impl<I: ::core::hash::Hash + Idx,
    T: ::core::hash::Hash> ::core::hash::Hash for IndexVec<I, T> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.raw, state);
        ::core::hash::Hash::hash(&self._marker, state)
    }
}Hash)]
39#[repr(transparent)]
40pub struct IndexVec<I: Idx, T> {
41    pub raw: Vec<T>,
42    _marker: PhantomData<fn(&I)>,
43}
44
45impl<I: Idx, T> IndexVec<I, T> {
46    /// Constructs a new, empty `IndexVec<I, T>`.
47    #[inline]
48    pub const fn new() -> Self {
49        IndexVec::from_raw(Vec::new())
50    }
51
52    /// Constructs a new `IndexVec<I, T>` from a `Vec<T>`.
53    #[inline]
54    pub const fn from_raw(raw: Vec<T>) -> Self {
55        IndexVec { raw, _marker: PhantomData }
56    }
57
58    #[inline]
59    pub fn with_capacity(capacity: usize) -> Self {
60        IndexVec::from_raw(Vec::with_capacity(capacity))
61    }
62
63    /// Creates a new vector with a copy of `elem` for each index in `universe`.
64    ///
65    /// Thus `IndexVec::from_elem(elem, &universe)` is equivalent to
66    /// `IndexVec::<I, _>::from_elem_n(elem, universe.len())`. That can help
67    /// type inference as it ensures that the resulting vector uses the same
68    /// index type as `universe`, rather than something potentially surprising.
69    ///
70    /// For example, if you want to store data for each local in a MIR body,
71    /// using `let mut uses = IndexVec::from_elem(vec![], &body.local_decls);`
72    /// ensures that `uses` is an `IndexVec<Local, _>`, and thus can give
73    /// better error messages later if one accidentally mismatches indices.
74    #[inline]
75    pub fn from_elem<S>(elem: T, universe: &IndexSlice<I, S>) -> Self
76    where
77        T: Clone,
78    {
79        IndexVec::from_raw(::alloc::vec::from_elem_global(elem, universe.len())vec![elem; universe.len()])
80    }
81
82    /// Creates a new IndexVec with n copies of the `elem`.
83    #[inline]
84    pub fn from_elem_n(elem: T, n: usize) -> Self
85    where
86        T: Clone,
87    {
88        IndexVec::from_raw(::alloc::vec::from_elem_global(elem, n)vec![elem; n])
89    }
90
91    /// Create an `IndexVec` with `n` elements, where the value of each
92    /// element is the result of `func(i)`. (The underlying vector will
93    /// be allocated only once, with a capacity of at least `n`.)
94    #[inline]
95    pub fn from_fn_n(func: impl FnMut(I) -> T, n: usize) -> Self {
96        // Allow the optimizer to elide the bounds checking when creating each index.
97        let _ = I::new(n);
98        IndexVec::from_raw((0..n).map(I::new).map(func).collect())
99    }
100
101    #[inline]
102    pub fn as_slice(&self) -> &IndexSlice<I, T> {
103        IndexSlice::from_raw(&self.raw)
104    }
105
106    #[inline]
107    pub fn as_mut_slice(&mut self) -> &mut IndexSlice<I, T> {
108        IndexSlice::from_raw_mut(&mut self.raw)
109    }
110
111    /// Pushes an element to the array returning the index where it was pushed to.
112    #[inline]
113    pub fn push(&mut self, d: T) -> I {
114        let idx = self.next_index();
115        self.raw.push(d);
116        idx
117    }
118
119    /// Pushes an element using the given function, which receives the new index and
120    /// the vector's data as arguments. This is useful when you need the element's index
121    /// during its construction.
122    #[inline]
123    pub fn push_with<F>(&mut self, func: F) -> I
124    where
125        F: FnOnce(I, &mut IndexSlice<I, T>) -> T,
126    {
127        let idx = self.next_index();
128        let new_elem = func(idx, self.as_mut_slice());
129        self.raw.push(new_elem);
130        idx
131    }
132
133    #[inline]
134    pub fn pop(&mut self) -> Option<T> {
135        self.raw.pop()
136    }
137
138    #[inline]
139    pub fn into_iter(self) -> vec::IntoIter<T> {
140        self.raw.into_iter()
141    }
142
143    #[inline]
144    pub fn into_iter_enumerated(
145        self,
146    ) -> impl DoubleEndedIterator<Item = (I, T)> + ExactSizeIterator {
147        // Allow the optimizer to elide the bounds checking when creating each index.
148        let _ = I::new(self.len());
149        self.raw.into_iter().enumerate().map(|(n, t)| (I::new(n), t))
150    }
151
152    #[inline]
153    pub fn drain<R: RangeBounds<usize>>(&mut self, range: R) -> impl Iterator<Item = T> {
154        self.raw.drain(range)
155    }
156
157    #[inline]
158    pub fn drain_enumerated<R: RangeBounds<usize>>(
159        &mut self,
160        range: R,
161    ) -> impl Iterator<Item = (I, T)> {
162        let begin = match range.start_bound() {
163            std::ops::Bound::Included(i) => *i,
164            std::ops::Bound::Excluded(i) => i.checked_add(1).unwrap(),
165            std::ops::Bound::Unbounded => 0,
166        };
167        self.raw.drain(range).enumerate().map(move |(n, t)| (I::new(begin + n), t))
168    }
169
170    #[inline]
171    pub fn shrink_to_fit(&mut self) {
172        self.raw.shrink_to_fit()
173    }
174
175    #[inline]
176    pub fn truncate(&mut self, a: usize) {
177        self.raw.truncate(a)
178    }
179
180    /// Grows the index vector so that it contains an entry for
181    /// `elem`; if that is already true, then has no
182    /// effect. Otherwise, inserts new values as needed by invoking
183    /// `fill_value`.
184    ///
185    /// Returns a reference to the `elem` entry.
186    #[inline]
187    pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) -> &mut T {
188        let min_new_len = elem.index() + 1;
189        if self.len() < min_new_len {
190            self.raw.resize_with(min_new_len, fill_value);
191        }
192
193        &mut self[elem]
194    }
195
196    #[inline]
197    pub fn resize(&mut self, new_len: usize, value: T)
198    where
199        T: Clone,
200    {
201        self.raw.resize(new_len, value)
202    }
203
204    #[inline]
205    pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
206        let min_new_len = elem.index() + 1;
207        self.raw.resize_with(min_new_len, fill_value);
208    }
209
210    #[inline]
211    pub fn append(&mut self, other: &mut Self) {
212        self.raw.append(&mut other.raw);
213    }
214
215    #[inline]
216    pub fn debug_map_view(&self) -> IndexSliceMapView<'_, I, T> {
217        IndexSliceMapView(self.as_slice())
218    }
219}
220
221/// `IndexVec` is often used as a map, so it provides some map-like APIs.
222impl<I: Idx, T> IndexVec<I, Option<T>> {
223    #[inline]
224    pub fn insert(&mut self, index: I, value: T) -> Option<T> {
225        self.ensure_contains_elem(index, || None).replace(value)
226    }
227
228    #[inline]
229    pub fn get_or_insert_with(&mut self, index: I, value: impl FnOnce() -> T) -> &mut T {
230        self.ensure_contains_elem(index, || None).get_or_insert_with(value)
231    }
232
233    #[inline]
234    pub fn remove(&mut self, index: I) -> Option<T> {
235        self.get_mut(index)?.take()
236    }
237
238    #[inline]
239    pub fn contains(&self, index: I) -> bool {
240        self.get(index).and_then(Option::as_ref).is_some()
241    }
242
243    /// This debug view will skip printing `None` entries.
244    /// This is useful when the slice is actually like a map and `None` means
245    /// a value is absent under that key.
246    #[inline]
247    pub fn debug_map_view_compact(&self) -> IndexSliceMapViewCompact<'_, I, T> {
248        IndexSliceMapViewCompact(self.as_slice())
249    }
250}
251
252pub struct IndexSliceMapView<'a, I: Idx, T>(&'a IndexSlice<I, T>);
253pub struct IndexSliceMapViewCompact<'a, I: Idx, T>(&'a IndexSlice<I, Option<T>>);
254
255impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
256    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
257        fmt::Debug::fmt(self.as_slice(), fmt)
258    }
259}
260
261impl<'a, I: Idx, T: fmt::Debug> fmt::Debug for IndexSliceMapView<'a, I, T> {
262    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
263        let mut entries = fmt.debug_map();
264        for (idx, val) in self.0.iter_enumerated() {
265            entries.entry(&idx, val);
266        }
267        entries.finish()
268    }
269}
270
271impl<'a, I: Idx, T: fmt::Debug> fmt::Debug for IndexSliceMapViewCompact<'a, I, T> {
272    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
273        let mut entries = fmt.debug_map();
274        for (idx, val) in self.0.iter_enumerated() {
275            if let Some(val) = val {
276                entries.entry(&idx, val);
277            }
278        }
279        entries.finish()
280    }
281}
282
283impl<I: Idx, T> Deref for IndexVec<I, T> {
284    type Target = IndexSlice<I, T>;
285
286    #[inline]
287    fn deref(&self) -> &Self::Target {
288        self.as_slice()
289    }
290}
291
292impl<I: Idx, T> DerefMut for IndexVec<I, T> {
293    #[inline]
294    fn deref_mut(&mut self) -> &mut Self::Target {
295        self.as_mut_slice()
296    }
297}
298
299impl<I: Idx, T> Borrow<IndexSlice<I, T>> for IndexVec<I, T> {
300    fn borrow(&self) -> &IndexSlice<I, T> {
301        self
302    }
303}
304
305impl<I: Idx, T> BorrowMut<IndexSlice<I, T>> for IndexVec<I, T> {
306    fn borrow_mut(&mut self) -> &mut IndexSlice<I, T> {
307        self
308    }
309}
310
311impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
312    #[inline]
313    fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
314        self.raw.extend(iter);
315    }
316
317    #[inline]
318    #[cfg(feature = "nightly")]
319    fn extend_one(&mut self, item: T) {
320        self.raw.push(item);
321    }
322
323    #[inline]
324    #[cfg(feature = "nightly")]
325    fn extend_reserve(&mut self, additional: usize) {
326        self.raw.reserve(additional);
327    }
328}
329
330impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
331    #[inline]
332    fn from_iter<J>(iter: J) -> Self
333    where
334        J: IntoIterator<Item = T>,
335    {
336        IndexVec::from_raw(Vec::from_iter(iter))
337    }
338}
339
340impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
341    type Item = T;
342    type IntoIter = vec::IntoIter<T>;
343
344    #[inline]
345    fn into_iter(self) -> vec::IntoIter<T> {
346        self.raw.into_iter()
347    }
348}
349
350impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
351    type Item = &'a T;
352    type IntoIter = slice::Iter<'a, T>;
353
354    #[inline]
355    fn into_iter(self) -> slice::Iter<'a, T> {
356        self.iter()
357    }
358}
359
360impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
361    type Item = &'a mut T;
362    type IntoIter = slice::IterMut<'a, T>;
363
364    #[inline]
365    fn into_iter(self) -> slice::IterMut<'a, T> {
366        self.iter_mut()
367    }
368}
369
370impl<I: Idx, T> Default for IndexVec<I, T> {
371    #[inline]
372    fn default() -> Self {
373        IndexVec::new()
374    }
375}
376
377impl<I: Idx, T, const N: usize> From<[T; N]> for IndexVec<I, T> {
378    #[inline]
379    fn from(array: [T; N]) -> Self {
380        IndexVec::from_raw(array.into())
381    }
382}
383
384#[cfg(feature = "nightly")]
385impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for IndexVec<I, T> {
386    fn encode(&self, s: &mut S) {
387        Encodable::encode(&self.raw, s);
388    }
389}
390
391#[cfg(feature = "nightly")]
392impl<D: Decoder, I: Idx, T: Decodable<D>> Decodable<D> for IndexVec<I, T> {
393    fn decode(d: &mut D) -> Self {
394        IndexVec::from_raw(Vec::<T>::decode(d))
395    }
396}
397
398// Whether `IndexVec` is `Send` depends only on the data,
399// not the phantom data.
400unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
401
402#[cfg(test)]
403mod tests;