]> git.lizzy.rs Git - rust.git/blob - src/librustc_index/vec.rs
4dde33283f575bab63edc8ec1b077798de874052
[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)`
540     #[inline]
541     pub fn from_fn_n(func: impl FnMut(I) -> T, n: usize) -> Self {
542         let indices = (0..n).map(I::new);
543         Self::from_raw(indices.map(func).collect())
544     }
545
546     #[inline]
547     pub fn push(&mut self, d: T) -> I {
548         let idx = I::new(self.len());
549         self.raw.push(d);
550         idx
551     }
552
553     #[inline]
554     pub fn pop(&mut self) -> Option<T> {
555         self.raw.pop()
556     }
557
558     #[inline]
559     pub fn len(&self) -> usize {
560         self.raw.len()
561     }
562
563     /// Gives the next index that will be assigned when `push` is
564     /// called.
565     #[inline]
566     pub fn next_index(&self) -> I {
567         I::new(self.len())
568     }
569
570     #[inline]
571     pub fn is_empty(&self) -> bool {
572         self.raw.is_empty()
573     }
574
575     #[inline]
576     pub fn into_iter(self) -> vec::IntoIter<T> {
577         self.raw.into_iter()
578     }
579
580     #[inline]
581     pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>> {
582         self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
583     }
584
585     #[inline]
586     pub fn iter(&self) -> slice::Iter<'_, T> {
587         self.raw.iter()
588     }
589
590     #[inline]
591     pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>> {
592         self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
593     }
594
595     #[inline]
596     pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
597         (0..self.len()).map(IntoIdx { _marker: PhantomData })
598     }
599
600     #[inline]
601     pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
602         self.raw.iter_mut()
603     }
604
605     #[inline]
606     pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>> {
607         self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
608     }
609
610     #[inline]
611     pub fn drain<'a, R: RangeBounds<usize>>(
612         &'a mut self,
613         range: R,
614     ) -> impl Iterator<Item = T> + 'a {
615         self.raw.drain(range)
616     }
617
618     #[inline]
619     pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
620         &'a mut self,
621         range: R,
622     ) -> impl Iterator<Item = (I, T)> + 'a {
623         self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
624     }
625
626     #[inline]
627     pub fn last(&self) -> Option<I> {
628         self.len().checked_sub(1).map(I::new)
629     }
630
631     #[inline]
632     pub fn shrink_to_fit(&mut self) {
633         self.raw.shrink_to_fit()
634     }
635
636     #[inline]
637     pub fn swap(&mut self, a: I, b: I) {
638         self.raw.swap(a.index(), b.index())
639     }
640
641     #[inline]
642     pub fn truncate(&mut self, a: usize) {
643         self.raw.truncate(a)
644     }
645
646     #[inline]
647     pub fn get(&self, index: I) -> Option<&T> {
648         self.raw.get(index.index())
649     }
650
651     #[inline]
652     pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
653         self.raw.get_mut(index.index())
654     }
655
656     /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
657     #[inline]
658     pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
659         let (ai, bi) = (a.index(), b.index());
660         assert!(ai != bi);
661
662         if ai < bi {
663             let (c1, c2) = self.raw.split_at_mut(bi);
664             (&mut c1[ai], &mut c2[0])
665         } else {
666             let (c2, c1) = self.pick2_mut(b, a);
667             (c1, c2)
668         }
669     }
670
671     pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
672         IndexVec { raw: self.raw, _marker: PhantomData }
673     }
674 }
675
676 impl<I: Idx, T: Clone> IndexVec<I, T> {
677     /// Grows the index vector so that it contains an entry for
678     /// `elem`; if that is already true, then has no
679     /// effect. Otherwise, inserts new values as needed by invoking
680     /// `fill_value`.
681     #[inline]
682     pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
683         let min_new_len = elem.index() + 1;
684         if self.len() < min_new_len {
685             self.raw.resize_with(min_new_len, fill_value);
686         }
687     }
688
689     #[inline]
690     pub fn resize(&mut self, new_len: usize, value: T) {
691         self.raw.resize(new_len, value)
692     }
693
694     #[inline]
695     pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
696         let min_new_len = elem.index() + 1;
697         self.raw.resize_with(min_new_len, fill_value);
698     }
699 }
700
701 impl<I: Idx, T: Ord> IndexVec<I, T> {
702     #[inline]
703     pub fn binary_search(&self, value: &T) -> Result<I, I> {
704         match self.raw.binary_search(value) {
705             Ok(i) => Ok(Idx::new(i)),
706             Err(i) => Err(Idx::new(i)),
707         }
708     }
709 }
710
711 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
712     type Output = T;
713
714     #[inline]
715     fn index(&self, index: I) -> &T {
716         &self.raw[index.index()]
717     }
718 }
719
720 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
721     #[inline]
722     fn index_mut(&mut self, index: I) -> &mut T {
723         &mut self.raw[index.index()]
724     }
725 }
726
727 impl<I: Idx, T> Default for IndexVec<I, T> {
728     #[inline]
729     fn default() -> Self {
730         Self::new()
731     }
732 }
733
734 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
735     #[inline]
736     fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
737         self.raw.extend(iter);
738     }
739
740     #[inline]
741     fn extend_one(&mut self, item: T) {
742         self.raw.push(item);
743     }
744
745     #[inline]
746     fn extend_reserve(&mut self, additional: usize) {
747         self.raw.reserve(additional);
748     }
749 }
750
751 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
752     #[inline]
753     fn from_iter<J>(iter: J) -> Self
754     where
755         J: IntoIterator<Item = T>,
756     {
757         IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
758     }
759 }
760
761 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
762     type Item = T;
763     type IntoIter = vec::IntoIter<T>;
764
765     #[inline]
766     fn into_iter(self) -> vec::IntoIter<T> {
767         self.raw.into_iter()
768     }
769 }
770
771 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
772     type Item = &'a T;
773     type IntoIter = slice::Iter<'a, T>;
774
775     #[inline]
776     fn into_iter(self) -> slice::Iter<'a, T> {
777         self.raw.iter()
778     }
779 }
780
781 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
782     type Item = &'a mut T;
783     type IntoIter = slice::IterMut<'a, T>;
784
785     #[inline]
786     fn into_iter(self) -> slice::IterMut<'a, T> {
787         self.raw.iter_mut()
788     }
789 }
790
791 pub struct IntoIdx<I: Idx> {
792     _marker: PhantomData<fn(&I)>,
793 }
794 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
795     type Output = (I, T);
796
797     extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
798         (I::new(n), t)
799     }
800 }
801
802 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
803     extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
804         (I::new(n), t)
805     }
806 }
807
808 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
809     type Output = I;
810
811     extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
812         I::new(n)
813     }
814 }
815
816 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
817     extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {
818         I::new(n)
819     }
820 }
821
822 #[cfg(test)]
823 mod tests;