]> git.lizzy.rs Git - rust.git/blob - src/librustc_index/vec.rs
Rollup merge of #71459 - divergentdave:pointer-offset-0x, r=RalfJung
[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, 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         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 replace_one(&mut self) -> Self {
195                 ::std::mem::replace(self, Self::from_u32(1))
196             }
197
198             #[inline]
199             fn replace_zero(&mut self) -> Self {
200                 ::std::mem::replace(self, Self::from_u32(0))
201             }
202
203             #[inline]
204             fn add_one(&self) -> Self {
205                 Self::from_usize(Self::index(*self) + 1)
206             }
207
208             #[inline]
209             fn sub_one(&self) -> Self {
210                 Self::from_usize(Self::index(*self) - 1)
211             }
212
213             #[inline]
214             fn add_usize(&self, u: usize) -> Option<Self> {
215                 Self::index(*self).checked_add(u).map(Self::from_usize)
216             }
217
218             #[inline]
219             fn sub_usize(&self, u: usize) -> Option<Self> {
220                 Self::index(*self).checked_sub(u).map(Self::from_usize)
221             }
222         }
223
224         impl From<$type> for u32 {
225             #[inline]
226             fn from(v: $type) -> u32 {
227                 v.as_u32()
228             }
229         }
230
231         impl From<$type> for usize {
232             #[inline]
233             fn from(v: $type) -> usize {
234                 v.as_usize()
235             }
236         }
237
238         impl From<usize> for $type {
239             #[inline]
240             fn from(value: usize) -> Self {
241                 Self::from_usize(value)
242             }
243         }
244
245         impl From<u32> for $type {
246             #[inline]
247             fn from(value: u32) -> Self {
248                 Self::from_u32(value)
249             }
250         }
251
252         $crate::newtype_index!(
253             @handle_debug
254             @derives      [$($derives,)*]
255             @type         [$type]
256             @debug_format [$debug_format]);
257     );
258
259     // base case for handle_debug where format is custom. No Debug implementation is emitted.
260     (@handle_debug
261      @derives      [$($_derives:ident,)*]
262      @type         [$type:ident]
263      @debug_format [custom]) => ();
264
265     // base case for handle_debug, no debug overrides found, so use default
266     (@handle_debug
267      @derives      []
268      @type         [$type:ident]
269      @debug_format [$debug_format:tt]) => (
270         impl ::std::fmt::Debug for $type {
271             fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
272                 write!(fmt, $debug_format, self.as_u32())
273             }
274         }
275     );
276
277     // Debug is requested for derive, don't generate any Debug implementation.
278     (@handle_debug
279      @derives      [Debug, $($derives:ident,)*]
280      @type         [$type:ident]
281      @debug_format [$debug_format:tt]) => ();
282
283     // It's not Debug, so just pop it off the front of the derives stack and check the rest.
284     (@handle_debug
285      @derives      [$_derive:ident, $($derives:ident,)*]
286      @type         [$type:ident]
287      @debug_format [$debug_format:tt]) => (
288         $crate::newtype_index!(
289             @handle_debug
290             @derives      [$($derives,)*]
291             @type         [$type]
292             @debug_format [$debug_format]);
293     );
294
295     // Append comma to end of derives list if it's missing
296     (@attrs        [$(#[$attrs:meta])*]
297      @type         [$type:ident]
298      @max          [$max:expr]
299      @vis          [$v:vis]
300      @debug_format [$debug_format:tt]
301                    derive [$($derives:ident),*]
302                    $($tokens:tt)*) => (
303         $crate::newtype_index!(
304             @attrs        [$(#[$attrs])*]
305             @type         [$type]
306             @max          [$max]
307             @vis          [$v]
308             @debug_format [$debug_format]
309                           derive [$($derives,)*]
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 is custom, just use the derives list as-is.
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                    ENCODABLE = custom
322                    $($tokens:tt)*) => (
323         $crate::newtype_index!(
324             @attrs        [$(#[$attrs])*]
325             @derives      [$($derives,)+]
326             @type         [$type]
327             @max          [$max]
328             @vis          [$v]
329             @debug_format [$debug_format]
330                           $($tokens)*);
331     );
332
333     // By not including the @derives marker in this list nor in the default args, we can force it
334     // to come first if it exists. When encodable isn't custom, add serialization traits by default.
335     (@attrs        [$(#[$attrs:meta])*]
336      @type         [$type:ident]
337      @max          [$max:expr]
338      @vis          [$v:vis]
339      @debug_format [$debug_format:tt]
340                    derive [$($derives:ident,)+]
341                    $($tokens:tt)*) => (
342         $crate::newtype_index!(
343             @derives      [$($derives,)+ RustcEncodable,]
344             @attrs        [$(#[$attrs])*]
345             @type         [$type]
346             @max          [$max]
347             @vis          [$v]
348             @debug_format [$debug_format]
349                           $($tokens)*);
350         $crate::newtype_index!(@decodable $type);
351     );
352
353     // The case where no derives are added, but encodable is overridden. Don't
354     // derive serialization traits
355     (@attrs        [$(#[$attrs:meta])*]
356      @type         [$type:ident]
357      @max          [$max:expr]
358      @vis          [$v:vis]
359      @debug_format [$debug_format:tt]
360                    ENCODABLE = custom
361                    $($tokens:tt)*) => (
362         $crate::newtype_index!(
363             @derives      []
364             @attrs        [$(#[$attrs])*]
365             @type         [$type]
366             @max          [$max]
367             @vis          [$v]
368             @debug_format [$debug_format]
369                           $($tokens)*);
370     );
371
372     // The case where no derives are added, add serialization derives by default
373     (@attrs        [$(#[$attrs:meta])*]
374      @type         [$type:ident]
375      @max          [$max:expr]
376      @vis          [$v:vis]
377      @debug_format [$debug_format:tt]
378                    $($tokens:tt)*) => (
379         $crate::newtype_index!(
380             @derives      [RustcEncodable,]
381             @attrs        [$(#[$attrs])*]
382             @type         [$type]
383             @max          [$max]
384             @vis          [$v]
385             @debug_format [$debug_format]
386                           $($tokens)*);
387         $crate::newtype_index!(@decodable $type);
388     );
389
390     (@decodable $type:ident) => (
391         impl ::rustc_serialize::Decodable for $type {
392             fn decode<D: ::rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
393                 d.read_u32().map(Self::from_u32)
394             }
395         }
396     );
397
398     // Rewrite final without comma to one that includes comma
399     (@derives      [$($derives:ident,)*]
400      @attrs        [$(#[$attrs:meta])*]
401      @type         [$type:ident]
402      @max          [$max:expr]
403      @vis          [$v:vis]
404      @debug_format [$debug_format:tt]
405                    $name:ident = $constant:expr) => (
406         $crate::newtype_index!(
407             @derives      [$($derives,)*]
408             @attrs        [$(#[$attrs])*]
409             @type         [$type]
410             @max          [$max]
411             @vis          [$v]
412             @debug_format [$debug_format]
413                           $name = $constant,);
414     );
415
416     // Rewrite final const without comma to one that includes comma
417     (@derives      [$($derives:ident,)*]
418      @attrs        [$(#[$attrs:meta])*]
419      @type         [$type:ident]
420      @max          [$max:expr]
421      @vis          [$v:vis]
422      @debug_format [$debug_format:tt]
423                    $(#[doc = $doc:expr])*
424                    const $name:ident = $constant:expr) => (
425         $crate::newtype_index!(
426             @derives      [$($derives,)*]
427             @attrs        [$(#[$attrs])*]
428             @type         [$type]
429             @max          [$max]
430             @vis          [$v]
431             @debug_format [$debug_format]
432                           $(#[doc = $doc])* const $name = $constant,);
433     );
434
435     // Replace existing default for max
436     (@derives      [$($derives:ident,)*]
437      @attrs        [$(#[$attrs:meta])*]
438      @type         [$type:ident]
439      @max          [$_max:expr]
440      @vis          [$v:vis]
441      @debug_format [$debug_format:tt]
442                    MAX = $max:expr,
443                    $($tokens:tt)*) => (
444         $crate::newtype_index!(
445             @derives      [$($derives,)*]
446             @attrs        [$(#[$attrs])*]
447             @type         [$type]
448             @max          [$max]
449             @vis          [$v]
450             @debug_format [$debug_format]
451                           $($tokens)*);
452     );
453
454     // Replace existing default for debug_format
455     (@derives      [$($derives:ident,)*]
456      @attrs        [$(#[$attrs:meta])*]
457      @type         [$type:ident]
458      @max          [$max:expr]
459      @vis          [$v:vis]
460      @debug_format [$_debug_format:tt]
461                    DEBUG_FORMAT = $debug_format:tt,
462                    $($tokens:tt)*) => (
463         $crate::newtype_index!(
464             @derives      [$($derives,)*]
465             @attrs        [$(#[$attrs])*]
466             @type         [$type]
467             @max          [$max]
468             @vis          [$v]
469             @debug_format [$debug_format]
470                           $($tokens)*);
471     );
472
473     // Assign a user-defined constant
474     (@derives      [$($derives:ident,)*]
475      @attrs        [$(#[$attrs:meta])*]
476      @type         [$type:ident]
477      @max          [$max:expr]
478      @vis          [$v:vis]
479      @debug_format [$debug_format:tt]
480                    $(#[doc = $doc:expr])*
481                    const $name:ident = $constant:expr,
482                    $($tokens:tt)*) => (
483         $(#[doc = $doc])*
484         $v const $name: $type = $type::from_u32($constant);
485         $crate::newtype_index!(
486             @derives      [$($derives,)*]
487             @attrs        [$(#[$attrs])*]
488             @type         [$type]
489             @max          [$max]
490             @vis          [$v]
491             @debug_format [$debug_format]
492                           $($tokens)*);
493     );
494 }
495
496 #[derive(Clone, PartialEq, Eq, Hash)]
497 pub struct IndexVec<I: Idx, T> {
498     pub raw: Vec<T>,
499     _marker: PhantomData<fn(&I)>,
500 }
501
502 // Whether `IndexVec` is `Send` depends only on the data,
503 // not the phantom data.
504 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
505
506 impl<I: Idx, T: Encodable> Encodable for IndexVec<I, T> {
507     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
508         Encodable::encode(&self.raw, s)
509     }
510 }
511
512 impl<I: Idx, T: Decodable> Decodable for IndexVec<I, T> {
513     fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
514         Decodable::decode(d).map(|v| IndexVec { raw: v, _marker: PhantomData })
515     }
516 }
517
518 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
519     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
520         fmt::Debug::fmt(&self.raw, fmt)
521     }
522 }
523
524 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
525
526 impl<I: Idx, T> IndexVec<I, T> {
527     #[inline]
528     pub fn new() -> Self {
529         IndexVec { raw: Vec::new(), _marker: PhantomData }
530     }
531
532     #[inline]
533     pub fn from_raw(raw: Vec<T>) -> Self {
534         IndexVec { raw, _marker: PhantomData }
535     }
536
537     #[inline]
538     pub fn with_capacity(capacity: usize) -> Self {
539         IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
540     }
541
542     #[inline]
543     pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
544     where
545         T: Clone,
546     {
547         IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
548     }
549
550     #[inline]
551     pub fn from_elem_n(elem: T, n: usize) -> Self
552     where
553         T: Clone,
554     {
555         IndexVec { raw: vec![elem; n], _marker: PhantomData }
556     }
557
558     /// Create an `IndexVec` with `n` elements, where the value of each
559     /// element is the result of `func(i)`
560     #[inline]
561     pub fn from_fn_n(func: impl FnMut(I) -> T, n: usize) -> Self {
562         let indices = (0..n).map(I::new);
563         Self::from_raw(indices.map(func).collect())
564     }
565
566     #[inline]
567     pub fn push(&mut self, d: T) -> I {
568         let idx = I::new(self.len());
569         self.raw.push(d);
570         idx
571     }
572
573     #[inline]
574     pub fn pop(&mut self) -> Option<T> {
575         self.raw.pop()
576     }
577
578     #[inline]
579     pub fn len(&self) -> usize {
580         self.raw.len()
581     }
582
583     /// Gives the next index that will be assigned when `push` is
584     /// called.
585     #[inline]
586     pub fn next_index(&self) -> I {
587         I::new(self.len())
588     }
589
590     #[inline]
591     pub fn is_empty(&self) -> bool {
592         self.raw.is_empty()
593     }
594
595     #[inline]
596     pub fn into_iter(self) -> vec::IntoIter<T> {
597         self.raw.into_iter()
598     }
599
600     #[inline]
601     pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>> {
602         self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
603     }
604
605     #[inline]
606     pub fn iter(&self) -> slice::Iter<'_, T> {
607         self.raw.iter()
608     }
609
610     #[inline]
611     pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>> {
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         self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
628     }
629
630     #[inline]
631     pub fn drain<'a, R: RangeBounds<usize>>(
632         &'a mut self,
633         range: R,
634     ) -> impl Iterator<Item = T> + 'a {
635         self.raw.drain(range)
636     }
637
638     #[inline]
639     pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
640         &'a mut self,
641         range: R,
642     ) -> impl Iterator<Item = (I, T)> + 'a {
643         self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
644     }
645
646     #[inline]
647     pub fn last(&self) -> Option<I> {
648         self.len().checked_sub(1).map(I::new)
649     }
650
651     #[inline]
652     pub fn shrink_to_fit(&mut self) {
653         self.raw.shrink_to_fit()
654     }
655
656     #[inline]
657     pub fn swap(&mut self, a: I, b: I) {
658         self.raw.swap(a.index(), b.index())
659     }
660
661     #[inline]
662     pub fn truncate(&mut self, a: usize) {
663         self.raw.truncate(a)
664     }
665
666     #[inline]
667     pub fn get(&self, index: I) -> Option<&T> {
668         self.raw.get(index.index())
669     }
670
671     #[inline]
672     pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
673         self.raw.get_mut(index.index())
674     }
675
676     /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
677     #[inline]
678     pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
679         let (ai, bi) = (a.index(), b.index());
680         assert!(ai != bi);
681
682         if ai < bi {
683             let (c1, c2) = self.raw.split_at_mut(bi);
684             (&mut c1[ai], &mut c2[0])
685         } else {
686             let (c2, c1) = self.pick2_mut(b, a);
687             (c1, c2)
688         }
689     }
690
691     pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
692         IndexVec { raw: self.raw, _marker: PhantomData }
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
764     where
765         J: IntoIterator<Item = T>,
766     {
767         IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
768     }
769 }
770
771 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
772     type Item = T;
773     type IntoIter = vec::IntoIter<T>;
774
775     #[inline]
776     fn into_iter(self) -> vec::IntoIter<T> {
777         self.raw.into_iter()
778     }
779 }
780
781 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
782     type Item = &'a T;
783     type IntoIter = slice::Iter<'a, T>;
784
785     #[inline]
786     fn into_iter(self) -> slice::Iter<'a, T> {
787         self.raw.iter()
788     }
789 }
790
791 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
792     type Item = &'a mut T;
793     type IntoIter = slice::IterMut<'a, T>;
794
795     #[inline]
796     fn into_iter(self) -> slice::IterMut<'a, T> {
797         self.raw.iter_mut()
798     }
799 }
800
801 pub struct IntoIdx<I: Idx> {
802     _marker: PhantomData<fn(&I)>,
803 }
804 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
805     type Output = (I, T);
806
807     extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
808         (I::new(n), t)
809     }
810 }
811
812 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
813     extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
814         (I::new(n), t)
815     }
816 }
817
818 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
819     type Output = I;
820
821     extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
822         I::new(n)
823     }
824 }
825
826 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
827     extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {
828         I::new(n)
829     }
830 }
831
832 #[cfg(test)]
833 mod tests;