]> git.lizzy.rs Git - rust.git/blob - src/librustc_index/vec.rs
c5dedab979326ab6a6c2657c2db775e317de759c
[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,)+ RustcEncodable,]
324             @attrs        [$(#[$attrs])*]
325             @type         [$type]
326             @max          [$max]
327             @vis          [$v]
328             @debug_format [$debug_format]
329                           $($tokens)*);
330         $crate::newtype_index!(@decodable $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      [RustcEncodable,]
361             @attrs        [$(#[$attrs])*]
362             @type         [$type]
363             @max          [$max]
364             @vis          [$v]
365             @debug_format [$debug_format]
366                           $($tokens)*);
367         $crate::newtype_index!(@decodable $type);
368     );
369
370     (@decodable $type:ident) => (
371         impl ::rustc_serialize::Decodable for $type {
372             fn decode<D: ::rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
373                 d.read_u32().map(Self::from_u32)
374             }
375         }
376     );
377
378     // Rewrite final without comma to one that includes comma
379     (@derives      [$($derives:ident,)*]
380      @attrs        [$(#[$attrs:meta])*]
381      @type         [$type:ident]
382      @max          [$max:expr]
383      @vis          [$v:vis]
384      @debug_format [$debug_format:tt]
385                    $name:ident = $constant:expr) => (
386         $crate::newtype_index!(
387             @derives      [$($derives,)*]
388             @attrs        [$(#[$attrs])*]
389             @type         [$type]
390             @max          [$max]
391             @vis          [$v]
392             @debug_format [$debug_format]
393                           $name = $constant,);
394     );
395
396     // Rewrite final const without comma to one that includes comma
397     (@derives      [$($derives:ident,)*]
398      @attrs        [$(#[$attrs:meta])*]
399      @type         [$type:ident]
400      @max          [$max:expr]
401      @vis          [$v:vis]
402      @debug_format [$debug_format:tt]
403                    $(#[doc = $doc:expr])*
404                    const $name:ident = $constant:expr) => (
405         $crate::newtype_index!(
406             @derives      [$($derives,)*]
407             @attrs        [$(#[$attrs])*]
408             @type         [$type]
409             @max          [$max]
410             @vis          [$v]
411             @debug_format [$debug_format]
412                           $(#[doc = $doc])* const $name = $constant,);
413     );
414
415     // Replace existing default for max
416     (@derives      [$($derives:ident,)*]
417      @attrs        [$(#[$attrs:meta])*]
418      @type         [$type:ident]
419      @max          [$_max:expr]
420      @vis          [$v:vis]
421      @debug_format [$debug_format:tt]
422                    MAX = $max:expr,
423                    $($tokens:tt)*) => (
424         $crate::newtype_index!(
425             @derives      [$($derives,)*]
426             @attrs        [$(#[$attrs])*]
427             @type         [$type]
428             @max          [$max]
429             @vis          [$v]
430             @debug_format [$debug_format]
431                           $($tokens)*);
432     );
433
434     // Replace existing default for debug_format
435     (@derives      [$($derives:ident,)*]
436      @attrs        [$(#[$attrs:meta])*]
437      @type         [$type:ident]
438      @max          [$max:expr]
439      @vis          [$v:vis]
440      @debug_format [$_debug_format:tt]
441                    DEBUG_FORMAT = $debug_format:tt,
442                    $($tokens:tt)*) => (
443         $crate::newtype_index!(
444             @derives      [$($derives,)*]
445             @attrs        [$(#[$attrs])*]
446             @type         [$type]
447             @max          [$max]
448             @vis          [$v]
449             @debug_format [$debug_format]
450                           $($tokens)*);
451     );
452
453     // Assign a user-defined constant
454     (@derives      [$($derives:ident,)*]
455      @attrs        [$(#[$attrs:meta])*]
456      @type         [$type:ident]
457      @max          [$max:expr]
458      @vis          [$v:vis]
459      @debug_format [$debug_format:tt]
460                    $(#[doc = $doc:expr])*
461                    const $name:ident = $constant:expr,
462                    $($tokens:tt)*) => (
463         $(#[doc = $doc])*
464         $v const $name: $type = $type::from_u32($constant);
465         $crate::newtype_index!(
466             @derives      [$($derives,)*]
467             @attrs        [$(#[$attrs])*]
468             @type         [$type]
469             @max          [$max]
470             @vis          [$v]
471             @debug_format [$debug_format]
472                           $($tokens)*);
473     );
474 }
475
476 #[derive(Clone, PartialEq, Eq, Hash)]
477 pub struct IndexVec<I: Idx, T> {
478     pub raw: Vec<T>,
479     _marker: PhantomData<fn(&I)>,
480 }
481
482 // Whether `IndexVec` is `Send` depends only on the data,
483 // not the phantom data.
484 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
485
486 impl<I: Idx, T: Encodable> Encodable for IndexVec<I, T> {
487     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
488         Encodable::encode(&self.raw, s)
489     }
490 }
491
492 impl<I: Idx, T: Decodable> Decodable for IndexVec<I, T> {
493     fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
494         Decodable::decode(d).map(|v| IndexVec { raw: v, _marker: PhantomData })
495     }
496 }
497
498 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
499     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
500         fmt::Debug::fmt(&self.raw, fmt)
501     }
502 }
503
504 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
505
506 impl<I: Idx, T> IndexVec<I, T> {
507     #[inline]
508     pub fn new() -> Self {
509         IndexVec { raw: Vec::new(), _marker: PhantomData }
510     }
511
512     #[inline]
513     pub fn from_raw(raw: Vec<T>) -> Self {
514         IndexVec { raw, _marker: PhantomData }
515     }
516
517     #[inline]
518     pub fn with_capacity(capacity: usize) -> Self {
519         IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
520     }
521
522     #[inline]
523     pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
524     where
525         T: Clone,
526     {
527         IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
528     }
529
530     #[inline]
531     pub fn from_elem_n(elem: T, n: usize) -> Self
532     where
533         T: Clone,
534     {
535         IndexVec { raw: vec![elem; n], _marker: PhantomData }
536     }
537
538     /// Create an `IndexVec` with `n` elements, where the value of each
539     /// element is the result of `func(i)`. (The underlying vector will
540     /// be allocated only once, with a capacity of at least `n`.)
541     #[inline]
542     pub fn from_fn_n(func: impl FnMut(I) -> T, n: usize) -> Self {
543         let indices = (0..n).map(I::new);
544         Self::from_raw(indices.map(func).collect())
545     }
546
547     #[inline]
548     pub fn push(&mut self, d: T) -> I {
549         let idx = I::new(self.len());
550         self.raw.push(d);
551         idx
552     }
553
554     #[inline]
555     pub fn pop(&mut self) -> Option<T> {
556         self.raw.pop()
557     }
558
559     #[inline]
560     pub fn len(&self) -> usize {
561         self.raw.len()
562     }
563
564     /// Gives the next index that will be assigned when `push` is
565     /// called.
566     #[inline]
567     pub fn next_index(&self) -> I {
568         I::new(self.len())
569     }
570
571     #[inline]
572     pub fn is_empty(&self) -> bool {
573         self.raw.is_empty()
574     }
575
576     #[inline]
577     pub fn into_iter(self) -> vec::IntoIter<T> {
578         self.raw.into_iter()
579     }
580
581     #[inline]
582     pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>> {
583         self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
584     }
585
586     #[inline]
587     pub fn iter(&self) -> slice::Iter<'_, T> {
588         self.raw.iter()
589     }
590
591     #[inline]
592     pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>> {
593         self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
594     }
595
596     #[inline]
597     pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
598         (0..self.len()).map(IntoIdx { _marker: PhantomData })
599     }
600
601     #[inline]
602     pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
603         self.raw.iter_mut()
604     }
605
606     #[inline]
607     pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>> {
608         self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
609     }
610
611     #[inline]
612     pub fn drain<'a, R: RangeBounds<usize>>(
613         &'a mut self,
614         range: R,
615     ) -> impl Iterator<Item = T> + 'a {
616         self.raw.drain(range)
617     }
618
619     #[inline]
620     pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
621         &'a mut self,
622         range: R,
623     ) -> impl Iterator<Item = (I, T)> + 'a {
624         self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
625     }
626
627     #[inline]
628     pub fn last(&self) -> Option<I> {
629         self.len().checked_sub(1).map(I::new)
630     }
631
632     #[inline]
633     pub fn shrink_to_fit(&mut self) {
634         self.raw.shrink_to_fit()
635     }
636
637     #[inline]
638     pub fn swap(&mut self, a: I, b: I) {
639         self.raw.swap(a.index(), b.index())
640     }
641
642     #[inline]
643     pub fn truncate(&mut self, a: usize) {
644         self.raw.truncate(a)
645     }
646
647     #[inline]
648     pub fn get(&self, index: I) -> Option<&T> {
649         self.raw.get(index.index())
650     }
651
652     #[inline]
653     pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
654         self.raw.get_mut(index.index())
655     }
656
657     /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
658     #[inline]
659     pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
660         let (ai, bi) = (a.index(), b.index());
661         assert!(ai != bi);
662
663         if ai < bi {
664             let (c1, c2) = self.raw.split_at_mut(bi);
665             (&mut c1[ai], &mut c2[0])
666         } else {
667             let (c2, c1) = self.pick2_mut(b, a);
668             (c1, c2)
669         }
670     }
671
672     pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
673         IndexVec { raw: self.raw, _marker: PhantomData }
674     }
675 }
676
677 impl<I: Idx, T: Clone> IndexVec<I, T> {
678     /// Grows the index vector so that it contains an entry for
679     /// `elem`; if that is already true, then has no
680     /// effect. Otherwise, inserts new values as needed by invoking
681     /// `fill_value`.
682     #[inline]
683     pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
684         let min_new_len = elem.index() + 1;
685         if self.len() < min_new_len {
686             self.raw.resize_with(min_new_len, fill_value);
687         }
688     }
689
690     #[inline]
691     pub fn resize(&mut self, new_len: usize, value: T) {
692         self.raw.resize(new_len, value)
693     }
694
695     #[inline]
696     pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
697         let min_new_len = elem.index() + 1;
698         self.raw.resize_with(min_new_len, fill_value);
699     }
700 }
701
702 impl<I: Idx, T: Ord> IndexVec<I, T> {
703     #[inline]
704     pub fn binary_search(&self, value: &T) -> Result<I, I> {
705         match self.raw.binary_search(value) {
706             Ok(i) => Ok(Idx::new(i)),
707             Err(i) => Err(Idx::new(i)),
708         }
709     }
710 }
711
712 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
713     type Output = T;
714
715     #[inline]
716     fn index(&self, index: I) -> &T {
717         &self.raw[index.index()]
718     }
719 }
720
721 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
722     #[inline]
723     fn index_mut(&mut self, index: I) -> &mut T {
724         &mut self.raw[index.index()]
725     }
726 }
727
728 impl<I: Idx, T> Default for IndexVec<I, T> {
729     #[inline]
730     fn default() -> Self {
731         Self::new()
732     }
733 }
734
735 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
736     #[inline]
737     fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
738         self.raw.extend(iter);
739     }
740
741     #[inline]
742     fn extend_one(&mut self, item: T) {
743         self.raw.push(item);
744     }
745
746     #[inline]
747     fn extend_reserve(&mut self, additional: usize) {
748         self.raw.reserve(additional);
749     }
750 }
751
752 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
753     #[inline]
754     fn from_iter<J>(iter: J) -> Self
755     where
756         J: IntoIterator<Item = T>,
757     {
758         IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
759     }
760 }
761
762 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
763     type Item = T;
764     type IntoIter = vec::IntoIter<T>;
765
766     #[inline]
767     fn into_iter(self) -> vec::IntoIter<T> {
768         self.raw.into_iter()
769     }
770 }
771
772 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
773     type Item = &'a T;
774     type IntoIter = slice::Iter<'a, T>;
775
776     #[inline]
777     fn into_iter(self) -> slice::Iter<'a, T> {
778         self.raw.iter()
779     }
780 }
781
782 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
783     type Item = &'a mut T;
784     type IntoIter = slice::IterMut<'a, T>;
785
786     #[inline]
787     fn into_iter(self) -> slice::IterMut<'a, T> {
788         self.raw.iter_mut()
789     }
790 }
791
792 pub struct IntoIdx<I: Idx> {
793     _marker: PhantomData<fn(&I)>,
794 }
795 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
796     type Output = (I, T);
797
798     extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
799         (I::new(n), t)
800     }
801 }
802
803 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
804     extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
805         (I::new(n), t)
806     }
807 }
808
809 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
810     type Output = I;
811
812     extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
813         I::new(n)
814     }
815 }
816
817 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
818     extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {
819         I::new(n)
820     }
821 }
822
823 #[cfg(test)]
824 mod tests;