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};
13 /// Represents some newtyped `usize` wrapper.
15 /// Purpose: avoid mixing indexes for different bitvector domains.
16 pub trait Idx: Copy + 'static + Ord + Debug + Hash {
17 fn new(idx: usize) -> Self;
19 fn index(self) -> usize;
21 fn increment_by(&mut self, amount: usize) {
22 *self = self.plus(amount);
25 fn plus(self, amount: usize) -> Self {
26 Self::new(self.index() + amount)
32 fn new(idx: usize) -> Self {
36 fn index(self) -> usize {
43 fn new(idx: usize) -> Self {
44 assert!(idx <= u32::MAX as usize);
48 fn index(self) -> usize {
53 /// Creates a struct type `S` that can be used as an index with
54 /// `IndexVec` and so on.
56 /// There are two ways of interacting with these indices:
58 /// - The `From` impls are the preferred way. So you can do
59 /// `S::from(v)` with a `usize` or `u32`. And you can convert back
60 /// to an integer with `u32::from(s)`.
62 /// - Alternatively, you can use the methods `S::new(v)` and `s.index()`
63 /// to create/return a value.
65 /// Internally, the index uses a u32, so the index must not exceed
66 /// `u32::MAX`. You can also customize things like the `Debug` impl,
67 /// what traits are derived, and so forth via the macro.
69 #[allow_internal_unstable(step_trait, rustc_attrs)]
70 macro_rules! newtype_index {
71 // ---- public rules ----
73 // Use default constants
74 ($(#[$attrs:meta])* $v:vis struct $name:ident { .. }) => (
75 $crate::newtype_index!(
76 // Leave out derives marker so we can use its absence to ensure it comes first
77 @attrs [$(#[$attrs])*]
79 // shave off 256 indices at the end to allow space for packing these indices into enums
82 @debug_format ["{}"]);
85 // Define any constants
86 ($(#[$attrs:meta])* $v:vis struct $name:ident { $($tokens:tt)+ }) => (
87 $crate::newtype_index!(
88 // Leave out derives marker so we can use its absence to ensure it comes first
89 @attrs [$(#[$attrs])*]
91 // shave off 256 indices at the end to allow space for packing these indices into enums
98 // ---- private rules ----
100 // Base case, user-defined constants (if any) have already been defined
101 (@derives [$($derives:ident,)*]
102 @attrs [$(#[$attrs:meta])*]
106 @debug_format [$debug_format:tt]) => (
108 #[derive(Copy, PartialEq, Eq, Hash, PartialOrd, Ord, $($derives),*)]
109 #[rustc_layout_scalar_valid_range_end($max)]
114 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_const($max);
126 $v fn from_usize(value: usize) -> Self {
127 assert!(value <= ($max as usize));
129 Self::from_u32_unchecked(value as u32)
134 $v fn from_u32(value: u32) -> Self {
135 assert!(value <= $max);
137 Self::from_u32_unchecked(value)
141 /// Hacky variant of `from_u32` for use in constants.
142 /// This version checks the "max" constraint by using an
143 /// invalid array dereference.
145 $v const fn from_u32_const(value: u32) -> Self {
146 // This will fail at const eval time unless `value <=
147 // max` is true (in which case we get the index 0).
148 // It will also fail at runtime, of course, but in a
149 // kind of wacky way.
150 let _ = ["out of range value used"][
151 !(value <= $max) as usize
155 Self { private: value }
160 $v const unsafe fn from_u32_unchecked(value: u32) -> Self {
161 Self { private: value }
164 /// Extracts the value of this index as an integer.
166 $v fn index(self) -> usize {
170 /// Extracts the value of this index as a `u32`.
172 $v fn as_u32(self) -> u32 {
176 /// Extracts the value of this index as a `usize`.
178 $v fn as_usize(self) -> usize {
179 self.as_u32() as usize
183 impl std::ops::Add<usize> for $type {
186 fn add(self, other: usize) -> Self {
187 Self::from_usize(self.index() + other)
191 impl $crate::vec::Idx for $type {
193 fn new(value: usize) -> Self {
194 Self::from_usize(value)
198 fn index(self) -> usize {
203 impl ::std::iter::Step for $type {
205 fn steps_between(start: &Self, end: &Self) -> Option<usize> {
206 <usize as ::std::iter::Step>::steps_between(
207 &Self::index(*start),
213 fn replace_one(&mut self) -> Self {
214 ::std::mem::replace(self, Self::from_u32(1))
218 fn replace_zero(&mut self) -> Self {
219 ::std::mem::replace(self, Self::from_u32(0))
223 fn add_one(&self) -> Self {
224 Self::from_usize(Self::index(*self) + 1)
228 fn sub_one(&self) -> Self {
229 Self::from_usize(Self::index(*self) - 1)
233 fn add_usize(&self, u: usize) -> Option<Self> {
234 Self::index(*self).checked_add(u).map(Self::from_usize)
238 fn sub_usize(&self, u: usize) -> Option<Self> {
239 Self::index(*self).checked_sub(u).map(Self::from_usize)
243 impl From<$type> for u32 {
245 fn from(v: $type) -> u32 {
250 impl From<$type> for usize {
252 fn from(v: $type) -> usize {
257 impl From<usize> for $type {
259 fn from(value: usize) -> Self {
260 Self::from_usize(value)
264 impl From<u32> for $type {
266 fn from(value: u32) -> Self {
267 Self::from_u32(value)
271 $crate::newtype_index!(
273 @derives [$($derives,)*]
275 @debug_format [$debug_format]);
278 // base case for handle_debug where format is custom. No Debug implementation is emitted.
280 @derives [$($_derives:ident,)*]
282 @debug_format [custom]) => ();
284 // base case for handle_debug, no debug overrides found, so use default
288 @debug_format [$debug_format:tt]) => (
289 impl ::std::fmt::Debug for $type {
290 fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
291 write!(fmt, $debug_format, self.as_u32())
296 // Debug is requested for derive, don't generate any Debug implementation.
298 @derives [Debug, $($derives:ident,)*]
300 @debug_format [$debug_format:tt]) => ();
302 // It's not Debug, so just pop it off the front of the derives stack and check the rest.
304 @derives [$_derive:ident, $($derives:ident,)*]
306 @debug_format [$debug_format:tt]) => (
307 $crate::newtype_index!(
309 @derives [$($derives,)*]
311 @debug_format [$debug_format]);
314 // Append comma to end of derives list if it's missing
315 (@attrs [$(#[$attrs:meta])*]
319 @debug_format [$debug_format:tt]
320 derive [$($derives:ident),*]
322 $crate::newtype_index!(
323 @attrs [$(#[$attrs])*]
327 @debug_format [$debug_format]
328 derive [$($derives,)*]
332 // By not including the @derives marker in this list nor in the default args, we can force it
333 // to come first if it exists. When encodable is custom, just use the derives list as-is.
334 (@attrs [$(#[$attrs:meta])*]
338 @debug_format [$debug_format:tt]
339 derive [$($derives:ident,)+]
342 $crate::newtype_index!(
343 @attrs [$(#[$attrs])*]
344 @derives [$($derives,)+]
348 @debug_format [$debug_format]
352 // By not including the @derives marker in this list nor in the default args, we can force it
353 // to come first if it exists. When encodable isn't custom, add serialization traits by default.
354 (@attrs [$(#[$attrs:meta])*]
358 @debug_format [$debug_format:tt]
359 derive [$($derives:ident,)+]
361 $crate::newtype_index!(
362 @derives [$($derives,)+ RustcEncodable,]
363 @attrs [$(#[$attrs])*]
367 @debug_format [$debug_format]
369 $crate::newtype_index!(@decodable $type);
372 // The case where no derives are added, but encodable is overridden. Don't
373 // derive serialization traits
374 (@attrs [$(#[$attrs:meta])*]
378 @debug_format [$debug_format:tt]
381 $crate::newtype_index!(
383 @attrs [$(#[$attrs])*]
387 @debug_format [$debug_format]
391 // The case where no derives are added, add serialization derives by default
392 (@attrs [$(#[$attrs:meta])*]
396 @debug_format [$debug_format:tt]
398 $crate::newtype_index!(
399 @derives [RustcEncodable,]
400 @attrs [$(#[$attrs])*]
404 @debug_format [$debug_format]
406 $crate::newtype_index!(@decodable $type);
409 (@decodable $type:ident) => (
410 impl ::rustc_serialize::Decodable for $type {
411 fn decode<D: ::rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
412 d.read_u32().map(Self::from_u32)
417 // Rewrite final without comma to one that includes comma
418 (@derives [$($derives:ident,)*]
419 @attrs [$(#[$attrs:meta])*]
423 @debug_format [$debug_format:tt]
424 $name:ident = $constant:expr) => (
425 $crate::newtype_index!(
426 @derives [$($derives,)*]
427 @attrs [$(#[$attrs])*]
431 @debug_format [$debug_format]
435 // Rewrite final const without comma to one that includes comma
436 (@derives [$($derives:ident,)*]
437 @attrs [$(#[$attrs:meta])*]
441 @debug_format [$debug_format:tt]
442 $(#[doc = $doc:expr])*
443 const $name:ident = $constant:expr) => (
444 $crate::newtype_index!(
445 @derives [$($derives,)*]
446 @attrs [$(#[$attrs])*]
450 @debug_format [$debug_format]
451 $(#[doc = $doc])* const $name = $constant,);
454 // Replace existing default for max
455 (@derives [$($derives:ident,)*]
456 @attrs [$(#[$attrs:meta])*]
460 @debug_format [$debug_format:tt]
463 $crate::newtype_index!(
464 @derives [$($derives,)*]
465 @attrs [$(#[$attrs])*]
469 @debug_format [$debug_format]
473 // Replace existing default for debug_format
474 (@derives [$($derives:ident,)*]
475 @attrs [$(#[$attrs:meta])*]
479 @debug_format [$_debug_format:tt]
480 DEBUG_FORMAT = $debug_format:tt,
482 $crate::newtype_index!(
483 @derives [$($derives,)*]
484 @attrs [$(#[$attrs])*]
488 @debug_format [$debug_format]
492 // Assign a user-defined constant
493 (@derives [$($derives:ident,)*]
494 @attrs [$(#[$attrs:meta])*]
498 @debug_format [$debug_format:tt]
499 $(#[doc = $doc:expr])*
500 const $name:ident = $constant:expr,
503 $v const $name: $type = $type::from_u32_const($constant);
504 $crate::newtype_index!(
505 @derives [$($derives,)*]
506 @attrs [$(#[$attrs])*]
510 @debug_format [$debug_format]
515 #[derive(Clone, PartialEq, Eq, Hash)]
516 pub struct IndexVec<I: Idx, T> {
518 _marker: PhantomData<fn(&I)>,
521 // Whether `IndexVec` is `Send` depends only on the data,
522 // not the phantom data.
523 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
525 impl<I: Idx, T: Encodable> Encodable for IndexVec<I, T> {
526 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
527 Encodable::encode(&self.raw, s)
531 impl<I: Idx, T: Decodable> Decodable for IndexVec<I, T> {
532 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
533 Decodable::decode(d).map(|v| IndexVec { raw: v, _marker: PhantomData })
537 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
538 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
539 fmt::Debug::fmt(&self.raw, fmt)
543 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
545 impl<I: Idx, T> IndexVec<I, T> {
547 pub fn new() -> Self {
548 IndexVec { raw: Vec::new(), _marker: PhantomData }
552 pub fn from_raw(raw: Vec<T>) -> Self {
553 IndexVec { raw, _marker: PhantomData }
557 pub fn with_capacity(capacity: usize) -> Self {
558 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
562 pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
566 IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
570 pub fn from_elem_n(elem: T, n: usize) -> Self
574 IndexVec { raw: vec![elem; n], _marker: PhantomData }
578 pub fn push(&mut self, d: T) -> I {
579 let idx = I::new(self.len());
585 pub fn pop(&mut self) -> Option<T> {
590 pub fn len(&self) -> usize {
594 /// Gives the next index that will be assigned when `push` is
597 pub fn next_index(&self) -> I {
602 pub fn is_empty(&self) -> bool {
607 pub fn into_iter(self) -> vec::IntoIter<T> {
612 pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>> {
613 self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
617 pub fn iter(&self) -> slice::Iter<'_, T> {
622 pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>> {
623 self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
627 pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
628 (0..self.len()).map(IntoIdx { _marker: PhantomData })
632 pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
637 pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>> {
638 self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
642 pub fn drain<'a, R: RangeBounds<usize>>(
645 ) -> impl Iterator<Item = T> + 'a {
646 self.raw.drain(range)
650 pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
653 ) -> impl Iterator<Item = (I, T)> + 'a {
654 self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
658 pub fn last(&self) -> Option<I> {
659 self.len().checked_sub(1).map(I::new)
663 pub fn shrink_to_fit(&mut self) {
664 self.raw.shrink_to_fit()
668 pub fn swap(&mut self, a: I, b: I) {
669 self.raw.swap(a.index(), b.index())
673 pub fn truncate(&mut self, a: usize) {
678 pub fn get(&self, index: I) -> Option<&T> {
679 self.raw.get(index.index())
683 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
684 self.raw.get_mut(index.index())
687 /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
689 pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
690 let (ai, bi) = (a.index(), b.index());
694 let (c1, c2) = self.raw.split_at_mut(bi);
695 (&mut c1[ai], &mut c2[0])
697 let (c2, c1) = self.pick2_mut(b, a);
702 pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
703 IndexVec { raw: self.raw, _marker: PhantomData }
707 impl<I: Idx, T: Clone> IndexVec<I, T> {
708 /// Grows the index vector so that it contains an entry for
709 /// `elem`; if that is already true, then has no
710 /// effect. Otherwise, inserts new values as needed by invoking
713 pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
714 let min_new_len = elem.index() + 1;
715 if self.len() < min_new_len {
716 self.raw.resize_with(min_new_len, fill_value);
721 pub fn resize(&mut self, new_len: usize, value: T) {
722 self.raw.resize(new_len, value)
726 pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
727 let min_new_len = elem.index() + 1;
728 self.raw.resize_with(min_new_len, fill_value);
732 impl<I: Idx, T: Ord> IndexVec<I, T> {
734 pub fn binary_search(&self, value: &T) -> Result<I, I> {
735 match self.raw.binary_search(value) {
736 Ok(i) => Ok(Idx::new(i)),
737 Err(i) => Err(Idx::new(i)),
742 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
746 fn index(&self, index: I) -> &T {
747 &self.raw[index.index()]
751 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
753 fn index_mut(&mut self, index: I) -> &mut T {
754 &mut self.raw[index.index()]
758 impl<I: Idx, T> Default for IndexVec<I, T> {
760 fn default() -> Self {
765 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
767 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
768 self.raw.extend(iter);
772 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
774 fn from_iter<J>(iter: J) -> Self
776 J: IntoIterator<Item = T>,
778 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
782 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
784 type IntoIter = vec::IntoIter<T>;
787 fn into_iter(self) -> vec::IntoIter<T> {
792 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
794 type IntoIter = slice::Iter<'a, T>;
797 fn into_iter(self) -> slice::Iter<'a, T> {
802 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
803 type Item = &'a mut T;
804 type IntoIter = slice::IterMut<'a, T>;
807 fn into_iter(self) -> slice::IterMut<'a, T> {
812 pub struct IntoIdx<I: Idx> {
813 _marker: PhantomData<fn(&I)>,
815 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
816 type Output = (I, T);
818 extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
823 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
824 extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
829 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
832 extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
837 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
838 extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {