1 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
6 use std::iter::{self, FromIterator};
7 use std::marker::PhantomData;
8 use std::ops::{Index, IndexMut, Range, RangeBounds};
12 /// Represents some newtyped `usize` wrapper.
14 /// Purpose: avoid mixing indexes for different bitvector domains.
15 pub trait Idx: Copy + 'static + Ord + Debug + Hash {
16 fn new(idx: usize) -> Self;
18 fn index(self) -> usize;
20 fn increment_by(&mut self, amount: usize) {
21 *self = self.plus(amount);
24 fn plus(self, amount: usize) -> Self {
25 Self::new(self.index() + amount)
31 fn new(idx: usize) -> Self {
35 fn index(self) -> usize {
42 fn new(idx: usize) -> Self {
43 assert!(idx <= u32::MAX as usize);
47 fn index(self) -> usize {
52 /// Creates a struct type `S` that can be used as an index with
53 /// `IndexVec` and so on.
55 /// There are two ways of interacting with these indices:
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)`.
61 /// - Alternatively, you can use the methods `S::new(v)` and `s.index()`
62 /// to create/return a value.
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.
68 #[allow_internal_unstable(step_trait, step_trait_ext, rustc_attrs)]
69 macro_rules! newtype_index {
70 // ---- public rules ----
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])*]
78 // shave off 256 indices at the end to allow space for packing these indices into enums
81 @debug_format ["{}"]);
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])*]
90 // shave off 256 indices at the end to allow space for packing these indices into enums
97 // ---- private rules ----
99 // Base case, user-defined constants (if any) have already been defined
100 (@derives [$($derives:ident,)*]
101 @attrs [$(#[$attrs:meta])*]
105 @debug_format [$debug_format:tt]) => (
107 #[derive(Copy, PartialEq, Eq, Hash, PartialOrd, Ord, $($derives),*)]
108 #[rustc_layout_scalar_valid_range_end($max)]
113 impl Clone for $type {
115 fn clone(&self) -> Self {
121 $v const MAX_AS_U32: u32 = $max;
123 $v const MAX: Self = Self::from_u32($max);
126 $v const fn from_usize(value: usize) -> Self {
127 [()][(value > ($max as usize)) as usize];
129 Self::from_u32_unchecked(value as u32)
134 $v const fn from_u32(value: u32) -> Self {
135 [()][(value > $max) as usize];
137 Self::from_u32_unchecked(value)
142 $v const unsafe fn from_u32_unchecked(value: u32) -> Self {
143 Self { private: value }
146 /// Extracts the value of this index as an integer.
148 $v const fn index(self) -> usize {
152 /// Extracts the value of this index as a `u32`.
154 $v const fn as_u32(self) -> u32 {
158 /// Extracts the value of this index as a `usize`.
160 $v const fn as_usize(self) -> usize {
161 self.as_u32() as usize
165 impl std::ops::Add<usize> for $type {
168 fn add(self, other: usize) -> Self {
169 Self::from_usize(self.index() + other)
173 impl $crate::vec::Idx for $type {
175 fn new(value: usize) -> Self {
176 Self::from_usize(value)
180 fn index(self) -> usize {
185 unsafe impl ::std::iter::Step for $type {
187 fn steps_between(start: &Self, end: &Self) -> Option<usize> {
188 <usize as ::std::iter::Step>::steps_between(
189 &Self::index(*start),
195 fn forward_checked(start: Self, u: usize) -> Option<Self> {
196 Self::index(start).checked_add(u).map(Self::from_usize)
200 fn backward_checked(start: Self, u: usize) -> Option<Self> {
201 Self::index(start).checked_sub(u).map(Self::from_usize)
205 impl From<$type> for u32 {
207 fn from(v: $type) -> u32 {
212 impl From<$type> for usize {
214 fn from(v: $type) -> usize {
219 impl From<usize> for $type {
221 fn from(value: usize) -> Self {
222 Self::from_usize(value)
226 impl From<u32> for $type {
228 fn from(value: u32) -> Self {
229 Self::from_u32(value)
233 $crate::newtype_index!(
235 @derives [$($derives,)*]
237 @debug_format [$debug_format]);
240 // base case for handle_debug where format is custom. No Debug implementation is emitted.
242 @derives [$($_derives:ident,)*]
244 @debug_format [custom]) => ();
246 // base case for handle_debug, no debug overrides found, so use default
250 @debug_format [$debug_format:tt]) => (
251 impl ::std::fmt::Debug for $type {
252 fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
253 write!(fmt, $debug_format, self.as_u32())
258 // Debug is requested for derive, don't generate any Debug implementation.
260 @derives [Debug, $($derives:ident,)*]
262 @debug_format [$debug_format:tt]) => ();
264 // It's not Debug, so just pop it off the front of the derives stack and check the rest.
266 @derives [$_derive:ident, $($derives:ident,)*]
268 @debug_format [$debug_format:tt]) => (
269 $crate::newtype_index!(
271 @derives [$($derives,)*]
273 @debug_format [$debug_format]);
276 // Append comma to end of derives list if it's missing
277 (@attrs [$(#[$attrs:meta])*]
281 @debug_format [$debug_format:tt]
282 derive [$($derives:ident),*]
284 $crate::newtype_index!(
285 @attrs [$(#[$attrs])*]
289 @debug_format [$debug_format]
290 derive [$($derives,)*]
294 // By not including the @derives marker in this list nor in the default args, we can force it
295 // to come first if it exists. When encodable is custom, just use the derives list as-is.
296 (@attrs [$(#[$attrs:meta])*]
300 @debug_format [$debug_format:tt]
301 derive [$($derives:ident,)+]
304 $crate::newtype_index!(
305 @attrs [$(#[$attrs])*]
306 @derives [$($derives,)+]
310 @debug_format [$debug_format]
314 // By not including the @derives marker in this list nor in the default args, we can force it
315 // to come first if it exists. When encodable isn't custom, add serialization traits by default.
316 (@attrs [$(#[$attrs:meta])*]
320 @debug_format [$debug_format:tt]
321 derive [$($derives:ident,)+]
323 $crate::newtype_index!(
324 @derives [$($derives,)+]
325 @attrs [$(#[$attrs])*]
329 @debug_format [$debug_format]
331 $crate::newtype_index!(@serializable $type);
334 // The case where no derives are added, but encodable is overridden. Don't
335 // derive serialization traits
336 (@attrs [$(#[$attrs:meta])*]
340 @debug_format [$debug_format:tt]
343 $crate::newtype_index!(
345 @attrs [$(#[$attrs])*]
349 @debug_format [$debug_format]
353 // The case where no derives are added, add serialization derives by default
354 (@attrs [$(#[$attrs:meta])*]
358 @debug_format [$debug_format:tt]
360 $crate::newtype_index!(
362 @attrs [$(#[$attrs])*]
366 @debug_format [$debug_format]
368 $crate::newtype_index!(@serializable $type);
371 (@serializable $type:ident) => (
372 impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for $type {
373 fn decode(d: &mut D) -> Result<Self, D::Error> {
374 d.read_u32().map(Self::from_u32)
377 impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for $type {
378 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
379 e.emit_u32(self.private)
384 // Rewrite final without comma to one that includes comma
385 (@derives [$($derives:ident,)*]
386 @attrs [$(#[$attrs:meta])*]
390 @debug_format [$debug_format:tt]
391 $name:ident = $constant:expr) => (
392 $crate::newtype_index!(
393 @derives [$($derives,)*]
394 @attrs [$(#[$attrs])*]
398 @debug_format [$debug_format]
402 // Rewrite final const without comma to one that includes comma
403 (@derives [$($derives:ident,)*]
404 @attrs [$(#[$attrs:meta])*]
408 @debug_format [$debug_format:tt]
409 $(#[doc = $doc:expr])*
410 const $name:ident = $constant:expr) => (
411 $crate::newtype_index!(
412 @derives [$($derives,)*]
413 @attrs [$(#[$attrs])*]
417 @debug_format [$debug_format]
418 $(#[doc = $doc])* const $name = $constant,);
421 // Replace existing default for max
422 (@derives [$($derives:ident,)*]
423 @attrs [$(#[$attrs:meta])*]
427 @debug_format [$debug_format:tt]
430 $crate::newtype_index!(
431 @derives [$($derives,)*]
432 @attrs [$(#[$attrs])*]
436 @debug_format [$debug_format]
440 // Replace existing default for debug_format
441 (@derives [$($derives:ident,)*]
442 @attrs [$(#[$attrs:meta])*]
446 @debug_format [$_debug_format:tt]
447 DEBUG_FORMAT = $debug_format:tt,
449 $crate::newtype_index!(
450 @derives [$($derives,)*]
451 @attrs [$(#[$attrs])*]
455 @debug_format [$debug_format]
459 // Assign a user-defined constant
460 (@derives [$($derives:ident,)*]
461 @attrs [$(#[$attrs:meta])*]
465 @debug_format [$debug_format:tt]
466 $(#[doc = $doc:expr])*
467 const $name:ident = $constant:expr,
470 $v const $name: $type = $type::from_u32($constant);
471 $crate::newtype_index!(
472 @derives [$($derives,)*]
473 @attrs [$(#[$attrs])*]
477 @debug_format [$debug_format]
482 #[derive(Clone, PartialEq, Eq, Hash)]
483 pub struct IndexVec<I: Idx, T> {
485 _marker: PhantomData<fn(&I)>,
488 // Whether `IndexVec` is `Send` depends only on the data,
489 // not the phantom data.
490 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
492 impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for IndexVec<I, T> {
493 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
494 Encodable::encode(&self.raw, s)
498 impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for &IndexVec<I, T> {
499 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
500 Encodable::encode(&self.raw, s)
504 impl<D: Decoder, I: Idx, T: Decodable<D>> Decodable<D> for IndexVec<I, T> {
505 fn decode(d: &mut D) -> Result<Self, D::Error> {
506 Decodable::decode(d).map(|v| IndexVec { raw: v, _marker: PhantomData })
510 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
511 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
512 fmt::Debug::fmt(&self.raw, fmt)
516 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
518 impl<I: Idx, T> IndexVec<I, T> {
520 pub fn new() -> Self {
521 IndexVec { raw: Vec::new(), _marker: PhantomData }
525 pub fn from_raw(raw: Vec<T>) -> Self {
526 IndexVec { raw, _marker: PhantomData }
530 pub fn with_capacity(capacity: usize) -> Self {
531 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
535 pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
539 IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
543 pub fn from_elem_n(elem: T, n: usize) -> Self
547 IndexVec { raw: vec![elem; n], _marker: PhantomData }
550 /// Create an `IndexVec` with `n` elements, where the value of each
551 /// element is the result of `func(i)`. (The underlying vector will
552 /// be allocated only once, with a capacity of at least `n`.)
554 pub fn from_fn_n(func: impl FnMut(I) -> T, n: usize) -> Self {
555 let indices = (0..n).map(I::new);
556 Self::from_raw(indices.map(func).collect())
560 pub fn push(&mut self, d: T) -> I {
561 let idx = I::new(self.len());
567 pub fn pop(&mut self) -> Option<T> {
572 pub fn len(&self) -> usize {
576 /// Gives the next index that will be assigned when `push` is
579 pub fn next_index(&self) -> I {
584 pub fn is_empty(&self) -> bool {
589 pub fn into_iter(self) -> vec::IntoIter<T> {
594 pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>> {
595 self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
599 pub fn iter(&self) -> slice::Iter<'_, T> {
604 pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>> {
605 self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
609 pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
610 (0..self.len()).map(IntoIdx { _marker: PhantomData })
614 pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
619 pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>> {
620 self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
624 pub fn drain<'a, R: RangeBounds<usize>>(
627 ) -> impl Iterator<Item = T> + 'a {
628 self.raw.drain(range)
632 pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
635 ) -> impl Iterator<Item = (I, T)> + 'a {
636 self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
640 pub fn last(&self) -> Option<I> {
641 self.len().checked_sub(1).map(I::new)
645 pub fn shrink_to_fit(&mut self) {
646 self.raw.shrink_to_fit()
650 pub fn swap(&mut self, a: I, b: I) {
651 self.raw.swap(a.index(), b.index())
655 pub fn truncate(&mut self, a: usize) {
660 pub fn get(&self, index: I) -> Option<&T> {
661 self.raw.get(index.index())
665 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
666 self.raw.get_mut(index.index())
669 /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
671 pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
672 let (ai, bi) = (a.index(), b.index());
676 let (c1, c2) = self.raw.split_at_mut(bi);
677 (&mut c1[ai], &mut c2[0])
679 let (c2, c1) = self.pick2_mut(b, a);
684 /// Returns mutable references to three distinct elements or panics otherwise.
686 pub fn pick3_mut(&mut self, a: I, b: I, c: I) -> (&mut T, &mut T, &mut T) {
687 let (ai, bi, ci) = (a.index(), b.index(), c.index());
688 assert!(ai != bi && bi != ci && ci != ai);
689 let len = self.raw.len();
690 assert!(ai < len && bi < len && ci < len);
691 let ptr = self.raw.as_mut_ptr();
692 unsafe { (&mut *ptr.add(ai), &mut *ptr.add(bi), &mut *ptr.add(ci)) }
695 pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
696 IndexVec { raw: self.raw, _marker: PhantomData }
699 /// Grows the index vector so that it contains an entry for
700 /// `elem`; if that is already true, then has no
701 /// effect. Otherwise, inserts new values as needed by invoking
704 pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
705 let min_new_len = elem.index() + 1;
706 if self.len() < min_new_len {
707 self.raw.resize_with(min_new_len, fill_value);
712 pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
713 let min_new_len = elem.index() + 1;
714 self.raw.resize_with(min_new_len, fill_value);
718 impl<I: Idx, T: Clone> IndexVec<I, T> {
720 pub fn resize(&mut self, new_len: usize, value: T) {
721 self.raw.resize(new_len, value)
725 impl<I: Idx, T: Ord> IndexVec<I, T> {
727 pub fn binary_search(&self, value: &T) -> Result<I, I> {
728 match self.raw.binary_search(value) {
729 Ok(i) => Ok(Idx::new(i)),
730 Err(i) => Err(Idx::new(i)),
735 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
739 fn index(&self, index: I) -> &T {
740 &self.raw[index.index()]
744 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
746 fn index_mut(&mut self, index: I) -> &mut T {
747 &mut self.raw[index.index()]
751 impl<I: Idx, T> Default for IndexVec<I, T> {
753 fn default() -> Self {
758 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
760 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
761 self.raw.extend(iter);
765 fn extend_one(&mut self, item: T) {
770 fn extend_reserve(&mut self, additional: usize) {
771 self.raw.reserve(additional);
775 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
777 fn from_iter<J>(iter: J) -> Self
779 J: IntoIterator<Item = T>,
781 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
785 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
787 type IntoIter = vec::IntoIter<T>;
790 fn into_iter(self) -> vec::IntoIter<T> {
795 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
797 type IntoIter = slice::Iter<'a, T>;
800 fn into_iter(self) -> slice::Iter<'a, T> {
805 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
806 type Item = &'a mut T;
807 type IntoIter = slice::IterMut<'a, T>;
810 fn into_iter(self) -> slice::IterMut<'a, T> {
815 pub struct IntoIdx<I: Idx> {
816 _marker: PhantomData<fn(&I)>,
818 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
819 type Output = (I, T);
821 extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
826 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
827 extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
832 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
835 extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
840 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
841 extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {