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 {
114 fn clone(&self) -> Self {
120 $v const MAX_AS_U32: u32 = $max;
122 $v const MAX: Self = Self::from_u32($max);
125 $v const fn from_usize(value: usize) -> Self {
126 assert!(value <= ($max as usize));
128 Self::from_u32_unchecked(value as u32)
133 $v const fn from_u32(value: u32) -> Self {
134 assert!(value <= $max);
136 Self::from_u32_unchecked(value)
141 $v const unsafe fn from_u32_unchecked(value: u32) -> Self {
142 Self { private: value }
145 /// Extracts the value of this index as an integer.
147 $v const fn index(self) -> usize {
151 /// Extracts the value of this index as a `u32`.
153 $v const fn as_u32(self) -> u32 {
157 /// Extracts the value of this index as a `usize`.
159 $v const fn as_usize(self) -> usize {
160 self.as_u32() as usize
164 impl std::ops::Add<usize> for $type {
167 fn add(self, other: usize) -> Self {
168 Self::from_usize(self.index() + other)
172 impl $crate::vec::Idx for $type {
174 fn new(value: usize) -> Self {
175 Self::from_usize(value)
179 fn index(self) -> usize {
184 unsafe impl ::std::iter::Step for $type {
186 fn steps_between(start: &Self, end: &Self) -> Option<usize> {
187 <usize as ::std::iter::Step>::steps_between(
188 &Self::index(*start),
194 fn forward_checked(start: Self, u: usize) -> Option<Self> {
195 Self::index(start).checked_add(u).map(Self::from_usize)
199 fn backward_checked(start: Self, u: usize) -> Option<Self> {
200 Self::index(start).checked_sub(u).map(Self::from_usize)
204 impl From<$type> for u32 {
206 fn from(v: $type) -> u32 {
211 impl From<$type> for usize {
213 fn from(v: $type) -> usize {
218 impl From<usize> for $type {
220 fn from(value: usize) -> Self {
221 Self::from_usize(value)
225 impl From<u32> for $type {
227 fn from(value: u32) -> Self {
228 Self::from_u32(value)
232 $crate::newtype_index!(
234 @derives [$($derives,)*]
236 @debug_format [$debug_format]);
239 // base case for handle_debug where format is custom. No Debug implementation is emitted.
241 @derives [$($_derives:ident,)*]
243 @debug_format [custom]) => ();
245 // base case for handle_debug, no debug overrides found, so use default
249 @debug_format [$debug_format:tt]) => (
250 impl ::std::fmt::Debug for $type {
251 fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
252 write!(fmt, $debug_format, self.as_u32())
257 // Debug is requested for derive, don't generate any Debug implementation.
259 @derives [Debug, $($derives:ident,)*]
261 @debug_format [$debug_format:tt]) => ();
263 // It's not Debug, so just pop it off the front of the derives stack and check the rest.
265 @derives [$_derive:ident, $($derives:ident,)*]
267 @debug_format [$debug_format:tt]) => (
268 $crate::newtype_index!(
270 @derives [$($derives,)*]
272 @debug_format [$debug_format]);
275 // Append comma to end of derives list if it's missing
276 (@attrs [$(#[$attrs:meta])*]
280 @debug_format [$debug_format:tt]
281 derive [$($derives:ident),*]
283 $crate::newtype_index!(
284 @attrs [$(#[$attrs])*]
288 @debug_format [$debug_format]
289 derive [$($derives,)*]
293 // By not including the @derives marker in this list nor in the default args, we can force it
294 // to come first if it exists. When encodable is custom, just use the derives list as-is.
295 (@attrs [$(#[$attrs:meta])*]
299 @debug_format [$debug_format:tt]
300 derive [$($derives:ident,)+]
303 $crate::newtype_index!(
304 @attrs [$(#[$attrs])*]
305 @derives [$($derives,)+]
309 @debug_format [$debug_format]
313 // By not including the @derives marker in this list nor in the default args, we can force it
314 // to come first if it exists. When encodable isn't custom, add serialization traits by default.
315 (@attrs [$(#[$attrs:meta])*]
319 @debug_format [$debug_format:tt]
320 derive [$($derives:ident,)+]
322 $crate::newtype_index!(
323 @derives [$($derives,)+]
324 @attrs [$(#[$attrs])*]
328 @debug_format [$debug_format]
330 $crate::newtype_index!(@serializable $type);
333 // The case where no derives are added, but encodable is overridden. Don't
334 // derive serialization traits
335 (@attrs [$(#[$attrs:meta])*]
339 @debug_format [$debug_format:tt]
342 $crate::newtype_index!(
344 @attrs [$(#[$attrs])*]
348 @debug_format [$debug_format]
352 // The case where no derives are added, add serialization derives by default
353 (@attrs [$(#[$attrs:meta])*]
357 @debug_format [$debug_format:tt]
359 $crate::newtype_index!(
361 @attrs [$(#[$attrs])*]
365 @debug_format [$debug_format]
367 $crate::newtype_index!(@serializable $type);
370 (@serializable $type:ident) => (
371 impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for $type {
372 fn decode(d: &mut D) -> Result<Self, D::Error> {
373 d.read_u32().map(Self::from_u32)
376 impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for $type {
377 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
378 e.emit_u32(self.private)
383 // Rewrite final without comma to one that includes comma
384 (@derives [$($derives:ident,)*]
385 @attrs [$(#[$attrs:meta])*]
389 @debug_format [$debug_format:tt]
390 $name:ident = $constant:expr) => (
391 $crate::newtype_index!(
392 @derives [$($derives,)*]
393 @attrs [$(#[$attrs])*]
397 @debug_format [$debug_format]
401 // Rewrite final const without comma to one that includes comma
402 (@derives [$($derives:ident,)*]
403 @attrs [$(#[$attrs:meta])*]
407 @debug_format [$debug_format:tt]
408 $(#[doc = $doc:expr])*
409 const $name:ident = $constant:expr) => (
410 $crate::newtype_index!(
411 @derives [$($derives,)*]
412 @attrs [$(#[$attrs])*]
416 @debug_format [$debug_format]
417 $(#[doc = $doc])* const $name = $constant,);
420 // Replace existing default for max
421 (@derives [$($derives:ident,)*]
422 @attrs [$(#[$attrs:meta])*]
426 @debug_format [$debug_format:tt]
429 $crate::newtype_index!(
430 @derives [$($derives,)*]
431 @attrs [$(#[$attrs])*]
435 @debug_format [$debug_format]
439 // Replace existing default for debug_format
440 (@derives [$($derives:ident,)*]
441 @attrs [$(#[$attrs:meta])*]
445 @debug_format [$_debug_format:tt]
446 DEBUG_FORMAT = $debug_format:tt,
448 $crate::newtype_index!(
449 @derives [$($derives,)*]
450 @attrs [$(#[$attrs])*]
454 @debug_format [$debug_format]
458 // Assign a user-defined constant
459 (@derives [$($derives:ident,)*]
460 @attrs [$(#[$attrs:meta])*]
464 @debug_format [$debug_format:tt]
465 $(#[doc = $doc:expr])*
466 const $name:ident = $constant:expr,
469 $v const $name: $type = $type::from_u32($constant);
470 $crate::newtype_index!(
471 @derives [$($derives,)*]
472 @attrs [$(#[$attrs])*]
476 @debug_format [$debug_format]
481 #[derive(Clone, PartialEq, Eq, Hash)]
482 pub struct IndexVec<I: Idx, T> {
484 _marker: PhantomData<fn(&I)>,
487 // Whether `IndexVec` is `Send` depends only on the data,
488 // not the phantom data.
489 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
491 impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for IndexVec<I, T> {
492 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
493 Encodable::encode(&self.raw, s)
497 impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for &IndexVec<I, T> {
498 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
499 Encodable::encode(&self.raw, s)
503 impl<D: Decoder, I: Idx, T: Decodable<D>> Decodable<D> for IndexVec<I, T> {
504 fn decode(d: &mut D) -> Result<Self, D::Error> {
505 Decodable::decode(d).map(|v| IndexVec { raw: v, _marker: PhantomData })
509 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
510 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
511 fmt::Debug::fmt(&self.raw, fmt)
515 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
517 impl<I: Idx, T> IndexVec<I, T> {
519 pub fn new() -> Self {
520 IndexVec { raw: Vec::new(), _marker: PhantomData }
524 pub fn from_raw(raw: Vec<T>) -> Self {
525 IndexVec { raw, _marker: PhantomData }
529 pub fn with_capacity(capacity: usize) -> Self {
530 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
534 pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
538 IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
542 pub fn from_elem_n(elem: T, n: usize) -> Self
546 IndexVec { raw: vec![elem; n], _marker: PhantomData }
549 /// Create an `IndexVec` with `n` elements, where the value of each
550 /// element is the result of `func(i)`. (The underlying vector will
551 /// be allocated only once, with a capacity of at least `n`.)
553 pub fn from_fn_n(func: impl FnMut(I) -> T, n: usize) -> Self {
554 let indices = (0..n).map(I::new);
555 Self::from_raw(indices.map(func).collect())
559 pub fn push(&mut self, d: T) -> I {
560 let idx = I::new(self.len());
566 pub fn pop(&mut self) -> Option<T> {
571 pub fn len(&self) -> usize {
575 /// Gives the next index that will be assigned when `push` is
578 pub fn next_index(&self) -> I {
583 pub fn is_empty(&self) -> bool {
588 pub fn into_iter(self) -> vec::IntoIter<T> {
593 pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>> {
594 self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
598 pub fn iter(&self) -> slice::Iter<'_, T> {
603 pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>> {
604 self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
608 pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
609 (0..self.len()).map(IntoIdx { _marker: PhantomData })
613 pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
618 pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>> {
619 self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
623 pub fn drain<'a, R: RangeBounds<usize>>(
626 ) -> impl Iterator<Item = T> + 'a {
627 self.raw.drain(range)
631 pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
634 ) -> impl Iterator<Item = (I, T)> + 'a {
635 self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
639 pub fn last(&self) -> Option<I> {
640 self.len().checked_sub(1).map(I::new)
644 pub fn shrink_to_fit(&mut self) {
645 self.raw.shrink_to_fit()
649 pub fn swap(&mut self, a: I, b: I) {
650 self.raw.swap(a.index(), b.index())
654 pub fn truncate(&mut self, a: usize) {
659 pub fn get(&self, index: I) -> Option<&T> {
660 self.raw.get(index.index())
664 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
665 self.raw.get_mut(index.index())
668 /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
670 pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
671 let (ai, bi) = (a.index(), b.index());
675 let (c1, c2) = self.raw.split_at_mut(bi);
676 (&mut c1[ai], &mut c2[0])
678 let (c2, c1) = self.pick2_mut(b, a);
683 /// Returns mutable references to three distinct elements or panics otherwise.
685 pub fn pick3_mut(&mut self, a: I, b: I, c: I) -> (&mut T, &mut T, &mut T) {
686 let (ai, bi, ci) = (a.index(), b.index(), c.index());
687 assert!(ai != bi && bi != ci && ci != ai);
688 let len = self.raw.len();
689 assert!(ai < len && bi < len && ci < len);
690 let ptr = self.raw.as_mut_ptr();
691 unsafe { (&mut *ptr.add(ai), &mut *ptr.add(bi), &mut *ptr.add(ci)) }
694 pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
695 IndexVec { raw: self.raw, _marker: PhantomData }
699 impl<I: Idx, T: Clone> IndexVec<I, T> {
700 /// Grows the index vector so that it contains an entry for
701 /// `elem`; if that is already true, then has no
702 /// effect. Otherwise, inserts new values as needed by invoking
705 pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
706 let min_new_len = elem.index() + 1;
707 if self.len() < min_new_len {
708 self.raw.resize_with(min_new_len, fill_value);
713 pub fn resize(&mut self, new_len: usize, value: T) {
714 self.raw.resize(new_len, value)
718 pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
719 let min_new_len = elem.index() + 1;
720 self.raw.resize_with(min_new_len, fill_value);
724 impl<I: Idx, T: Ord> IndexVec<I, T> {
726 pub fn binary_search(&self, value: &T) -> Result<I, I> {
727 match self.raw.binary_search(value) {
728 Ok(i) => Ok(Idx::new(i)),
729 Err(i) => Err(Idx::new(i)),
734 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
738 fn index(&self, index: I) -> &T {
739 &self.raw[index.index()]
743 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
745 fn index_mut(&mut self, index: I) -> &mut T {
746 &mut self.raw[index.index()]
750 impl<I: Idx, T> Default for IndexVec<I, T> {
752 fn default() -> Self {
757 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
759 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
760 self.raw.extend(iter);
764 fn extend_one(&mut self, item: T) {
769 fn extend_reserve(&mut self, additional: usize) {
770 self.raw.reserve(additional);
774 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
776 fn from_iter<J>(iter: J) -> Self
778 J: IntoIterator<Item = T>,
780 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
784 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
786 type IntoIter = vec::IntoIter<T>;
789 fn into_iter(self) -> vec::IntoIter<T> {
794 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
796 type IntoIter = slice::Iter<'a, T>;
799 fn into_iter(self) -> slice::Iter<'a, T> {
804 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
805 type Item = &'a mut T;
806 type IntoIter = slice::IterMut<'a, T>;
809 fn into_iter(self) -> slice::IterMut<'a, T> {
814 pub struct IntoIdx<I: Idx> {
815 _marker: PhantomData<fn(&I)>,
817 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
818 type Output = (I, T);
820 extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
825 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
826 extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
831 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
834 extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
839 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
840 extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {