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