2 use std::iter::{self, FromIterator};
4 use std::marker::PhantomData;
5 use std::ops::{Index, IndexMut, Range, RangeBounds};
11 use rustc_serialize as serialize;
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 unsafe { $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) => (
402 fn __decodable__impl__hack() {
403 mod __more_hacks_because__self_doesnt_work_in_functions {
404 extern crate serialize;
405 use self::serialize::{Decodable, Decoder};
406 impl Decodable for super::$type {
407 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
408 d.read_u32().map(Self::from)
416 // Rewrite final without comma to one that includes comma
417 (@derives [$($derives:ident,)*]
418 @attrs [$(#[$attrs:meta])*]
422 @debug_format [$debug_format:tt]
423 $name:ident = $constant:expr) => (
424 $crate::newtype_index!(
425 @derives [$($derives,)*]
426 @attrs [$(#[$attrs])*]
430 @debug_format [$debug_format]
434 // Rewrite final const without comma to one that includes comma
435 (@derives [$($derives:ident,)*]
436 @attrs [$(#[$attrs:meta])*]
440 @debug_format [$debug_format:tt]
441 $(#[doc = $doc:expr])*
442 const $name:ident = $constant:expr) => (
443 $crate::newtype_index!(
444 @derives [$($derives,)*]
445 @attrs [$(#[$attrs])*]
449 @debug_format [$debug_format]
450 $(#[doc = $doc])* const $name = $constant,);
453 // Replace existing default for max
454 (@derives [$($derives:ident,)*]
455 @attrs [$(#[$attrs:meta])*]
459 @debug_format [$debug_format:tt]
462 $crate::newtype_index!(
463 @derives [$($derives,)*]
464 @attrs [$(#[$attrs])*]
468 @debug_format [$debug_format]
472 // Replace existing default for debug_format
473 (@derives [$($derives:ident,)*]
474 @attrs [$(#[$attrs:meta])*]
478 @debug_format [$_debug_format:tt]
479 DEBUG_FORMAT = $debug_format:tt,
481 $crate::newtype_index!(
482 @derives [$($derives,)*]
483 @attrs [$(#[$attrs])*]
487 @debug_format [$debug_format]
491 // Assign a user-defined constant
492 (@derives [$($derives:ident,)*]
493 @attrs [$(#[$attrs:meta])*]
497 @debug_format [$debug_format:tt]
498 $(#[doc = $doc:expr])*
499 const $name:ident = $constant:expr,
502 pub const $name: $type = $type::from_u32_const($constant);
503 $crate::newtype_index!(
504 @derives [$($derives,)*]
505 @attrs [$(#[$attrs])*]
509 @debug_format [$debug_format]
514 #[derive(Clone, PartialEq, Eq, Hash)]
515 pub struct IndexVec<I: Idx, T> {
517 _marker: PhantomData<fn(&I)>
520 // Whether `IndexVec` is `Send` depends only on the data,
521 // not the phantom data.
522 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
524 impl<I: Idx, T: serialize::Encodable> serialize::Encodable for IndexVec<I, T> {
525 fn encode<S: serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
526 serialize::Encodable::encode(&self.raw, s)
530 impl<I: Idx, T: serialize::Decodable> serialize::Decodable for IndexVec<I, T> {
531 fn decode<D: serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
532 serialize::Decodable::decode(d).map(|v| {
533 IndexVec { raw: v, _marker: PhantomData }
538 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
539 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
540 fmt::Debug::fmt(&self.raw, fmt)
544 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
546 impl<I: Idx, T> IndexVec<I, T> {
548 pub fn new() -> Self {
549 IndexVec { raw: Vec::new(), _marker: PhantomData }
553 pub fn from_raw(raw: Vec<T>) -> Self {
554 IndexVec { raw, _marker: PhantomData }
558 pub fn with_capacity(capacity: usize) -> Self {
559 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
563 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
573 IndexVec { raw: vec![elem; n], _marker: PhantomData }
577 pub fn push(&mut self, d: T) -> I {
578 let idx = I::new(self.len());
584 pub fn pop(&mut self) -> Option<T> {
589 pub fn len(&self) -> usize {
593 /// Gives the next index that will be assigned when `push` is
596 pub fn next_index(&self) -> I {
601 pub fn is_empty(&self) -> bool {
606 pub fn into_iter(self) -> vec::IntoIter<T> {
611 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>>
624 self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
628 pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
629 (0..self.len()).map(IntoIdx { _marker: PhantomData })
633 pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
638 pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>>
640 self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
644 pub fn drain<'a, R: RangeBounds<usize>>(
645 &'a mut self, range: R) -> impl Iterator<Item=T> + 'a {
646 self.raw.drain(range)
650 pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
651 &'a mut self, range: R) -> impl Iterator<Item=(I, T)> + 'a {
652 self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
656 pub fn last(&self) -> Option<I> {
657 self.len().checked_sub(1).map(I::new)
661 pub fn shrink_to_fit(&mut self) {
662 self.raw.shrink_to_fit()
666 pub fn swap(&mut self, a: I, b: I) {
667 self.raw.swap(a.index(), b.index())
671 pub fn truncate(&mut self, a: usize) {
676 pub fn get(&self, index: I) -> Option<&T> {
677 self.raw.get(index.index())
681 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
682 self.raw.get_mut(index.index())
685 /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
687 pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
688 let (ai, bi) = (a.index(), b.index());
692 let (c1, c2) = self.raw.split_at_mut(bi);
693 (&mut c1[ai], &mut c2[0])
695 let (c2, c1) = self.pick2_mut(b, a);
700 pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
703 _marker: PhantomData,
708 impl<I: Idx, T: Clone> IndexVec<I, T> {
709 /// Grows the index vector so that it contains an entry for
710 /// `elem`; if that is already true, then has no
711 /// effect. Otherwise, inserts new values as needed by invoking
714 pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
715 let min_new_len = elem.index() + 1;
716 if self.len() < min_new_len {
717 self.raw.resize_with(min_new_len, fill_value);
722 pub fn resize(&mut self, new_len: usize, value: T) {
723 self.raw.resize(new_len, value)
727 pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
728 let min_new_len = elem.index() + 1;
729 self.raw.resize_with(min_new_len, fill_value);
733 impl<I: Idx, T: Ord> IndexVec<I, T> {
735 pub fn binary_search(&self, value: &T) -> Result<I, I> {
736 match self.raw.binary_search(value) {
737 Ok(i) => Ok(Idx::new(i)),
738 Err(i) => Err(Idx::new(i)),
743 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
747 fn index(&self, index: I) -> &T {
748 &self.raw[index.index()]
752 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
754 fn index_mut(&mut self, index: I) -> &mut T {
755 &mut self.raw[index.index()]
759 impl<I: Idx, T> Default for IndexVec<I, T> {
761 fn default() -> Self {
766 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
768 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
769 self.raw.extend(iter);
773 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
775 fn from_iter<J>(iter: J) -> Self where J: IntoIterator<Item=T> {
776 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
780 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
782 type IntoIter = vec::IntoIter<T>;
785 fn into_iter(self) -> vec::IntoIter<T> {
791 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
793 type IntoIter = slice::Iter<'a, T>;
796 fn into_iter(self) -> slice::Iter<'a, T> {
801 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
802 type Item = &'a mut T;
803 type IntoIter = slice::IterMut<'a, T>;
806 fn into_iter(self) -> slice::IterMut<'a, T> {
811 pub struct IntoIdx<I: Idx> { _marker: PhantomData<fn(&I)> }
812 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
813 type Output = (I, T);
815 extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
820 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
821 extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
826 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
829 extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
834 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
835 extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {