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