1 use rustc_serialize::{Encodable, Decodable, Encoder, Decoder};
4 use std::iter::{self, FromIterator};
6 use std::marker::PhantomData;
7 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 { idx }
34 fn index(self) -> usize { self }
39 fn new(idx: usize) -> Self { assert!(idx <= u32::MAX as usize); idx as u32 }
41 fn index(self) -> usize { self as usize }
44 /// Creates a struct type `S` that can be used as an index with
45 /// `IndexVec` and so on.
47 /// There are two ways of interacting with these indices:
49 /// - The `From` impls are the preferred way. So you can do
50 /// `S::from(v)` with a `usize` or `u32`. And you can convert back
51 /// to an integer with `u32::from(s)`.
53 /// - Alternatively, you can use the methods `S::new(v)` and `s.index()`
54 /// to create/return a value.
56 /// Internally, the index uses a u32, so the index must not exceed
57 /// `u32::MAX`. You can also customize things like the `Debug` impl,
58 /// what traits are derived, and so forth via the macro.
60 #[allow_internal_unstable(step_trait, rustc_attrs)]
61 macro_rules! newtype_index {
62 // ---- public rules ----
64 // Use default constants
65 ($(#[$attrs:meta])* $v:vis struct $name:ident { .. }) => (
66 $crate::newtype_index!(
67 // Leave out derives marker so we can use its absence to ensure it comes first
68 @attrs [$(#[$attrs])*]
70 // shave off 256 indices at the end to allow space for packing these indices into enums
73 @debug_format ["{}"]);
76 // Define any constants
77 ($(#[$attrs:meta])* $v:vis struct $name:ident { $($tokens:tt)+ }) => (
78 $crate::newtype_index!(
79 // Leave out derives marker so we can use its absence to ensure it comes first
80 @attrs [$(#[$attrs])*]
82 // shave off 256 indices at the end to allow space for packing these indices into enums
89 // ---- private rules ----
91 // Base case, user-defined constants (if any) have already been defined
92 (@derives [$($derives:ident,)*]
93 @attrs [$(#[$attrs:meta])*]
97 @debug_format [$debug_format:tt]) => (
99 #[derive(Copy, PartialEq, Eq, Hash, PartialOrd, Ord, $($derives),*)]
100 #[rustc_layout_scalar_valid_range_end($max)]
105 impl Clone for $type {
106 fn clone(&self) -> Self {
112 $v const MAX_AS_U32: u32 = $max;
114 $v const MAX: $type = $type::from_u32_const($max);
117 $v fn from_usize(value: usize) -> Self {
118 assert!(value <= ($max as usize));
120 $type::from_u32_unchecked(value as u32)
125 $v fn from_u32(value: u32) -> Self {
126 assert!(value <= $max);
128 $type::from_u32_unchecked(value)
132 /// Hacky variant of `from_u32` for use in constants.
133 /// This version checks the "max" constraint by using an
134 /// invalid array dereference.
136 $v const fn from_u32_const(value: u32) -> Self {
137 // This will fail at const eval time unless `value <=
138 // max` is true (in which case we get the index 0).
139 // It will also fail at runtime, of course, but in a
140 // kind of wacky way.
141 let _ = ["out of range value used"][
142 !(value <= $max) as usize
146 $type { private: value }
151 $v const unsafe fn from_u32_unchecked(value: u32) -> Self {
152 $type { private: value }
155 /// Extracts the value of this index as an integer.
157 $v fn index(self) -> usize {
161 /// Extracts the value of this index as a `u32`.
163 $v fn as_u32(self) -> u32 {
167 /// Extracts the value of this index as a `usize`.
169 $v fn as_usize(self) -> usize {
170 self.as_u32() as usize
174 impl std::ops::Add<usize> for $type {
177 fn add(self, other: usize) -> Self {
178 Self::new(self.index() + other)
184 fn new(value: usize) -> Self {
189 fn index(self) -> usize {
194 impl ::std::iter::Step for $type {
196 fn steps_between(start: &Self, end: &Self) -> Option<usize> {
197 <usize as ::std::iter::Step>::steps_between(
204 fn replace_one(&mut self) -> Self {
205 ::std::mem::replace(self, Self::new(1))
209 fn replace_zero(&mut self) -> Self {
210 ::std::mem::replace(self, Self::new(0))
214 fn add_one(&self) -> Self {
215 Self::new(Idx::index(*self) + 1)
219 fn sub_one(&self) -> Self {
220 Self::new(Idx::index(*self) - 1)
224 fn add_usize(&self, u: usize) -> Option<Self> {
225 Idx::index(*self).checked_add(u).map(Self::new)
229 fn sub_usize(&self, u: usize) -> Option<Self> {
230 Idx::index(*self).checked_sub(u).map(Self::new)
234 impl From<$type> for u32 {
236 fn from(v: $type) -> u32 {
241 impl From<$type> for usize {
243 fn from(v: $type) -> usize {
248 impl From<usize> for $type {
250 fn from(value: usize) -> Self {
251 $type::from_usize(value)
255 impl From<u32> for $type {
257 fn from(value: u32) -> Self {
258 $type::from_u32(value)
262 $crate::newtype_index!(
264 @derives [$($derives,)*]
266 @debug_format [$debug_format]);
269 // base case for handle_debug where format is custom. No Debug implementation is emitted.
271 @derives [$($_derives:ident,)*]
273 @debug_format [custom]) => ();
275 // base case for handle_debug, no debug overrides found, so use default
279 @debug_format [$debug_format:tt]) => (
280 impl ::std::fmt::Debug for $type {
281 fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
282 write!(fmt, $debug_format, self.as_u32())
287 // Debug is requested for derive, don't generate any Debug implementation.
289 @derives [Debug, $($derives:ident,)*]
291 @debug_format [$debug_format:tt]) => ();
293 // It's not Debug, so just pop it off the front of the derives stack and check the rest.
295 @derives [$_derive:ident, $($derives:ident,)*]
297 @debug_format [$debug_format:tt]) => (
298 $crate::newtype_index!(
300 @derives [$($derives,)*]
302 @debug_format [$debug_format]);
305 // Append comma to end of derives list if it's missing
306 (@attrs [$(#[$attrs:meta])*]
310 @debug_format [$debug_format:tt]
311 derive [$($derives:ident),*]
313 $crate::newtype_index!(
314 @attrs [$(#[$attrs])*]
318 @debug_format [$debug_format]
319 derive [$($derives,)*]
323 // By not including the @derives marker in this list nor in the default args, we can force it
324 // to come first if it exists. When encodable is custom, just use the derives list as-is.
325 (@attrs [$(#[$attrs:meta])*]
329 @debug_format [$debug_format:tt]
330 derive [$($derives:ident,)+]
333 $crate::newtype_index!(
334 @attrs [$(#[$attrs])*]
335 @derives [$($derives,)+]
339 @debug_format [$debug_format]
343 // By not including the @derives marker in this list nor in the default args, we can force it
344 // to come first if it exists. When encodable isn't custom, add serialization traits by default.
345 (@attrs [$(#[$attrs:meta])*]
349 @debug_format [$debug_format:tt]
350 derive [$($derives:ident,)+]
352 $crate::newtype_index!(
353 @derives [$($derives,)+ RustcEncodable,]
354 @attrs [$(#[$attrs])*]
358 @debug_format [$debug_format]
360 $crate::newtype_index!(@decodable $type);
363 // The case where no derives are added, but encodable is overridden. Don't
364 // derive serialization traits
365 (@attrs [$(#[$attrs:meta])*]
369 @debug_format [$debug_format:tt]
372 $crate::newtype_index!(
374 @attrs [$(#[$attrs])*]
378 @debug_format [$debug_format]
382 // The case where no derives are added, add serialization derives by default
383 (@attrs [$(#[$attrs:meta])*]
387 @debug_format [$debug_format:tt]
389 $crate::newtype_index!(
390 @derives [RustcEncodable,]
391 @attrs [$(#[$attrs])*]
395 @debug_format [$debug_format]
397 $crate::newtype_index!(@decodable $type);
400 (@decodable $type:ident) => (
401 impl ::rustc_serialize::Decodable for $type {
402 fn decode<D: ::rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
403 d.read_u32().map(Self::from)
408 // Rewrite final without comma to one that includes comma
409 (@derives [$($derives:ident,)*]
410 @attrs [$(#[$attrs:meta])*]
414 @debug_format [$debug_format:tt]
415 $name:ident = $constant:expr) => (
416 $crate::newtype_index!(
417 @derives [$($derives,)*]
418 @attrs [$(#[$attrs])*]
422 @debug_format [$debug_format]
426 // Rewrite final const without comma to one that includes comma
427 (@derives [$($derives:ident,)*]
428 @attrs [$(#[$attrs:meta])*]
432 @debug_format [$debug_format:tt]
433 $(#[doc = $doc:expr])*
434 const $name:ident = $constant:expr) => (
435 $crate::newtype_index!(
436 @derives [$($derives,)*]
437 @attrs [$(#[$attrs])*]
441 @debug_format [$debug_format]
442 $(#[doc = $doc])* const $name = $constant,);
445 // Replace existing default for max
446 (@derives [$($derives:ident,)*]
447 @attrs [$(#[$attrs:meta])*]
451 @debug_format [$debug_format:tt]
454 $crate::newtype_index!(
455 @derives [$($derives,)*]
456 @attrs [$(#[$attrs])*]
460 @debug_format [$debug_format]
464 // Replace existing default for debug_format
465 (@derives [$($derives:ident,)*]
466 @attrs [$(#[$attrs:meta])*]
470 @debug_format [$_debug_format:tt]
471 DEBUG_FORMAT = $debug_format:tt,
473 $crate::newtype_index!(
474 @derives [$($derives,)*]
475 @attrs [$(#[$attrs])*]
479 @debug_format [$debug_format]
483 // Assign a user-defined constant
484 (@derives [$($derives:ident,)*]
485 @attrs [$(#[$attrs:meta])*]
489 @debug_format [$debug_format:tt]
490 $(#[doc = $doc:expr])*
491 const $name:ident = $constant:expr,
494 pub const $name: $type = $type::from_u32_const($constant);
495 $crate::newtype_index!(
496 @derives [$($derives,)*]
497 @attrs [$(#[$attrs])*]
501 @debug_format [$debug_format]
506 #[derive(Clone, PartialEq, Eq, Hash)]
507 pub struct IndexVec<I: Idx, T> {
509 _marker: PhantomData<fn(&I)>
512 // Whether `IndexVec` is `Send` depends only on the data,
513 // not the phantom data.
514 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
516 impl<I: Idx, T: Encodable> Encodable for IndexVec<I, T> {
517 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
518 Encodable::encode(&self.raw, s)
522 impl<I: Idx, T: Decodable> Decodable for IndexVec<I, T> {
523 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
524 Decodable::decode(d).map(|v| {
525 IndexVec { raw: v, _marker: PhantomData }
530 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
531 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
532 fmt::Debug::fmt(&self.raw, fmt)
536 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
538 impl<I: Idx, T> IndexVec<I, T> {
540 pub fn new() -> Self {
541 IndexVec { raw: Vec::new(), _marker: PhantomData }
545 pub fn from_raw(raw: Vec<T>) -> Self {
546 IndexVec { raw, _marker: PhantomData }
550 pub fn with_capacity(capacity: usize) -> Self {
551 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
555 pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
558 IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
562 pub fn from_elem_n(elem: T, n: usize) -> Self
565 IndexVec { raw: vec![elem; n], _marker: PhantomData }
569 pub fn push(&mut self, d: T) -> I {
570 let idx = I::new(self.len());
576 pub fn pop(&mut self) -> Option<T> {
581 pub fn len(&self) -> usize {
585 /// Gives the next index that will be assigned when `push` is
588 pub fn next_index(&self) -> I {
593 pub fn is_empty(&self) -> bool {
598 pub fn into_iter(self) -> vec::IntoIter<T> {
603 pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>>
605 self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
609 pub fn iter(&self) -> slice::Iter<'_, T> {
614 pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>>
616 self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
620 pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
621 (0..self.len()).map(IntoIdx { _marker: PhantomData })
625 pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
630 pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>>
632 self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
636 pub fn drain<'a, R: RangeBounds<usize>>(
637 &'a mut self, range: R) -> impl Iterator<Item=T> + 'a {
638 self.raw.drain(range)
642 pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
643 &'a mut self, range: R) -> impl Iterator<Item=(I, T)> + 'a {
644 self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
648 pub fn last(&self) -> Option<I> {
649 self.len().checked_sub(1).map(I::new)
653 pub fn shrink_to_fit(&mut self) {
654 self.raw.shrink_to_fit()
658 pub fn swap(&mut self, a: I, b: I) {
659 self.raw.swap(a.index(), b.index())
663 pub fn truncate(&mut self, a: usize) {
668 pub fn get(&self, index: I) -> Option<&T> {
669 self.raw.get(index.index())
673 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
674 self.raw.get_mut(index.index())
677 /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
679 pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
680 let (ai, bi) = (a.index(), b.index());
684 let (c1, c2) = self.raw.split_at_mut(bi);
685 (&mut c1[ai], &mut c2[0])
687 let (c2, c1) = self.pick2_mut(b, a);
692 pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
695 _marker: PhantomData,
700 impl<I: Idx, T: Clone> IndexVec<I, T> {
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(&mut self, new_len: usize, value: T) {
715 self.raw.resize(new_len, 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 impl<I: Idx, T: Ord> IndexVec<I, T> {
727 pub fn binary_search(&self, value: &T) -> Result<I, I> {
728 match self.raw.binary_search(value) {
729 Ok(i) => Ok(Idx::new(i)),
730 Err(i) => Err(Idx::new(i)),
735 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
739 fn index(&self, index: I) -> &T {
740 &self.raw[index.index()]
744 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
746 fn index_mut(&mut self, index: I) -> &mut T {
747 &mut self.raw[index.index()]
751 impl<I: Idx, T> Default for IndexVec<I, T> {
753 fn default() -> Self {
758 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
760 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
761 self.raw.extend(iter);
765 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
767 fn from_iter<J>(iter: J) -> Self where J: IntoIterator<Item=T> {
768 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
772 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
774 type IntoIter = vec::IntoIter<T>;
777 fn into_iter(self) -> vec::IntoIter<T> {
783 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
785 type IntoIter = slice::Iter<'a, T>;
788 fn into_iter(self) -> slice::Iter<'a, T> {
793 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
794 type Item = &'a mut T;
795 type IntoIter = slice::IterMut<'a, T>;
798 fn into_iter(self) -> slice::IterMut<'a, T> {
803 pub struct IntoIdx<I: Idx> { _marker: PhantomData<fn(&I)> }
804 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
805 type Output = (I, T);
807 extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
812 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
813 extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
818 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
821 extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
826 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
827 extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {