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(Clone, PartialEq, Eq, 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(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(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        IndexVec::from_raw((0..n).map(I::new).map(func).collect())
97    }
98
99    #[inline]
100    pub fn as_slice(&self) -> &IndexSlice<I, T> {
101        IndexSlice::from_raw(&self.raw)
102    }
103
104    #[inline]
105    pub fn as_mut_slice(&mut self) -> &mut IndexSlice<I, T> {
106        IndexSlice::from_raw_mut(&mut self.raw)
107    }
108
109    /// Pushes an element to the array returning the index where it was pushed to.
110    #[inline]
111    pub fn push(&mut self, d: T) -> I {
112        let idx = self.next_index();
113        self.raw.push(d);
114        idx
115    }
116
117    #[inline]
118    pub fn pop(&mut self) -> Option<T> {
119        self.raw.pop()
120    }
121
122    #[inline]
123    pub fn into_iter(self) -> vec::IntoIter<T> {
124        self.raw.into_iter()
125    }
126
127    #[inline]
128    pub fn into_iter_enumerated(
129        self,
130    ) -> impl DoubleEndedIterator<Item = (I, T)> + ExactSizeIterator {
131        self.raw.into_iter().enumerate().map(|(n, t)| (I::new(n), t))
132    }
133
134    #[inline]
135    pub fn drain<R: RangeBounds<usize>>(&mut self, range: R) -> impl Iterator<Item = T> + '_ {
136        self.raw.drain(range)
137    }
138
139    #[inline]
140    pub fn drain_enumerated<R: RangeBounds<usize>>(
141        &mut self,
142        range: R,
143    ) -> impl Iterator<Item = (I, T)> + '_ {
144        let begin = match range.start_bound() {
145            std::ops::Bound::Included(i) => *i,
146            std::ops::Bound::Excluded(i) => i.checked_add(1).unwrap(),
147            std::ops::Bound::Unbounded => 0,
148        };
149        self.raw.drain(range).enumerate().map(move |(n, t)| (I::new(begin + n), t))
150    }
151
152    #[inline]
153    pub fn shrink_to_fit(&mut self) {
154        self.raw.shrink_to_fit()
155    }
156
157    #[inline]
158    pub fn truncate(&mut self, a: usize) {
159        self.raw.truncate(a)
160    }
161
162    /// Grows the index vector so that it contains an entry for
163    /// `elem`; if that is already true, then has no
164    /// effect. Otherwise, inserts new values as needed by invoking
165    /// `fill_value`.
166    ///
167    /// Returns a reference to the `elem` entry.
168    #[inline]
169    pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) -> &mut T {
170        let min_new_len = elem.index() + 1;
171        if self.len() < min_new_len {
172            self.raw.resize_with(min_new_len, fill_value);
173        }
174
175        &mut self[elem]
176    }
177
178    #[inline]
179    pub fn resize(&mut self, new_len: usize, value: T)
180    where
181        T: Clone,
182    {
183        self.raw.resize(new_len, value)
184    }
185
186    #[inline]
187    pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
188        let min_new_len = elem.index() + 1;
189        self.raw.resize_with(min_new_len, fill_value);
190    }
191
192    #[inline]
193    pub fn append(&mut self, other: &mut Self) {
194        self.raw.append(&mut other.raw);
195    }
196}
197
198/// `IndexVec` is often used as a map, so it provides some map-like APIs.
199impl<I: Idx, T> IndexVec<I, Option<T>> {
200    #[inline]
201    pub fn insert(&mut self, index: I, value: T) -> Option<T> {
202        self.ensure_contains_elem(index, || None).replace(value)
203    }
204
205    #[inline]
206    pub fn get_or_insert_with(&mut self, index: I, value: impl FnOnce() -> T) -> &mut T {
207        self.ensure_contains_elem(index, || None).get_or_insert_with(value)
208    }
209
210    #[inline]
211    pub fn remove(&mut self, index: I) -> Option<T> {
212        self.get_mut(index)?.take()
213    }
214
215    #[inline]
216    pub fn contains(&self, index: I) -> bool {
217        self.get(index).and_then(Option::as_ref).is_some()
218    }
219}
220
221impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
222    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
223        fmt::Debug::fmt(&self.raw, fmt)
224    }
225}
226
227impl<I: Idx, T> Deref for IndexVec<I, T> {
228    type Target = IndexSlice<I, T>;
229
230    #[inline]
231    fn deref(&self) -> &Self::Target {
232        self.as_slice()
233    }
234}
235
236impl<I: Idx, T> DerefMut for IndexVec<I, T> {
237    #[inline]
238    fn deref_mut(&mut self) -> &mut Self::Target {
239        self.as_mut_slice()
240    }
241}
242
243impl<I: Idx, T> Borrow<IndexSlice<I, T>> for IndexVec<I, T> {
244    fn borrow(&self) -> &IndexSlice<I, T> {
245        self
246    }
247}
248
249impl<I: Idx, T> BorrowMut<IndexSlice<I, T>> for IndexVec<I, T> {
250    fn borrow_mut(&mut self) -> &mut IndexSlice<I, T> {
251        self
252    }
253}
254
255impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
256    #[inline]
257    fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
258        self.raw.extend(iter);
259    }
260
261    #[inline]
262    #[cfg(feature = "nightly")]
263    fn extend_one(&mut self, item: T) {
264        self.raw.push(item);
265    }
266
267    #[inline]
268    #[cfg(feature = "nightly")]
269    fn extend_reserve(&mut self, additional: usize) {
270        self.raw.reserve(additional);
271    }
272}
273
274impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
275    #[inline]
276    fn from_iter<J>(iter: J) -> Self
277    where
278        J: IntoIterator<Item = T>,
279    {
280        IndexVec::from_raw(Vec::from_iter(iter))
281    }
282}
283
284impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
285    type Item = T;
286    type IntoIter = vec::IntoIter<T>;
287
288    #[inline]
289    fn into_iter(self) -> vec::IntoIter<T> {
290        self.raw.into_iter()
291    }
292}
293
294impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
295    type Item = &'a T;
296    type IntoIter = slice::Iter<'a, T>;
297
298    #[inline]
299    fn into_iter(self) -> slice::Iter<'a, T> {
300        self.iter()
301    }
302}
303
304impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
305    type Item = &'a mut T;
306    type IntoIter = slice::IterMut<'a, T>;
307
308    #[inline]
309    fn into_iter(self) -> slice::IterMut<'a, T> {
310        self.iter_mut()
311    }
312}
313
314impl<I: Idx, T> Default for IndexVec<I, T> {
315    #[inline]
316    fn default() -> Self {
317        IndexVec::new()
318    }
319}
320
321impl<I: Idx, T, const N: usize> From<[T; N]> for IndexVec<I, T> {
322    #[inline]
323    fn from(array: [T; N]) -> Self {
324        IndexVec::from_raw(array.into())
325    }
326}
327
328#[cfg(feature = "nightly")]
329impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for IndexVec<I, T> {
330    fn encode(&self, s: &mut S) {
331        Encodable::encode(&self.raw, s);
332    }
333}
334
335#[cfg(feature = "nightly")]
336impl<D: Decoder, I: Idx, T: Decodable<D>> Decodable<D> for IndexVec<I, T> {
337    fn decode(d: &mut D) -> Self {
338        IndexVec::from_raw(Vec::<T>::decode(d))
339    }
340}
341
342// Whether `IndexVec` is `Send` depends only on the data,
343// not the phantom data.
344unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
345
346#[cfg(test)]
347mod tests;