]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_index/src/vec.rs
Auto merge of #104999 - saethlin:immediate-abort-inlining, r=thomcc
[rust.git] / compiler / rustc_index / src / vec.rs
1 #[cfg(feature = "rustc_serialize")]
2 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
3
4 use std::fmt;
5 use std::fmt::Debug;
6 use std::hash::Hash;
7 use std::iter::FromIterator;
8 use std::marker::PhantomData;
9 use std::ops::{Index, IndexMut, RangeBounds};
10 use std::slice;
11 use std::vec;
12
13 /// Represents some newtyped `usize` wrapper.
14 ///
15 /// Purpose: avoid mixing indexes for different bitvector domains.
16 pub trait Idx: Copy + 'static + Eq + PartialEq + Debug + Hash {
17     fn new(idx: usize) -> Self;
18
19     fn index(self) -> usize;
20
21     #[inline]
22     fn increment_by(&mut self, amount: usize) {
23         *self = self.plus(amount);
24     }
25
26     #[inline]
27     fn plus(self, amount: usize) -> Self {
28         Self::new(self.index() + amount)
29     }
30 }
31
32 impl Idx for usize {
33     #[inline]
34     fn new(idx: usize) -> Self {
35         idx
36     }
37     #[inline]
38     fn index(self) -> usize {
39         self
40     }
41 }
42
43 impl Idx for u32 {
44     #[inline]
45     fn new(idx: usize) -> Self {
46         assert!(idx <= u32::MAX as usize);
47         idx as u32
48     }
49     #[inline]
50     fn index(self) -> usize {
51         self as usize
52     }
53 }
54
55 #[derive(Clone, PartialEq, Eq, Hash)]
56 pub struct IndexVec<I: Idx, T> {
57     pub raw: Vec<T>,
58     _marker: PhantomData<fn(&I)>,
59 }
60
61 // Whether `IndexVec` is `Send` depends only on the data,
62 // not the phantom data.
63 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
64
65 #[cfg(feature = "rustc_serialize")]
66 impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for IndexVec<I, T> {
67     fn encode(&self, s: &mut S) {
68         Encodable::encode(&self.raw, s);
69     }
70 }
71
72 #[cfg(feature = "rustc_serialize")]
73 impl<D: Decoder, I: Idx, T: Decodable<D>> Decodable<D> for IndexVec<I, T> {
74     fn decode(d: &mut D) -> Self {
75         IndexVec { raw: Decodable::decode(d), _marker: PhantomData }
76     }
77 }
78
79 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
80     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
81         fmt::Debug::fmt(&self.raw, fmt)
82     }
83 }
84
85 impl<I: Idx, T> IndexVec<I, T> {
86     #[inline]
87     pub fn new() -> Self {
88         IndexVec { raw: Vec::new(), _marker: PhantomData }
89     }
90
91     #[inline]
92     pub fn from_raw(raw: Vec<T>) -> Self {
93         IndexVec { raw, _marker: PhantomData }
94     }
95
96     #[inline]
97     pub fn with_capacity(capacity: usize) -> Self {
98         IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
99     }
100
101     #[inline]
102     pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
103     where
104         T: Clone,
105     {
106         IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
107     }
108
109     #[inline]
110     pub fn from_elem_n(elem: T, n: usize) -> Self
111     where
112         T: Clone,
113     {
114         IndexVec { raw: vec![elem; n], _marker: PhantomData }
115     }
116
117     /// Create an `IndexVec` with `n` elements, where the value of each
118     /// element is the result of `func(i)`. (The underlying vector will
119     /// be allocated only once, with a capacity of at least `n`.)
120     #[inline]
121     pub fn from_fn_n(func: impl FnMut(I) -> T, n: usize) -> Self {
122         let indices = (0..n).map(I::new);
123         Self::from_raw(indices.map(func).collect())
124     }
125
126     #[inline]
127     pub fn push(&mut self, d: T) -> I {
128         let idx = I::new(self.len());
129         self.raw.push(d);
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 len(&self) -> usize {
140         self.raw.len()
141     }
142
143     /// Gives the next index that will be assigned when `push` is
144     /// called.
145     #[inline]
146     pub fn next_index(&self) -> I {
147         I::new(self.len())
148     }
149
150     #[inline]
151     pub fn is_empty(&self) -> bool {
152         self.raw.is_empty()
153     }
154
155     #[inline]
156     pub fn into_iter(self) -> vec::IntoIter<T> {
157         self.raw.into_iter()
158     }
159
160     #[inline]
161     pub fn into_iter_enumerated(
162         self,
163     ) -> impl DoubleEndedIterator<Item = (I, T)> + ExactSizeIterator {
164         self.raw.into_iter().enumerate().map(|(n, t)| (I::new(n), t))
165     }
166
167     #[inline]
168     pub fn iter(&self) -> slice::Iter<'_, T> {
169         self.raw.iter()
170     }
171
172     #[inline]
173     pub fn iter_enumerated(
174         &self,
175     ) -> impl DoubleEndedIterator<Item = (I, &T)> + ExactSizeIterator + '_ {
176         self.raw.iter().enumerate().map(|(n, t)| (I::new(n), t))
177     }
178
179     #[inline]
180     pub fn indices(
181         &self,
182     ) -> impl DoubleEndedIterator<Item = I> + ExactSizeIterator + Clone + 'static {
183         (0..self.len()).map(|n| I::new(n))
184     }
185
186     #[inline]
187     pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
188         self.raw.iter_mut()
189     }
190
191     #[inline]
192     pub fn iter_enumerated_mut(
193         &mut self,
194     ) -> impl DoubleEndedIterator<Item = (I, &mut T)> + ExactSizeIterator + '_ {
195         self.raw.iter_mut().enumerate().map(|(n, t)| (I::new(n), t))
196     }
197
198     #[inline]
199     pub fn drain<'a, R: RangeBounds<usize>>(
200         &'a mut self,
201         range: R,
202     ) -> impl Iterator<Item = T> + 'a {
203         self.raw.drain(range)
204     }
205
206     #[inline]
207     pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
208         &'a mut self,
209         range: R,
210     ) -> impl Iterator<Item = (I, T)> + 'a {
211         self.raw.drain(range).enumerate().map(|(n, t)| (I::new(n), t))
212     }
213
214     #[inline]
215     pub fn last(&self) -> Option<I> {
216         self.len().checked_sub(1).map(I::new)
217     }
218
219     #[inline]
220     pub fn shrink_to_fit(&mut self) {
221         self.raw.shrink_to_fit()
222     }
223
224     #[inline]
225     pub fn swap(&mut self, a: I, b: I) {
226         self.raw.swap(a.index(), b.index())
227     }
228
229     #[inline]
230     pub fn truncate(&mut self, a: usize) {
231         self.raw.truncate(a)
232     }
233
234     #[inline]
235     pub fn get(&self, index: I) -> Option<&T> {
236         self.raw.get(index.index())
237     }
238
239     #[inline]
240     pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
241         self.raw.get_mut(index.index())
242     }
243
244     /// Returns mutable references to two distinct elements, `a` and `b`.
245     ///
246     /// Panics if `a == b`.
247     #[inline]
248     pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
249         let (ai, bi) = (a.index(), b.index());
250         assert!(ai != bi);
251
252         if ai < bi {
253             let (c1, c2) = self.raw.split_at_mut(bi);
254             (&mut c1[ai], &mut c2[0])
255         } else {
256             let (c2, c1) = self.pick2_mut(b, a);
257             (c1, c2)
258         }
259     }
260
261     /// Returns mutable references to three distinct elements.
262     ///
263     /// Panics if the elements are not distinct.
264     #[inline]
265     pub fn pick3_mut(&mut self, a: I, b: I, c: I) -> (&mut T, &mut T, &mut T) {
266         let (ai, bi, ci) = (a.index(), b.index(), c.index());
267         assert!(ai != bi && bi != ci && ci != ai);
268         let len = self.raw.len();
269         assert!(ai < len && bi < len && ci < len);
270         let ptr = self.raw.as_mut_ptr();
271         unsafe { (&mut *ptr.add(ai), &mut *ptr.add(bi), &mut *ptr.add(ci)) }
272     }
273
274     pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
275         IndexVec { raw: self.raw, _marker: PhantomData }
276     }
277
278     /// Grows the index vector so that it contains an entry for
279     /// `elem`; if that is already true, then has no
280     /// effect. Otherwise, inserts new values as needed by invoking
281     /// `fill_value`.
282     #[inline]
283     pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
284         let min_new_len = elem.index() + 1;
285         if self.len() < min_new_len {
286             self.raw.resize_with(min_new_len, fill_value);
287         }
288     }
289
290     #[inline]
291     pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
292         let min_new_len = elem.index() + 1;
293         self.raw.resize_with(min_new_len, fill_value);
294     }
295 }
296
297 /// `IndexVec` is often used as a map, so it provides some map-like APIs.
298 impl<I: Idx, T> IndexVec<I, Option<T>> {
299     #[inline]
300     pub fn insert(&mut self, index: I, value: T) -> Option<T> {
301         self.ensure_contains_elem(index, || None);
302         self[index].replace(value)
303     }
304
305     #[inline]
306     pub fn get_or_insert_with(&mut self, index: I, value: impl FnOnce() -> T) -> &mut T {
307         self.ensure_contains_elem(index, || None);
308         self[index].get_or_insert_with(value)
309     }
310
311     #[inline]
312     pub fn remove(&mut self, index: I) -> Option<T> {
313         self.ensure_contains_elem(index, || None);
314         self[index].take()
315     }
316 }
317
318 impl<I: Idx, T: Clone> IndexVec<I, T> {
319     #[inline]
320     pub fn resize(&mut self, new_len: usize, value: T) {
321         self.raw.resize(new_len, value)
322     }
323 }
324
325 impl<I: Idx, T: Ord> IndexVec<I, T> {
326     #[inline]
327     pub fn binary_search(&self, value: &T) -> Result<I, I> {
328         match self.raw.binary_search(value) {
329             Ok(i) => Ok(Idx::new(i)),
330             Err(i) => Err(Idx::new(i)),
331         }
332     }
333 }
334
335 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
336     type Output = T;
337
338     #[inline]
339     fn index(&self, index: I) -> &T {
340         &self.raw[index.index()]
341     }
342 }
343
344 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
345     #[inline]
346     fn index_mut(&mut self, index: I) -> &mut T {
347         &mut self.raw[index.index()]
348     }
349 }
350
351 impl<I: Idx, T> Default for IndexVec<I, T> {
352     #[inline]
353     fn default() -> Self {
354         Self::new()
355     }
356 }
357
358 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
359     #[inline]
360     fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
361         self.raw.extend(iter);
362     }
363
364     #[inline]
365     #[cfg(feature = "nightly")]
366     fn extend_one(&mut self, item: T) {
367         self.raw.push(item);
368     }
369
370     #[inline]
371     #[cfg(feature = "nightly")]
372     fn extend_reserve(&mut self, additional: usize) {
373         self.raw.reserve(additional);
374     }
375 }
376
377 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
378     #[inline]
379     fn from_iter<J>(iter: J) -> Self
380     where
381         J: IntoIterator<Item = T>,
382     {
383         IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
384     }
385 }
386
387 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
388     type Item = T;
389     type IntoIter = vec::IntoIter<T>;
390
391     #[inline]
392     fn into_iter(self) -> vec::IntoIter<T> {
393         self.raw.into_iter()
394     }
395 }
396
397 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
398     type Item = &'a T;
399     type IntoIter = slice::Iter<'a, T>;
400
401     #[inline]
402     fn into_iter(self) -> slice::Iter<'a, T> {
403         self.raw.iter()
404     }
405 }
406
407 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
408     type Item = &'a mut T;
409     type IntoIter = slice::IterMut<'a, T>;
410
411     #[inline]
412     fn into_iter(self) -> slice::IterMut<'a, T> {
413         self.raw.iter_mut()
414     }
415 }
416
417 #[cfg(test)]
418 mod tests;