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 // FIXME: replace with `assert!(value <= ($max as usize));` once `const_panic` is stable
128 [()][(value > ($max as usize)) as usize];
130 Self::from_u32_unchecked(value as u32)
135 $v const fn from_u32(value: u32) -> Self {
136 // FIXME: replace with `assert!(value <= $max);` once `const_panic` is stable
137 [()][(value > $max) as usize];
139 Self::from_u32_unchecked(value)
144 $v const unsafe fn from_u32_unchecked(value: u32) -> Self {
145 Self { private: value }
148 /// Extracts the value of this index as an integer.
150 $v const fn index(self) -> usize {
154 /// Extracts the value of this index as a `u32`.
156 $v const fn as_u32(self) -> u32 {
160 /// Extracts the value of this index as a `usize`.
162 $v const fn as_usize(self) -> usize {
163 self.as_u32() as usize
167 impl std::ops::Add<usize> for $type {
170 fn add(self, other: usize) -> Self {
171 Self::from_usize(self.index() + other)
175 impl $crate::vec::Idx for $type {
177 fn new(value: usize) -> Self {
178 Self::from_usize(value)
182 fn index(self) -> usize {
187 unsafe impl ::std::iter::Step for $type {
189 fn steps_between(start: &Self, end: &Self) -> Option<usize> {
190 <usize as ::std::iter::Step>::steps_between(
191 &Self::index(*start),
197 fn forward_checked(start: Self, u: usize) -> Option<Self> {
198 Self::index(start).checked_add(u).map(Self::from_usize)
202 fn backward_checked(start: Self, u: usize) -> Option<Self> {
203 Self::index(start).checked_sub(u).map(Self::from_usize)
207 impl From<$type> for u32 {
209 fn from(v: $type) -> u32 {
214 impl From<$type> for usize {
216 fn from(v: $type) -> usize {
221 impl From<usize> for $type {
223 fn from(value: usize) -> Self {
224 Self::from_usize(value)
228 impl From<u32> for $type {
230 fn from(value: u32) -> Self {
231 Self::from_u32(value)
235 $crate::newtype_index!(
237 @derives [$($derives,)*]
239 @debug_format [$debug_format]);
242 // base case for handle_debug where format is custom. No Debug implementation is emitted.
244 @derives [$($_derives:ident,)*]
246 @debug_format [custom]) => ();
248 // base case for handle_debug, no debug overrides found, so use default
252 @debug_format [$debug_format:tt]) => (
253 impl ::std::fmt::Debug for $type {
254 fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
255 write!(fmt, $debug_format, self.as_u32())
260 // Debug is requested for derive, don't generate any Debug implementation.
262 @derives [Debug, $($derives:ident,)*]
264 @debug_format [$debug_format:tt]) => ();
266 // It's not Debug, so just pop it off the front of the derives stack and check the rest.
268 @derives [$_derive:ident, $($derives:ident,)*]
270 @debug_format [$debug_format:tt]) => (
271 $crate::newtype_index!(
273 @derives [$($derives,)*]
275 @debug_format [$debug_format]);
278 // Append comma to end of derives list if it's missing
279 (@attrs [$(#[$attrs:meta])*]
283 @debug_format [$debug_format:tt]
284 derive [$($derives:ident),*]
286 $crate::newtype_index!(
287 @attrs [$(#[$attrs])*]
291 @debug_format [$debug_format]
292 derive [$($derives,)*]
296 // By not including the @derives marker in this list nor in the default args, we can force it
297 // to come first if it exists. When encodable is custom, just use the derives list as-is.
298 (@attrs [$(#[$attrs:meta])*]
302 @debug_format [$debug_format:tt]
303 derive [$($derives:ident,)+]
306 $crate::newtype_index!(
307 @attrs [$(#[$attrs])*]
308 @derives [$($derives,)+]
312 @debug_format [$debug_format]
316 // By not including the @derives marker in this list nor in the default args, we can force it
317 // to come first if it exists. When encodable isn't custom, add serialization traits by default.
318 (@attrs [$(#[$attrs:meta])*]
322 @debug_format [$debug_format:tt]
323 derive [$($derives:ident,)+]
325 $crate::newtype_index!(
326 @derives [$($derives,)+]
327 @attrs [$(#[$attrs])*]
331 @debug_format [$debug_format]
333 $crate::newtype_index!(@serializable $type);
336 // The case where no derives are added, but encodable is overridden. Don't
337 // derive serialization traits
338 (@attrs [$(#[$attrs:meta])*]
342 @debug_format [$debug_format:tt]
345 $crate::newtype_index!(
347 @attrs [$(#[$attrs])*]
351 @debug_format [$debug_format]
355 // The case where no derives are added, add serialization derives by default
356 (@attrs [$(#[$attrs:meta])*]
360 @debug_format [$debug_format:tt]
362 $crate::newtype_index!(
364 @attrs [$(#[$attrs])*]
368 @debug_format [$debug_format]
370 $crate::newtype_index!(@serializable $type);
373 (@serializable $type:ident) => (
374 impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for $type {
375 fn decode(d: &mut D) -> Result<Self, D::Error> {
376 d.read_u32().map(Self::from_u32)
379 impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for $type {
380 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
381 e.emit_u32(self.private)
386 // Rewrite final without comma to one that includes comma
387 (@derives [$($derives:ident,)*]
388 @attrs [$(#[$attrs:meta])*]
392 @debug_format [$debug_format:tt]
393 $name:ident = $constant:expr) => (
394 $crate::newtype_index!(
395 @derives [$($derives,)*]
396 @attrs [$(#[$attrs])*]
400 @debug_format [$debug_format]
404 // Rewrite final const without comma to one that includes comma
405 (@derives [$($derives:ident,)*]
406 @attrs [$(#[$attrs:meta])*]
410 @debug_format [$debug_format:tt]
411 $(#[doc = $doc:expr])*
412 const $name:ident = $constant:expr) => (
413 $crate::newtype_index!(
414 @derives [$($derives,)*]
415 @attrs [$(#[$attrs])*]
419 @debug_format [$debug_format]
420 $(#[doc = $doc])* const $name = $constant,);
423 // Replace existing default for max
424 (@derives [$($derives:ident,)*]
425 @attrs [$(#[$attrs:meta])*]
429 @debug_format [$debug_format:tt]
432 $crate::newtype_index!(
433 @derives [$($derives,)*]
434 @attrs [$(#[$attrs])*]
438 @debug_format [$debug_format]
442 // Replace existing default for debug_format
443 (@derives [$($derives:ident,)*]
444 @attrs [$(#[$attrs:meta])*]
448 @debug_format [$_debug_format:tt]
449 DEBUG_FORMAT = $debug_format:tt,
451 $crate::newtype_index!(
452 @derives [$($derives,)*]
453 @attrs [$(#[$attrs])*]
457 @debug_format [$debug_format]
461 // Assign a user-defined constant
462 (@derives [$($derives:ident,)*]
463 @attrs [$(#[$attrs:meta])*]
467 @debug_format [$debug_format:tt]
468 $(#[doc = $doc:expr])*
469 const $name:ident = $constant:expr,
472 $v const $name: $type = $type::from_u32($constant);
473 $crate::newtype_index!(
474 @derives [$($derives,)*]
475 @attrs [$(#[$attrs])*]
479 @debug_format [$debug_format]
484 #[derive(Clone, PartialEq, Eq, Hash)]
485 pub struct IndexVec<I: Idx, T> {
487 _marker: PhantomData<fn(&I)>,
490 // Whether `IndexVec` is `Send` depends only on the data,
491 // not the phantom data.
492 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
494 impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for IndexVec<I, T> {
495 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
496 Encodable::encode(&self.raw, s)
500 impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for &IndexVec<I, T> {
501 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
502 Encodable::encode(&self.raw, s)
506 impl<D: Decoder, I: Idx, T: Decodable<D>> Decodable<D> for IndexVec<I, T> {
507 fn decode(d: &mut D) -> Result<Self, D::Error> {
508 Decodable::decode(d).map(|v| IndexVec { raw: v, _marker: PhantomData })
512 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
513 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
514 fmt::Debug::fmt(&self.raw, fmt)
518 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
520 impl<I: Idx, T> IndexVec<I, T> {
522 pub fn new() -> Self {
523 IndexVec { raw: Vec::new(), _marker: PhantomData }
527 pub fn from_raw(raw: Vec<T>) -> Self {
528 IndexVec { raw, _marker: PhantomData }
532 pub fn with_capacity(capacity: usize) -> Self {
533 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
537 pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
541 IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
545 pub fn from_elem_n(elem: T, n: usize) -> Self
549 IndexVec { raw: vec![elem; n], _marker: PhantomData }
552 /// Create an `IndexVec` with `n` elements, where the value of each
553 /// element is the result of `func(i)`. (The underlying vector will
554 /// be allocated only once, with a capacity of at least `n`.)
556 pub fn from_fn_n(func: impl FnMut(I) -> T, n: usize) -> Self {
557 let indices = (0..n).map(I::new);
558 Self::from_raw(indices.map(func).collect())
562 pub fn push(&mut self, d: T) -> I {
563 let idx = I::new(self.len());
569 pub fn pop(&mut self) -> Option<T> {
574 pub fn len(&self) -> usize {
578 /// Gives the next index that will be assigned when `push` is
581 pub fn next_index(&self) -> I {
586 pub fn is_empty(&self) -> bool {
591 pub fn into_iter(self) -> vec::IntoIter<T> {
596 pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>> {
597 self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
601 pub fn iter(&self) -> slice::Iter<'_, T> {
606 pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>> {
607 self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
611 pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
612 (0..self.len()).map(IntoIdx { _marker: PhantomData })
616 pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
621 pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>> {
622 self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
626 pub fn drain<'a, R: RangeBounds<usize>>(
629 ) -> impl Iterator<Item = T> + 'a {
630 self.raw.drain(range)
634 pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
637 ) -> impl Iterator<Item = (I, T)> + 'a {
638 self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
642 pub fn last(&self) -> Option<I> {
643 self.len().checked_sub(1).map(I::new)
647 pub fn shrink_to_fit(&mut self) {
648 self.raw.shrink_to_fit()
652 pub fn swap(&mut self, a: I, b: I) {
653 self.raw.swap(a.index(), b.index())
657 pub fn truncate(&mut self, a: usize) {
662 pub fn get(&self, index: I) -> Option<&T> {
663 self.raw.get(index.index())
667 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
668 self.raw.get_mut(index.index())
671 /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
673 pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
674 let (ai, bi) = (a.index(), b.index());
678 let (c1, c2) = self.raw.split_at_mut(bi);
679 (&mut c1[ai], &mut c2[0])
681 let (c2, c1) = self.pick2_mut(b, a);
686 /// Returns mutable references to three distinct elements or panics otherwise.
688 pub fn pick3_mut(&mut self, a: I, b: I, c: I) -> (&mut T, &mut T, &mut T) {
689 let (ai, bi, ci) = (a.index(), b.index(), c.index());
690 assert!(ai != bi && bi != ci && ci != ai);
691 let len = self.raw.len();
692 assert!(ai < len && bi < len && ci < len);
693 let ptr = self.raw.as_mut_ptr();
694 unsafe { (&mut *ptr.add(ai), &mut *ptr.add(bi), &mut *ptr.add(ci)) }
697 pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
698 IndexVec { raw: self.raw, _marker: PhantomData }
701 /// Grows the index vector so that it contains an entry for
702 /// `elem`; if that is already true, then has no
703 /// effect. Otherwise, inserts new values as needed by invoking
706 pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
707 let min_new_len = elem.index() + 1;
708 if self.len() < min_new_len {
709 self.raw.resize_with(min_new_len, fill_value);
714 pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
715 let min_new_len = elem.index() + 1;
716 self.raw.resize_with(min_new_len, fill_value);
720 impl<I: Idx, T: Clone> IndexVec<I, T> {
722 pub fn resize(&mut self, new_len: usize, value: T) {
723 self.raw.resize(new_len, value)
727 impl<I: Idx, T: Ord> IndexVec<I, T> {
729 pub fn binary_search(&self, value: &T) -> Result<I, I> {
730 match self.raw.binary_search(value) {
731 Ok(i) => Ok(Idx::new(i)),
732 Err(i) => Err(Idx::new(i)),
737 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
741 fn index(&self, index: I) -> &T {
742 &self.raw[index.index()]
746 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
748 fn index_mut(&mut self, index: I) -> &mut T {
749 &mut self.raw[index.index()]
753 impl<I: Idx, T> Default for IndexVec<I, T> {
755 fn default() -> Self {
760 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
762 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
763 self.raw.extend(iter);
767 fn extend_one(&mut self, item: T) {
772 fn extend_reserve(&mut self, additional: usize) {
773 self.raw.reserve(additional);
777 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
779 fn from_iter<J>(iter: J) -> Self
781 J: IntoIterator<Item = T>,
783 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
787 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
789 type IntoIter = vec::IntoIter<T>;
792 fn into_iter(self) -> vec::IntoIter<T> {
797 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
799 type IntoIter = slice::Iter<'a, T>;
802 fn into_iter(self) -> slice::Iter<'a, T> {
807 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
808 type Item = &'a mut T;
809 type IntoIter = slice::IterMut<'a, T>;
812 fn into_iter(self) -> slice::IterMut<'a, T> {
817 pub struct IntoIdx<I: Idx> {
818 _marker: PhantomData<fn(&I)>,
820 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
821 type Output = (I, T);
823 extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
828 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
829 extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
834 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
837 extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
842 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
843 extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {