1 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
6 use std::iter::FromIterator;
7 use std::marker::PhantomData;
8 use std::ops::{Index, IndexMut, 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, rustc_attrs, trusted_step)]
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 assert!(value <= ($max as usize));
129 Self::from_u32_unchecked(value as u32)
134 $v const fn from_u32(value: u32) -> Self {
135 assert!(value <= $max);
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 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 // Safety: The implementation of `Step` upholds all invariants.
206 unsafe impl ::std::iter::TrustedStep for $type {}
208 impl From<$type> for u32 {
210 fn from(v: $type) -> u32 {
215 impl From<$type> for usize {
217 fn from(v: $type) -> usize {
222 impl From<usize> for $type {
224 fn from(value: usize) -> Self {
225 Self::from_usize(value)
229 impl From<u32> for $type {
231 fn from(value: u32) -> Self {
232 Self::from_u32(value)
236 $crate::newtype_index!(
238 @derives [$($derives,)*]
240 @debug_format [$debug_format]);
243 // base case for handle_debug where format is custom. No Debug implementation is emitted.
245 @derives [$($_derives:ident,)*]
247 @debug_format [custom]) => ();
249 // base case for handle_debug, no debug overrides found, so use default
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())
261 // Debug is requested for derive, don't generate any Debug implementation.
263 @derives [Debug, $($derives:ident,)*]
265 @debug_format [$debug_format:tt]) => ();
267 // It's not Debug, so just pop it off the front of the derives stack and check the rest.
269 @derives [$_derive:ident, $($derives:ident,)*]
271 @debug_format [$debug_format:tt]) => (
272 $crate::newtype_index!(
274 @derives [$($derives,)*]
276 @debug_format [$debug_format]);
279 // Append comma to end of derives list if it's missing
280 (@attrs [$(#[$attrs:meta])*]
284 @debug_format [$debug_format:tt]
285 derive [$($derives:ident),*]
287 $crate::newtype_index!(
288 @attrs [$(#[$attrs])*]
292 @debug_format [$debug_format]
293 derive [$($derives,)*]
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])*]
303 @debug_format [$debug_format:tt]
304 derive [$($derives:ident,)+]
307 $crate::newtype_index!(
308 @attrs [$(#[$attrs])*]
309 @derives [$($derives,)+]
313 @debug_format [$debug_format]
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])*]
323 @debug_format [$debug_format:tt]
324 derive [$($derives:ident,)+]
326 $crate::newtype_index!(
327 @derives [$($derives,)+]
328 @attrs [$(#[$attrs])*]
332 @debug_format [$debug_format]
334 $crate::newtype_index!(@serializable $type);
337 // The case where no derives are added, but encodable is overridden. Don't
338 // derive serialization traits
339 (@attrs [$(#[$attrs:meta])*]
343 @debug_format [$debug_format:tt]
346 $crate::newtype_index!(
348 @attrs [$(#[$attrs])*]
352 @debug_format [$debug_format]
356 // The case where no derives are added, add serialization derives by default
357 (@attrs [$(#[$attrs:meta])*]
361 @debug_format [$debug_format:tt]
363 $crate::newtype_index!(
365 @attrs [$(#[$attrs])*]
369 @debug_format [$debug_format]
371 $crate::newtype_index!(@serializable $type);
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)
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)
387 // Rewrite final without comma to one that includes comma
388 (@derives [$($derives:ident,)*]
389 @attrs [$(#[$attrs:meta])*]
393 @debug_format [$debug_format:tt]
394 $name:ident = $constant:expr) => (
395 $crate::newtype_index!(
396 @derives [$($derives,)*]
397 @attrs [$(#[$attrs])*]
401 @debug_format [$debug_format]
405 // Rewrite final const without comma to one that includes comma
406 (@derives [$($derives:ident,)*]
407 @attrs [$(#[$attrs:meta])*]
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])*]
420 @debug_format [$debug_format]
421 $(#[doc = $doc])* const $name = $constant,);
424 // Replace existing default for max
425 (@derives [$($derives:ident,)*]
426 @attrs [$(#[$attrs:meta])*]
430 @debug_format [$debug_format:tt]
433 $crate::newtype_index!(
434 @derives [$($derives,)*]
435 @attrs [$(#[$attrs])*]
439 @debug_format [$debug_format]
443 // Replace existing default for debug_format
444 (@derives [$($derives:ident,)*]
445 @attrs [$(#[$attrs:meta])*]
449 @debug_format [$_debug_format:tt]
450 DEBUG_FORMAT = $debug_format:tt,
452 $crate::newtype_index!(
453 @derives [$($derives,)*]
454 @attrs [$(#[$attrs])*]
458 @debug_format [$debug_format]
462 // Assign a user-defined constant
463 (@derives [$($derives:ident,)*]
464 @attrs [$(#[$attrs:meta])*]
468 @debug_format [$debug_format:tt]
469 $(#[doc = $doc:expr])*
470 const $name:ident = $constant:expr,
473 $v const $name: $type = $type::from_u32($constant);
474 $crate::newtype_index!(
475 @derives [$($derives,)*]
476 @attrs [$(#[$attrs])*]
480 @debug_format [$debug_format]
485 #[derive(Clone, PartialEq, Eq, Hash)]
486 pub struct IndexVec<I: Idx, T> {
488 _marker: PhantomData<fn(&I)>,
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 {}
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)
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)
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 })
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)
519 impl<I: Idx, T> IndexVec<I, T> {
521 pub fn new() -> Self {
522 IndexVec { raw: Vec::new(), _marker: PhantomData }
526 pub fn from_raw(raw: Vec<T>) -> Self {
527 IndexVec { raw, _marker: PhantomData }
531 pub fn with_capacity(capacity: usize) -> Self {
532 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
536 pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
540 IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
544 pub fn from_elem_n(elem: T, n: usize) -> Self
548 IndexVec { raw: vec![elem; n], _marker: PhantomData }
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`.)
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())
561 pub fn push(&mut self, d: T) -> I {
562 let idx = I::new(self.len());
568 pub fn pop(&mut self) -> Option<T> {
573 pub fn len(&self) -> usize {
577 /// Gives the next index that will be assigned when `push` is
580 pub fn next_index(&self) -> I {
585 pub fn is_empty(&self) -> bool {
590 pub fn into_iter(self) -> vec::IntoIter<T> {
595 pub fn into_iter_enumerated(
597 ) -> impl DoubleEndedIterator<Item = (I, T)> + ExactSizeIterator {
598 self.raw.into_iter().enumerate().map(|(n, t)| (I::new(n), t))
602 pub fn iter(&self) -> slice::Iter<'_, T> {
607 pub fn iter_enumerated(
609 ) -> impl DoubleEndedIterator<Item = (I, &T)> + ExactSizeIterator + '_ {
610 self.raw.iter().enumerate().map(|(n, t)| (I::new(n), t))
614 pub fn indices(&self) -> impl DoubleEndedIterator<Item = I> + ExactSizeIterator + 'static {
615 (0..self.len()).map(|n| I::new(n))
619 pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
624 pub fn iter_enumerated_mut(
626 ) -> impl DoubleEndedIterator<Item = (I, &mut T)> + ExactSizeIterator + '_ {
627 self.raw.iter_mut().enumerate().map(|(n, t)| (I::new(n), t))
631 pub fn drain<'a, R: RangeBounds<usize>>(
634 ) -> impl Iterator<Item = T> + 'a {
635 self.raw.drain(range)
639 pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
642 ) -> impl Iterator<Item = (I, T)> + 'a {
643 self.raw.drain(range).enumerate().map(|(n, t)| (I::new(n), t))
647 pub fn last(&self) -> Option<I> {
648 self.len().checked_sub(1).map(I::new)
652 pub fn shrink_to_fit(&mut self) {
653 self.raw.shrink_to_fit()
657 pub fn swap(&mut self, a: I, b: I) {
658 self.raw.swap(a.index(), b.index())
662 pub fn truncate(&mut self, a: usize) {
667 pub fn get(&self, index: I) -> Option<&T> {
668 self.raw.get(index.index())
672 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
673 self.raw.get_mut(index.index())
676 /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
678 pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
679 let (ai, bi) = (a.index(), b.index());
683 let (c1, c2) = self.raw.split_at_mut(bi);
684 (&mut c1[ai], &mut c2[0])
686 let (c2, c1) = self.pick2_mut(b, a);
691 /// Returns mutable references to three distinct elements or panics otherwise.
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)) }
702 pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
703 IndexVec { raw: self.raw, _marker: PhantomData }
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
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);
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);
725 /// `IndexVec` is often used as a map, so it provides some map-like APIs.
726 impl<I: Idx, T> IndexVec<I, Option<T>> {
728 pub fn insert(&mut self, index: I, value: T) -> Option<T> {
729 self.ensure_contains_elem(index, || None);
730 self[index].replace(value)
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)
740 pub fn remove(&mut self, index: I) -> Option<T> {
741 self.ensure_contains_elem(index, || None);
746 impl<I: Idx, T: Clone> IndexVec<I, T> {
748 pub fn resize(&mut self, new_len: usize, value: T) {
749 self.raw.resize(new_len, value)
753 impl<I: Idx, T: Ord> IndexVec<I, T> {
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)),
763 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
767 fn index(&self, index: I) -> &T {
768 &self.raw[index.index()]
772 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
774 fn index_mut(&mut self, index: I) -> &mut T {
775 &mut self.raw[index.index()]
779 impl<I: Idx, T> Default for IndexVec<I, T> {
781 fn default() -> Self {
786 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
788 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
789 self.raw.extend(iter);
793 fn extend_one(&mut self, item: T) {
798 fn extend_reserve(&mut self, additional: usize) {
799 self.raw.reserve(additional);
803 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
805 fn from_iter<J>(iter: J) -> Self
807 J: IntoIterator<Item = T>,
809 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
813 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
815 type IntoIter = vec::IntoIter<T>;
818 fn into_iter(self) -> vec::IntoIter<T> {
823 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
825 type IntoIter = slice::Iter<'a, T>;
828 fn into_iter(self) -> slice::Iter<'a, T> {
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>;
838 fn into_iter(self) -> slice::IterMut<'a, T> {