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,)+ RustcEncodable,]
324 @attrs [$(#[$attrs])*]
328 @debug_format [$debug_format]
330 $crate::newtype_index!(@decodable $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!(
360 @derives [RustcEncodable,]
361 @attrs [$(#[$attrs])*]
365 @debug_format [$debug_format]
367 $crate::newtype_index!(@decodable $type);
370 (@decodable $type:ident) => (
371 impl ::rustc_serialize::Decodable for $type {
372 fn decode<D: ::rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
373 d.read_u32().map(Self::from_u32)
378 // Rewrite final without comma to one that includes comma
379 (@derives [$($derives:ident,)*]
380 @attrs [$(#[$attrs:meta])*]
384 @debug_format [$debug_format:tt]
385 $name:ident = $constant:expr) => (
386 $crate::newtype_index!(
387 @derives [$($derives,)*]
388 @attrs [$(#[$attrs])*]
392 @debug_format [$debug_format]
396 // Rewrite final const without comma to one that includes comma
397 (@derives [$($derives:ident,)*]
398 @attrs [$(#[$attrs:meta])*]
402 @debug_format [$debug_format:tt]
403 $(#[doc = $doc:expr])*
404 const $name:ident = $constant:expr) => (
405 $crate::newtype_index!(
406 @derives [$($derives,)*]
407 @attrs [$(#[$attrs])*]
411 @debug_format [$debug_format]
412 $(#[doc = $doc])* const $name = $constant,);
415 // Replace existing default for max
416 (@derives [$($derives:ident,)*]
417 @attrs [$(#[$attrs:meta])*]
421 @debug_format [$debug_format:tt]
424 $crate::newtype_index!(
425 @derives [$($derives,)*]
426 @attrs [$(#[$attrs])*]
430 @debug_format [$debug_format]
434 // Replace existing default for debug_format
435 (@derives [$($derives:ident,)*]
436 @attrs [$(#[$attrs:meta])*]
440 @debug_format [$_debug_format:tt]
441 DEBUG_FORMAT = $debug_format:tt,
443 $crate::newtype_index!(
444 @derives [$($derives,)*]
445 @attrs [$(#[$attrs])*]
449 @debug_format [$debug_format]
453 // Assign a user-defined constant
454 (@derives [$($derives:ident,)*]
455 @attrs [$(#[$attrs:meta])*]
459 @debug_format [$debug_format:tt]
460 $(#[doc = $doc:expr])*
461 const $name:ident = $constant:expr,
464 $v const $name: $type = $type::from_u32($constant);
465 $crate::newtype_index!(
466 @derives [$($derives,)*]
467 @attrs [$(#[$attrs])*]
471 @debug_format [$debug_format]
476 #[derive(Clone, PartialEq, Eq, Hash)]
477 pub struct IndexVec<I: Idx, T> {
479 _marker: PhantomData<fn(&I)>,
482 // Whether `IndexVec` is `Send` depends only on the data,
483 // not the phantom data.
484 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
486 impl<I: Idx, T: Encodable> Encodable for IndexVec<I, T> {
487 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
488 Encodable::encode(&self.raw, s)
492 impl<I: Idx, T: Decodable> Decodable for IndexVec<I, T> {
493 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
494 Decodable::decode(d).map(|v| IndexVec { raw: v, _marker: PhantomData })
498 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
499 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
500 fmt::Debug::fmt(&self.raw, fmt)
504 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
506 impl<I: Idx, T> IndexVec<I, T> {
508 pub fn new() -> Self {
509 IndexVec { raw: Vec::new(), _marker: PhantomData }
513 pub fn from_raw(raw: Vec<T>) -> Self {
514 IndexVec { raw, _marker: PhantomData }
518 pub fn with_capacity(capacity: usize) -> Self {
519 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
523 pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
527 IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
531 pub fn from_elem_n(elem: T, n: usize) -> Self
535 IndexVec { raw: vec![elem; n], _marker: PhantomData }
538 /// Create an `IndexVec` with `n` elements, where the value of each
539 /// element is the result of `func(i)`. (The underlying vector will
540 /// be allocated only once, with a capacity of at least `n`.)
542 pub fn from_fn_n(func: impl FnMut(I) -> T, n: usize) -> Self {
543 let indices = (0..n).map(I::new);
544 Self::from_raw(indices.map(func).collect())
548 pub fn push(&mut self, d: T) -> I {
549 let idx = I::new(self.len());
555 pub fn pop(&mut self) -> Option<T> {
560 pub fn len(&self) -> usize {
564 /// Gives the next index that will be assigned when `push` is
567 pub fn next_index(&self) -> I {
572 pub fn is_empty(&self) -> bool {
577 pub fn into_iter(self) -> vec::IntoIter<T> {
582 pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>> {
583 self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
587 pub fn iter(&self) -> slice::Iter<'_, T> {
592 pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>> {
593 self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
597 pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
598 (0..self.len()).map(IntoIdx { _marker: PhantomData })
602 pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
607 pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>> {
608 self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
612 pub fn drain<'a, R: RangeBounds<usize>>(
615 ) -> impl Iterator<Item = T> + 'a {
616 self.raw.drain(range)
620 pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
623 ) -> impl Iterator<Item = (I, T)> + 'a {
624 self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
628 pub fn last(&self) -> Option<I> {
629 self.len().checked_sub(1).map(I::new)
633 pub fn shrink_to_fit(&mut self) {
634 self.raw.shrink_to_fit()
638 pub fn swap(&mut self, a: I, b: I) {
639 self.raw.swap(a.index(), b.index())
643 pub fn truncate(&mut self, a: usize) {
648 pub fn get(&self, index: I) -> Option<&T> {
649 self.raw.get(index.index())
653 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
654 self.raw.get_mut(index.index())
657 /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
659 pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
660 let (ai, bi) = (a.index(), b.index());
664 let (c1, c2) = self.raw.split_at_mut(bi);
665 (&mut c1[ai], &mut c2[0])
667 let (c2, c1) = self.pick2_mut(b, a);
672 pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
673 IndexVec { raw: self.raw, _marker: PhantomData }
677 impl<I: Idx, T: Clone> IndexVec<I, T> {
678 /// Grows the index vector so that it contains an entry for
679 /// `elem`; if that is already true, then has no
680 /// effect. Otherwise, inserts new values as needed by invoking
683 pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
684 let min_new_len = elem.index() + 1;
685 if self.len() < min_new_len {
686 self.raw.resize_with(min_new_len, fill_value);
691 pub fn resize(&mut self, new_len: usize, value: T) {
692 self.raw.resize(new_len, value)
696 pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
697 let min_new_len = elem.index() + 1;
698 self.raw.resize_with(min_new_len, fill_value);
702 impl<I: Idx, T: Ord> IndexVec<I, T> {
704 pub fn binary_search(&self, value: &T) -> Result<I, I> {
705 match self.raw.binary_search(value) {
706 Ok(i) => Ok(Idx::new(i)),
707 Err(i) => Err(Idx::new(i)),
712 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
716 fn index(&self, index: I) -> &T {
717 &self.raw[index.index()]
721 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
723 fn index_mut(&mut self, index: I) -> &mut T {
724 &mut self.raw[index.index()]
728 impl<I: Idx, T> Default for IndexVec<I, T> {
730 fn default() -> Self {
735 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
737 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
738 self.raw.extend(iter);
742 fn extend_one(&mut self, item: T) {
747 fn extend_reserve(&mut self, additional: usize) {
748 self.raw.reserve(additional);
752 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
754 fn from_iter<J>(iter: J) -> Self
756 J: IntoIterator<Item = T>,
758 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
762 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
764 type IntoIter = vec::IntoIter<T>;
767 fn into_iter(self) -> vec::IntoIter<T> {
772 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
774 type IntoIter = slice::Iter<'a, T>;
777 fn into_iter(self) -> slice::Iter<'a, T> {
782 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
783 type Item = &'a mut T;
784 type IntoIter = slice::IterMut<'a, T>;
787 fn into_iter(self) -> slice::IterMut<'a, T> {
792 pub struct IntoIdx<I: Idx> {
793 _marker: PhantomData<fn(&I)>,
795 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
796 type Output = (I, T);
798 extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
803 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
804 extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
809 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
812 extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
817 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
818 extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {