]> git.lizzy.rs Git - rust.git/blob - src/librustc_index/vec.rs
Rollup merge of #75485 - RalfJung:pin, r=nagisa
[rust.git] / src / librustc_index / 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::{self, FromIterator};
7 use std::marker::PhantomData;
8 use std::ops::{Index, IndexMut, Range, 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 + Ord + 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 /// Creates a struct type `S` that can be used as an index with
53 /// `IndexVec` and so on.
54 ///
55 /// There are two ways of interacting with these indices:
56 ///
57 /// - The `From` impls are the preferred way. So you can do
58 ///   `S::from(v)` with a `usize` or `u32`. And you can convert back
59 ///   to an integer with `u32::from(s)`.
60 ///
61 /// - Alternatively, you can use the methods `S::new(v)` and `s.index()`
62 ///   to create/return a value.
63 ///
64 /// Internally, the index uses a u32, so the index must not exceed
65 /// `u32::MAX`. You can also customize things like the `Debug` impl,
66 /// what traits are derived, and so forth via the macro.
67 #[macro_export]
68 #[allow_internal_unstable(step_trait, step_trait_ext, rustc_attrs)]
69 macro_rules! newtype_index {
70     // ---- public rules ----
71
72     // Use default constants
73     ($(#[$attrs:meta])* $v:vis struct $name:ident { .. }) => (
74         $crate::newtype_index!(
75             // Leave out derives marker so we can use its absence to ensure it comes first
76             @attrs        [$(#[$attrs])*]
77             @type         [$name]
78             // shave off 256 indices at the end to allow space for packing these indices into enums
79             @max          [0xFFFF_FF00]
80             @vis          [$v]
81             @debug_format ["{}"]);
82     );
83
84     // Define any constants
85     ($(#[$attrs:meta])* $v:vis struct $name:ident { $($tokens:tt)+ }) => (
86         $crate::newtype_index!(
87             // Leave out derives marker so we can use its absence to ensure it comes first
88             @attrs        [$(#[$attrs])*]
89             @type         [$name]
90             // shave off 256 indices at the end to allow space for packing these indices into enums
91             @max          [0xFFFF_FF00]
92             @vis          [$v]
93             @debug_format ["{}"]
94                           $($tokens)+);
95     );
96
97     // ---- private rules ----
98
99     // Base case, user-defined constants (if any) have already been defined
100     (@derives      [$($derives:ident,)*]
101      @attrs        [$(#[$attrs:meta])*]
102      @type         [$type:ident]
103      @max          [$max:expr]
104      @vis          [$v:vis]
105      @debug_format [$debug_format:tt]) => (
106         $(#[$attrs])*
107         #[derive(Copy, PartialEq, Eq, Hash, PartialOrd, Ord, $($derives),*)]
108         #[rustc_layout_scalar_valid_range_end($max)]
109         $v struct $type {
110             private: u32
111         }
112
113         impl Clone for $type {
114             fn clone(&self) -> Self {
115                 *self
116             }
117         }
118
119         impl $type {
120             $v const MAX_AS_U32: u32 = $max;
121
122             $v const MAX: Self = Self::from_u32($max);
123
124             #[inline]
125             $v const fn from_usize(value: usize) -> Self {
126                 assert!(value <= ($max as usize));
127                 unsafe {
128                     Self::from_u32_unchecked(value as u32)
129                 }
130             }
131
132             #[inline]
133             $v const fn from_u32(value: u32) -> Self {
134                 assert!(value <= $max);
135                 unsafe {
136                     Self::from_u32_unchecked(value)
137                 }
138             }
139
140             #[inline]
141             $v const unsafe fn from_u32_unchecked(value: u32) -> Self {
142                 Self { private: value }
143             }
144
145             /// Extracts the value of this index as an integer.
146             #[inline]
147             $v const fn index(self) -> usize {
148                 self.as_usize()
149             }
150
151             /// Extracts the value of this index as a `u32`.
152             #[inline]
153             $v const fn as_u32(self) -> u32 {
154                 self.private
155             }
156
157             /// Extracts the value of this index as a `usize`.
158             #[inline]
159             $v const fn as_usize(self) -> usize {
160                 self.as_u32() as usize
161             }
162         }
163
164         impl std::ops::Add<usize> for $type {
165             type Output = Self;
166
167             fn add(self, other: usize) -> Self {
168                 Self::from_usize(self.index() + other)
169             }
170         }
171
172         impl $crate::vec::Idx for $type {
173             #[inline]
174             fn new(value: usize) -> Self {
175                 Self::from_usize(value)
176             }
177
178             #[inline]
179             fn index(self) -> usize {
180                 self.as_usize()
181             }
182         }
183
184         unsafe impl ::std::iter::Step for $type {
185             #[inline]
186             fn steps_between(start: &Self, end: &Self) -> Option<usize> {
187                 <usize as ::std::iter::Step>::steps_between(
188                     &Self::index(*start),
189                     &Self::index(*end),
190                 )
191             }
192
193             #[inline]
194             fn forward_checked(start: Self, u: usize) -> Option<Self> {
195                 Self::index(start).checked_add(u).map(Self::from_usize)
196             }
197
198             #[inline]
199             fn backward_checked(start: Self, u: usize) -> Option<Self> {
200                 Self::index(start).checked_sub(u).map(Self::from_usize)
201             }
202         }
203
204         impl From<$type> for u32 {
205             #[inline]
206             fn from(v: $type) -> u32 {
207                 v.as_u32()
208             }
209         }
210
211         impl From<$type> for usize {
212             #[inline]
213             fn from(v: $type) -> usize {
214                 v.as_usize()
215             }
216         }
217
218         impl From<usize> for $type {
219             #[inline]
220             fn from(value: usize) -> Self {
221                 Self::from_usize(value)
222             }
223         }
224
225         impl From<u32> for $type {
226             #[inline]
227             fn from(value: u32) -> Self {
228                 Self::from_u32(value)
229             }
230         }
231
232         $crate::newtype_index!(
233             @handle_debug
234             @derives      [$($derives,)*]
235             @type         [$type]
236             @debug_format [$debug_format]);
237     );
238
239     // base case for handle_debug where format is custom. No Debug implementation is emitted.
240     (@handle_debug
241      @derives      [$($_derives:ident,)*]
242      @type         [$type:ident]
243      @debug_format [custom]) => ();
244
245     // base case for handle_debug, no debug overrides found, so use default
246     (@handle_debug
247      @derives      []
248      @type         [$type:ident]
249      @debug_format [$debug_format:tt]) => (
250         impl ::std::fmt::Debug for $type {
251             fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
252                 write!(fmt, $debug_format, self.as_u32())
253             }
254         }
255     );
256
257     // Debug is requested for derive, don't generate any Debug implementation.
258     (@handle_debug
259      @derives      [Debug, $($derives:ident,)*]
260      @type         [$type:ident]
261      @debug_format [$debug_format:tt]) => ();
262
263     // It's not Debug, so just pop it off the front of the derives stack and check the rest.
264     (@handle_debug
265      @derives      [$_derive:ident, $($derives:ident,)*]
266      @type         [$type:ident]
267      @debug_format [$debug_format:tt]) => (
268         $crate::newtype_index!(
269             @handle_debug
270             @derives      [$($derives,)*]
271             @type         [$type]
272             @debug_format [$debug_format]);
273     );
274
275     // Append comma to end of derives list if it's missing
276     (@attrs        [$(#[$attrs:meta])*]
277      @type         [$type:ident]
278      @max          [$max:expr]
279      @vis          [$v:vis]
280      @debug_format [$debug_format:tt]
281                    derive [$($derives:ident),*]
282                    $($tokens:tt)*) => (
283         $crate::newtype_index!(
284             @attrs        [$(#[$attrs])*]
285             @type         [$type]
286             @max          [$max]
287             @vis          [$v]
288             @debug_format [$debug_format]
289                           derive [$($derives,)*]
290                           $($tokens)*);
291     );
292
293     // By not including the @derives marker in this list nor in the default args, we can force it
294     // to come first if it exists. When encodable is custom, just use the derives list as-is.
295     (@attrs        [$(#[$attrs:meta])*]
296      @type         [$type:ident]
297      @max          [$max:expr]
298      @vis          [$v:vis]
299      @debug_format [$debug_format:tt]
300                    derive [$($derives:ident,)+]
301                    ENCODABLE = custom
302                    $($tokens:tt)*) => (
303         $crate::newtype_index!(
304             @attrs        [$(#[$attrs])*]
305             @derives      [$($derives,)+]
306             @type         [$type]
307             @max          [$max]
308             @vis          [$v]
309             @debug_format [$debug_format]
310                           $($tokens)*);
311     );
312
313     // By not including the @derives marker in this list nor in the default args, we can force it
314     // to come first if it exists. When encodable isn't custom, add serialization traits by default.
315     (@attrs        [$(#[$attrs:meta])*]
316      @type         [$type:ident]
317      @max          [$max:expr]
318      @vis          [$v:vis]
319      @debug_format [$debug_format:tt]
320                    derive [$($derives:ident,)+]
321                    $($tokens:tt)*) => (
322         $crate::newtype_index!(
323             @derives      [$($derives,)+]
324             @attrs        [$(#[$attrs])*]
325             @type         [$type]
326             @max          [$max]
327             @vis          [$v]
328             @debug_format [$debug_format]
329                           $($tokens)*);
330         $crate::newtype_index!(@serializable $type);
331     );
332
333     // The case where no derives are added, but encodable is overridden. Don't
334     // derive serialization traits
335     (@attrs        [$(#[$attrs:meta])*]
336      @type         [$type:ident]
337      @max          [$max:expr]
338      @vis          [$v:vis]
339      @debug_format [$debug_format:tt]
340                    ENCODABLE = custom
341                    $($tokens:tt)*) => (
342         $crate::newtype_index!(
343             @derives      []
344             @attrs        [$(#[$attrs])*]
345             @type         [$type]
346             @max          [$max]
347             @vis          [$v]
348             @debug_format [$debug_format]
349                           $($tokens)*);
350     );
351
352     // The case where no derives are added, add serialization derives by default
353     (@attrs        [$(#[$attrs:meta])*]
354      @type         [$type:ident]
355      @max          [$max:expr]
356      @vis          [$v:vis]
357      @debug_format [$debug_format:tt]
358                    $($tokens:tt)*) => (
359         $crate::newtype_index!(
360             @derives      []
361             @attrs        [$(#[$attrs])*]
362             @type         [$type]
363             @max          [$max]
364             @vis          [$v]
365             @debug_format [$debug_format]
366                           $($tokens)*);
367         $crate::newtype_index!(@serializable $type);
368     );
369
370     (@serializable $type:ident) => (
371         impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for $type {
372             fn decode(d: &mut D) -> Result<Self, D::Error> {
373                 d.read_u32().map(Self::from_u32)
374             }
375         }
376         impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for $type {
377             fn encode(&self, e: &mut E) -> Result<(), E::Error> {
378                 e.emit_u32(self.private)
379             }
380         }
381     );
382
383     // Rewrite final without comma to one that includes comma
384     (@derives      [$($derives:ident,)*]
385      @attrs        [$(#[$attrs:meta])*]
386      @type         [$type:ident]
387      @max          [$max:expr]
388      @vis          [$v:vis]
389      @debug_format [$debug_format:tt]
390                    $name:ident = $constant:expr) => (
391         $crate::newtype_index!(
392             @derives      [$($derives,)*]
393             @attrs        [$(#[$attrs])*]
394             @type         [$type]
395             @max          [$max]
396             @vis          [$v]
397             @debug_format [$debug_format]
398                           $name = $constant,);
399     );
400
401     // Rewrite final const without comma to one that includes comma
402     (@derives      [$($derives:ident,)*]
403      @attrs        [$(#[$attrs:meta])*]
404      @type         [$type:ident]
405      @max          [$max:expr]
406      @vis          [$v:vis]
407      @debug_format [$debug_format:tt]
408                    $(#[doc = $doc:expr])*
409                    const $name:ident = $constant:expr) => (
410         $crate::newtype_index!(
411             @derives      [$($derives,)*]
412             @attrs        [$(#[$attrs])*]
413             @type         [$type]
414             @max          [$max]
415             @vis          [$v]
416             @debug_format [$debug_format]
417                           $(#[doc = $doc])* const $name = $constant,);
418     );
419
420     // Replace existing default for max
421     (@derives      [$($derives:ident,)*]
422      @attrs        [$(#[$attrs:meta])*]
423      @type         [$type:ident]
424      @max          [$_max:expr]
425      @vis          [$v:vis]
426      @debug_format [$debug_format:tt]
427                    MAX = $max:expr,
428                    $($tokens:tt)*) => (
429         $crate::newtype_index!(
430             @derives      [$($derives,)*]
431             @attrs        [$(#[$attrs])*]
432             @type         [$type]
433             @max          [$max]
434             @vis          [$v]
435             @debug_format [$debug_format]
436                           $($tokens)*);
437     );
438
439     // Replace existing default for debug_format
440     (@derives      [$($derives:ident,)*]
441      @attrs        [$(#[$attrs:meta])*]
442      @type         [$type:ident]
443      @max          [$max:expr]
444      @vis          [$v:vis]
445      @debug_format [$_debug_format:tt]
446                    DEBUG_FORMAT = $debug_format:tt,
447                    $($tokens:tt)*) => (
448         $crate::newtype_index!(
449             @derives      [$($derives,)*]
450             @attrs        [$(#[$attrs])*]
451             @type         [$type]
452             @max          [$max]
453             @vis          [$v]
454             @debug_format [$debug_format]
455                           $($tokens)*);
456     );
457
458     // Assign a user-defined constant
459     (@derives      [$($derives:ident,)*]
460      @attrs        [$(#[$attrs:meta])*]
461      @type         [$type:ident]
462      @max          [$max:expr]
463      @vis          [$v:vis]
464      @debug_format [$debug_format:tt]
465                    $(#[doc = $doc:expr])*
466                    const $name:ident = $constant:expr,
467                    $($tokens:tt)*) => (
468         $(#[doc = $doc])*
469         $v const $name: $type = $type::from_u32($constant);
470         $crate::newtype_index!(
471             @derives      [$($derives,)*]
472             @attrs        [$(#[$attrs])*]
473             @type         [$type]
474             @max          [$max]
475             @vis          [$v]
476             @debug_format [$debug_format]
477                           $($tokens)*);
478     );
479 }
480
481 #[derive(Clone, PartialEq, Eq, Hash)]
482 pub struct IndexVec<I: Idx, T> {
483     pub raw: Vec<T>,
484     _marker: PhantomData<fn(&I)>,
485 }
486
487 // Whether `IndexVec` is `Send` depends only on the data,
488 // not the phantom data.
489 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
490
491 impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for IndexVec<I, T> {
492     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
493         Encodable::encode(&self.raw, s)
494     }
495 }
496
497 impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for &IndexVec<I, T> {
498     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
499         Encodable::encode(&self.raw, s)
500     }
501 }
502
503 impl<D: Decoder, I: Idx, T: Decodable<D>> Decodable<D> for IndexVec<I, T> {
504     fn decode(d: &mut D) -> Result<Self, D::Error> {
505         Decodable::decode(d).map(|v| IndexVec { raw: v, _marker: PhantomData })
506     }
507 }
508
509 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
510     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
511         fmt::Debug::fmt(&self.raw, fmt)
512     }
513 }
514
515 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
516
517 impl<I: Idx, T> IndexVec<I, T> {
518     #[inline]
519     pub fn new() -> Self {
520         IndexVec { raw: Vec::new(), _marker: PhantomData }
521     }
522
523     #[inline]
524     pub fn from_raw(raw: Vec<T>) -> Self {
525         IndexVec { raw, _marker: PhantomData }
526     }
527
528     #[inline]
529     pub fn with_capacity(capacity: usize) -> Self {
530         IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
531     }
532
533     #[inline]
534     pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
535     where
536         T: Clone,
537     {
538         IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
539     }
540
541     #[inline]
542     pub fn from_elem_n(elem: T, n: usize) -> Self
543     where
544         T: Clone,
545     {
546         IndexVec { raw: vec![elem; n], _marker: PhantomData }
547     }
548
549     /// Create an `IndexVec` with `n` elements, where the value of each
550     /// element is the result of `func(i)`. (The underlying vector will
551     /// be allocated only once, with a capacity of at least `n`.)
552     #[inline]
553     pub fn from_fn_n(func: impl FnMut(I) -> T, n: usize) -> Self {
554         let indices = (0..n).map(I::new);
555         Self::from_raw(indices.map(func).collect())
556     }
557
558     #[inline]
559     pub fn push(&mut self, d: T) -> I {
560         let idx = I::new(self.len());
561         self.raw.push(d);
562         idx
563     }
564
565     #[inline]
566     pub fn pop(&mut self) -> Option<T> {
567         self.raw.pop()
568     }
569
570     #[inline]
571     pub fn len(&self) -> usize {
572         self.raw.len()
573     }
574
575     /// Gives the next index that will be assigned when `push` is
576     /// called.
577     #[inline]
578     pub fn next_index(&self) -> I {
579         I::new(self.len())
580     }
581
582     #[inline]
583     pub fn is_empty(&self) -> bool {
584         self.raw.is_empty()
585     }
586
587     #[inline]
588     pub fn into_iter(self) -> vec::IntoIter<T> {
589         self.raw.into_iter()
590     }
591
592     #[inline]
593     pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>> {
594         self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
595     }
596
597     #[inline]
598     pub fn iter(&self) -> slice::Iter<'_, T> {
599         self.raw.iter()
600     }
601
602     #[inline]
603     pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>> {
604         self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
605     }
606
607     #[inline]
608     pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
609         (0..self.len()).map(IntoIdx { _marker: PhantomData })
610     }
611
612     #[inline]
613     pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
614         self.raw.iter_mut()
615     }
616
617     #[inline]
618     pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>> {
619         self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
620     }
621
622     #[inline]
623     pub fn drain<'a, R: RangeBounds<usize>>(
624         &'a mut self,
625         range: R,
626     ) -> impl Iterator<Item = T> + 'a {
627         self.raw.drain(range)
628     }
629
630     #[inline]
631     pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
632         &'a mut self,
633         range: R,
634     ) -> impl Iterator<Item = (I, T)> + 'a {
635         self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
636     }
637
638     #[inline]
639     pub fn last(&self) -> Option<I> {
640         self.len().checked_sub(1).map(I::new)
641     }
642
643     #[inline]
644     pub fn shrink_to_fit(&mut self) {
645         self.raw.shrink_to_fit()
646     }
647
648     #[inline]
649     pub fn swap(&mut self, a: I, b: I) {
650         self.raw.swap(a.index(), b.index())
651     }
652
653     #[inline]
654     pub fn truncate(&mut self, a: usize) {
655         self.raw.truncate(a)
656     }
657
658     #[inline]
659     pub fn get(&self, index: I) -> Option<&T> {
660         self.raw.get(index.index())
661     }
662
663     #[inline]
664     pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
665         self.raw.get_mut(index.index())
666     }
667
668     /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
669     #[inline]
670     pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
671         let (ai, bi) = (a.index(), b.index());
672         assert!(ai != bi);
673
674         if ai < bi {
675             let (c1, c2) = self.raw.split_at_mut(bi);
676             (&mut c1[ai], &mut c2[0])
677         } else {
678             let (c2, c1) = self.pick2_mut(b, a);
679             (c1, c2)
680         }
681     }
682
683     /// Returns mutable references to three distinct elements or panics otherwise.
684     #[inline]
685     pub fn pick3_mut(&mut self, a: I, b: I, c: I) -> (&mut T, &mut T, &mut T) {
686         let (ai, bi, ci) = (a.index(), b.index(), c.index());
687         assert!(ai != bi && bi != ci && ci != ai);
688         let len = self.raw.len();
689         assert!(ai < len && bi < len && ci < len);
690         let ptr = self.raw.as_mut_ptr();
691         unsafe { (&mut *ptr.add(ai), &mut *ptr.add(bi), &mut *ptr.add(ci)) }
692     }
693
694     pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
695         IndexVec { raw: self.raw, _marker: PhantomData }
696     }
697 }
698
699 impl<I: Idx, T: Clone> IndexVec<I, T> {
700     /// Grows the index vector so that it contains an entry for
701     /// `elem`; if that is already true, then has no
702     /// effect. Otherwise, inserts new values as needed by invoking
703     /// `fill_value`.
704     #[inline]
705     pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
706         let min_new_len = elem.index() + 1;
707         if self.len() < min_new_len {
708             self.raw.resize_with(min_new_len, fill_value);
709         }
710     }
711
712     #[inline]
713     pub fn resize(&mut self, new_len: usize, value: T) {
714         self.raw.resize(new_len, value)
715     }
716
717     #[inline]
718     pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
719         let min_new_len = elem.index() + 1;
720         self.raw.resize_with(min_new_len, fill_value);
721     }
722 }
723
724 impl<I: Idx, T: Ord> IndexVec<I, T> {
725     #[inline]
726     pub fn binary_search(&self, value: &T) -> Result<I, I> {
727         match self.raw.binary_search(value) {
728             Ok(i) => Ok(Idx::new(i)),
729             Err(i) => Err(Idx::new(i)),
730         }
731     }
732 }
733
734 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
735     type Output = T;
736
737     #[inline]
738     fn index(&self, index: I) -> &T {
739         &self.raw[index.index()]
740     }
741 }
742
743 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
744     #[inline]
745     fn index_mut(&mut self, index: I) -> &mut T {
746         &mut self.raw[index.index()]
747     }
748 }
749
750 impl<I: Idx, T> Default for IndexVec<I, T> {
751     #[inline]
752     fn default() -> Self {
753         Self::new()
754     }
755 }
756
757 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
758     #[inline]
759     fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
760         self.raw.extend(iter);
761     }
762
763     #[inline]
764     fn extend_one(&mut self, item: T) {
765         self.raw.push(item);
766     }
767
768     #[inline]
769     fn extend_reserve(&mut self, additional: usize) {
770         self.raw.reserve(additional);
771     }
772 }
773
774 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
775     #[inline]
776     fn from_iter<J>(iter: J) -> Self
777     where
778         J: IntoIterator<Item = T>,
779     {
780         IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
781     }
782 }
783
784 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
785     type Item = T;
786     type IntoIter = vec::IntoIter<T>;
787
788     #[inline]
789     fn into_iter(self) -> vec::IntoIter<T> {
790         self.raw.into_iter()
791     }
792 }
793
794 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
795     type Item = &'a T;
796     type IntoIter = slice::Iter<'a, T>;
797
798     #[inline]
799     fn into_iter(self) -> slice::Iter<'a, T> {
800         self.raw.iter()
801     }
802 }
803
804 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
805     type Item = &'a mut T;
806     type IntoIter = slice::IterMut<'a, T>;
807
808     #[inline]
809     fn into_iter(self) -> slice::IterMut<'a, T> {
810         self.raw.iter_mut()
811     }
812 }
813
814 pub struct IntoIdx<I: Idx> {
815     _marker: PhantomData<fn(&I)>,
816 }
817 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
818     type Output = (I, T);
819
820     extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
821         (I::new(n), t)
822     }
823 }
824
825 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
826     extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
827         (I::new(n), t)
828     }
829 }
830
831 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
832     type Output = I;
833
834     extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
835         I::new(n)
836     }
837 }
838
839 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
840     extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {
841         I::new(n)
842     }
843 }
844
845 #[cfg(test)]
846 mod tests;