]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_index/src/vec.rs
Rollup merge of #100630 - Enselic:export_extern_crate_as_self, r=GuillaumeGomez
[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(
176         &self,
177     ) -> impl DoubleEndedIterator<Item = I> + ExactSizeIterator + Clone + 'static {
178         (0..self.len()).map(|n| I::new(n))
179     }
180
181     #[inline]
182     pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
183         self.raw.iter_mut()
184     }
185
186     #[inline]
187     pub fn iter_enumerated_mut(
188         &mut self,
189     ) -> impl DoubleEndedIterator<Item = (I, &mut T)> + ExactSizeIterator + '_ {
190         self.raw.iter_mut().enumerate().map(|(n, t)| (I::new(n), t))
191     }
192
193     #[inline]
194     pub fn drain<'a, R: RangeBounds<usize>>(
195         &'a mut self,
196         range: R,
197     ) -> impl Iterator<Item = T> + 'a {
198         self.raw.drain(range)
199     }
200
201     #[inline]
202     pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
203         &'a mut self,
204         range: R,
205     ) -> impl Iterator<Item = (I, T)> + 'a {
206         self.raw.drain(range).enumerate().map(|(n, t)| (I::new(n), t))
207     }
208
209     #[inline]
210     pub fn last(&self) -> Option<I> {
211         self.len().checked_sub(1).map(I::new)
212     }
213
214     #[inline]
215     pub fn shrink_to_fit(&mut self) {
216         self.raw.shrink_to_fit()
217     }
218
219     #[inline]
220     pub fn swap(&mut self, a: I, b: I) {
221         self.raw.swap(a.index(), b.index())
222     }
223
224     #[inline]
225     pub fn truncate(&mut self, a: usize) {
226         self.raw.truncate(a)
227     }
228
229     #[inline]
230     pub fn get(&self, index: I) -> Option<&T> {
231         self.raw.get(index.index())
232     }
233
234     #[inline]
235     pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
236         self.raw.get_mut(index.index())
237     }
238
239     /// Returns mutable references to two distinct elements, `a` and `b`.
240     ///
241     /// Panics if `a == b`.
242     #[inline]
243     pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
244         let (ai, bi) = (a.index(), b.index());
245         assert!(ai != bi);
246
247         if ai < bi {
248             let (c1, c2) = self.raw.split_at_mut(bi);
249             (&mut c1[ai], &mut c2[0])
250         } else {
251             let (c2, c1) = self.pick2_mut(b, a);
252             (c1, c2)
253         }
254     }
255
256     /// Returns mutable references to three distinct elements.
257     ///
258     /// Panics if the elements are not distinct.
259     #[inline]
260     pub fn pick3_mut(&mut self, a: I, b: I, c: I) -> (&mut T, &mut T, &mut T) {
261         let (ai, bi, ci) = (a.index(), b.index(), c.index());
262         assert!(ai != bi && bi != ci && ci != ai);
263         let len = self.raw.len();
264         assert!(ai < len && bi < len && ci < len);
265         let ptr = self.raw.as_mut_ptr();
266         unsafe { (&mut *ptr.add(ai), &mut *ptr.add(bi), &mut *ptr.add(ci)) }
267     }
268
269     pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
270         IndexVec { raw: self.raw, _marker: PhantomData }
271     }
272
273     /// Grows the index vector so that it contains an entry for
274     /// `elem`; if that is already true, then has no
275     /// effect. Otherwise, inserts new values as needed by invoking
276     /// `fill_value`.
277     #[inline]
278     pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
279         let min_new_len = elem.index() + 1;
280         if self.len() < min_new_len {
281             self.raw.resize_with(min_new_len, fill_value);
282         }
283     }
284
285     #[inline]
286     pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
287         let min_new_len = elem.index() + 1;
288         self.raw.resize_with(min_new_len, fill_value);
289     }
290 }
291
292 /// `IndexVec` is often used as a map, so it provides some map-like APIs.
293 impl<I: Idx, T> IndexVec<I, Option<T>> {
294     #[inline]
295     pub fn insert(&mut self, index: I, value: T) -> Option<T> {
296         self.ensure_contains_elem(index, || None);
297         self[index].replace(value)
298     }
299
300     #[inline]
301     pub fn get_or_insert_with(&mut self, index: I, value: impl FnOnce() -> T) -> &mut T {
302         self.ensure_contains_elem(index, || None);
303         self[index].get_or_insert_with(value)
304     }
305
306     #[inline]
307     pub fn remove(&mut self, index: I) -> Option<T> {
308         self.ensure_contains_elem(index, || None);
309         self[index].take()
310     }
311 }
312
313 impl<I: Idx, T: Clone> IndexVec<I, T> {
314     #[inline]
315     pub fn resize(&mut self, new_len: usize, value: T) {
316         self.raw.resize(new_len, value)
317     }
318 }
319
320 impl<I: Idx, T: Ord> IndexVec<I, T> {
321     #[inline]
322     pub fn binary_search(&self, value: &T) -> Result<I, I> {
323         match self.raw.binary_search(value) {
324             Ok(i) => Ok(Idx::new(i)),
325             Err(i) => Err(Idx::new(i)),
326         }
327     }
328 }
329
330 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
331     type Output = T;
332
333     #[inline]
334     fn index(&self, index: I) -> &T {
335         &self.raw[index.index()]
336     }
337 }
338
339 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
340     #[inline]
341     fn index_mut(&mut self, index: I) -> &mut T {
342         &mut self.raw[index.index()]
343     }
344 }
345
346 impl<I: Idx, T> Default for IndexVec<I, T> {
347     #[inline]
348     fn default() -> Self {
349         Self::new()
350     }
351 }
352
353 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
354     #[inline]
355     fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
356         self.raw.extend(iter);
357     }
358
359     #[inline]
360     fn extend_one(&mut self, item: T) {
361         self.raw.push(item);
362     }
363
364     #[inline]
365     fn extend_reserve(&mut self, additional: usize) {
366         self.raw.reserve(additional);
367     }
368 }
369
370 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
371     #[inline]
372     fn from_iter<J>(iter: J) -> Self
373     where
374         J: IntoIterator<Item = T>,
375     {
376         IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
377     }
378 }
379
380 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
381     type Item = T;
382     type IntoIter = vec::IntoIter<T>;
383
384     #[inline]
385     fn into_iter(self) -> vec::IntoIter<T> {
386         self.raw.into_iter()
387     }
388 }
389
390 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
391     type Item = &'a T;
392     type IntoIter = slice::Iter<'a, T>;
393
394     #[inline]
395     fn into_iter(self) -> slice::Iter<'a, T> {
396         self.raw.iter()
397     }
398 }
399
400 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
401     type Item = &'a mut T;
402     type IntoIter = slice::IterMut<'a, T>;
403
404     #[inline]
405     fn into_iter(self) -> slice::IterMut<'a, T> {
406         self.raw.iter_mut()
407     }
408 }
409
410 #[cfg(test)]
411 mod tests;