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