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 /// Maximum value the index can take, as a `u32`.
122 $v const MAX_AS_U32: u32 = $max;
124 /// Maximum value the index can take.
125 $v const MAX: Self = Self::from_u32($max);
127 /// Creates a new index from a given `usize`.
131 /// Will panic if `value` exceeds `MAX`.
133 $v const fn from_usize(value: usize) -> Self {
134 assert!(value <= ($max as usize));
135 // SAFETY: We just checked that `value <= max`.
137 Self::from_u32_unchecked(value as u32)
141 /// Creates a new index from a given `u32`.
145 /// Will panic if `value` exceeds `MAX`.
147 $v const fn from_u32(value: u32) -> Self {
148 assert!(value <= $max);
149 // SAFETY: We just checked that `value <= max`.
151 Self::from_u32_unchecked(value)
155 /// Creates a new index from a given `u32`.
159 /// The provided value must be less than or equal to the maximum value for the newtype.
160 /// Providing a value outside this range is undefined due to layout restrictions.
162 /// Prefer using `from_u32`.
164 $v const unsafe fn from_u32_unchecked(value: u32) -> Self {
165 Self { private: value }
168 /// Extracts the value of this index as a `usize`.
170 $v const fn index(self) -> usize {
174 /// Extracts the value of this index as a `u32`.
176 $v const fn as_u32(self) -> u32 {
180 /// Extracts the value of this index as a `usize`.
182 $v const fn as_usize(self) -> usize {
183 self.as_u32() as usize
187 impl std::ops::Add<usize> for $type {
190 fn add(self, other: usize) -> Self {
191 Self::from_usize(self.index() + other)
195 impl $crate::vec::Idx for $type {
197 fn new(value: usize) -> Self {
198 Self::from_usize(value)
202 fn index(self) -> usize {
207 impl ::std::iter::Step for $type {
209 fn steps_between(start: &Self, end: &Self) -> Option<usize> {
210 <usize as ::std::iter::Step>::steps_between(
211 &Self::index(*start),
217 fn forward_checked(start: Self, u: usize) -> Option<Self> {
218 Self::index(start).checked_add(u).map(Self::from_usize)
222 fn backward_checked(start: Self, u: usize) -> Option<Self> {
223 Self::index(start).checked_sub(u).map(Self::from_usize)
227 // Safety: The implementation of `Step` upholds all invariants.
228 unsafe impl ::std::iter::TrustedStep for $type {}
230 impl From<$type> for u32 {
232 fn from(v: $type) -> u32 {
237 impl From<$type> for usize {
239 fn from(v: $type) -> usize {
244 impl From<usize> for $type {
246 fn from(value: usize) -> Self {
247 Self::from_usize(value)
251 impl From<u32> for $type {
253 fn from(value: u32) -> Self {
254 Self::from_u32(value)
258 $crate::newtype_index!(
260 @derives [$($derives,)*]
262 @debug_format [$debug_format]);
265 // base case for handle_debug where format is custom. No Debug implementation is emitted.
267 @derives [$($_derives:ident,)*]
269 @debug_format [custom]) => ();
271 // base case for handle_debug, no debug overrides found, so use default
275 @debug_format [$debug_format:tt]) => (
276 impl ::std::fmt::Debug for $type {
277 fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
278 write!(fmt, $debug_format, self.as_u32())
283 // Debug is requested for derive, don't generate any Debug implementation.
285 @derives [Debug, $($derives:ident,)*]
287 @debug_format [$debug_format:tt]) => ();
289 // It's not Debug, so just pop it off the front of the derives stack and check the rest.
291 @derives [$_derive:ident, $($derives:ident,)*]
293 @debug_format [$debug_format:tt]) => (
294 $crate::newtype_index!(
296 @derives [$($derives,)*]
298 @debug_format [$debug_format]);
301 // Append comma to end of derives list if it's missing
302 (@attrs [$(#[$attrs:meta])*]
306 @debug_format [$debug_format:tt]
307 derive [$($derives:ident),*]
309 $crate::newtype_index!(
310 @attrs [$(#[$attrs])*]
314 @debug_format [$debug_format]
315 derive [$($derives,)*]
319 // By not including the @derives marker in this list nor in the default args, we can force it
320 // to come first if it exists. When encodable is custom, just use the derives list as-is.
321 (@attrs [$(#[$attrs:meta])*]
325 @debug_format [$debug_format:tt]
326 derive [$($derives:ident,)+]
329 $crate::newtype_index!(
330 @attrs [$(#[$attrs])*]
331 @derives [$($derives,)+]
335 @debug_format [$debug_format]
339 // By not including the @derives marker in this list nor in the default args, we can force it
340 // to come first if it exists. When encodable isn't custom, add serialization traits by default.
341 (@attrs [$(#[$attrs:meta])*]
345 @debug_format [$debug_format:tt]
346 derive [$($derives:ident,)+]
348 $crate::newtype_index!(
349 @derives [$($derives,)+]
350 @attrs [$(#[$attrs])*]
354 @debug_format [$debug_format]
356 $crate::newtype_index!(@serializable $type);
359 // The case where no derives are added, but encodable is overridden. Don't
360 // derive serialization traits
361 (@attrs [$(#[$attrs:meta])*]
365 @debug_format [$debug_format:tt]
368 $crate::newtype_index!(
370 @attrs [$(#[$attrs])*]
374 @debug_format [$debug_format]
378 // The case where no derives are added, add serialization derives by default
379 (@attrs [$(#[$attrs:meta])*]
383 @debug_format [$debug_format:tt]
385 $crate::newtype_index!(
387 @attrs [$(#[$attrs])*]
391 @debug_format [$debug_format]
393 $crate::newtype_index!(@serializable $type);
396 (@serializable $type:ident) => (
397 impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for $type {
398 fn decode(d: &mut D) -> Result<Self, D::Error> {
399 d.read_u32().map(Self::from_u32)
402 impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for $type {
403 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
404 e.emit_u32(self.private)
409 // Rewrite final without comma to one that includes comma
410 (@derives [$($derives:ident,)*]
411 @attrs [$(#[$attrs:meta])*]
415 @debug_format [$debug_format:tt]
416 $name:ident = $constant:expr) => (
417 $crate::newtype_index!(
418 @derives [$($derives,)*]
419 @attrs [$(#[$attrs])*]
423 @debug_format [$debug_format]
427 // Rewrite final const without comma to one that includes comma
428 (@derives [$($derives:ident,)*]
429 @attrs [$(#[$attrs:meta])*]
433 @debug_format [$debug_format:tt]
434 $(#[doc = $doc:expr])*
435 const $name:ident = $constant:expr) => (
436 $crate::newtype_index!(
437 @derives [$($derives,)*]
438 @attrs [$(#[$attrs])*]
442 @debug_format [$debug_format]
443 $(#[doc = $doc])* const $name = $constant,);
446 // Replace existing default for max
447 (@derives [$($derives:ident,)*]
448 @attrs [$(#[$attrs:meta])*]
452 @debug_format [$debug_format:tt]
455 $crate::newtype_index!(
456 @derives [$($derives,)*]
457 @attrs [$(#[$attrs])*]
461 @debug_format [$debug_format]
465 // Replace existing default for debug_format
466 (@derives [$($derives:ident,)*]
467 @attrs [$(#[$attrs:meta])*]
471 @debug_format [$_debug_format:tt]
472 DEBUG_FORMAT = $debug_format:tt,
474 $crate::newtype_index!(
475 @derives [$($derives,)*]
476 @attrs [$(#[$attrs])*]
480 @debug_format [$debug_format]
484 // Assign a user-defined constant
485 (@derives [$($derives:ident,)*]
486 @attrs [$(#[$attrs:meta])*]
490 @debug_format [$debug_format:tt]
491 $(#[doc = $doc:expr])*
492 const $name:ident = $constant:expr,
495 $v const $name: $type = $type::from_u32($constant);
496 $crate::newtype_index!(
497 @derives [$($derives,)*]
498 @attrs [$(#[$attrs])*]
502 @debug_format [$debug_format]
507 #[derive(Clone, PartialEq, Eq, Hash)]
508 pub struct IndexVec<I: Idx, T> {
510 _marker: PhantomData<fn(&I)>,
513 // Whether `IndexVec` is `Send` depends only on the data,
514 // not the phantom data.
515 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
517 impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for IndexVec<I, T> {
518 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
519 Encodable::encode(&self.raw, s)
523 impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for &IndexVec<I, T> {
524 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
525 Encodable::encode(&self.raw, s)
529 impl<D: Decoder, I: Idx, T: Decodable<D>> Decodable<D> for IndexVec<I, T> {
530 fn decode(d: &mut D) -> Result<Self, D::Error> {
531 Decodable::decode(d).map(|v| IndexVec { raw: v, _marker: PhantomData })
535 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
536 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
537 fmt::Debug::fmt(&self.raw, fmt)
541 impl<I: Idx, T> IndexVec<I, T> {
543 pub fn new() -> Self {
544 IndexVec { raw: Vec::new(), _marker: PhantomData }
548 pub fn from_raw(raw: Vec<T>) -> Self {
549 IndexVec { raw, _marker: PhantomData }
553 pub fn with_capacity(capacity: usize) -> Self {
554 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
558 pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
562 IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
566 pub fn from_elem_n(elem: T, n: usize) -> Self
570 IndexVec { raw: vec![elem; n], _marker: PhantomData }
573 /// Create an `IndexVec` with `n` elements, where the value of each
574 /// element is the result of `func(i)`. (The underlying vector will
575 /// be allocated only once, with a capacity of at least `n`.)
577 pub fn from_fn_n(func: impl FnMut(I) -> T, n: usize) -> Self {
578 let indices = (0..n).map(I::new);
579 Self::from_raw(indices.map(func).collect())
583 pub fn push(&mut self, d: T) -> I {
584 let idx = I::new(self.len());
590 pub fn pop(&mut self) -> Option<T> {
595 pub fn len(&self) -> usize {
599 /// Gives the next index that will be assigned when `push` is
602 pub fn next_index(&self) -> I {
607 pub fn is_empty(&self) -> bool {
612 pub fn into_iter(self) -> vec::IntoIter<T> {
617 pub fn into_iter_enumerated(
619 ) -> impl DoubleEndedIterator<Item = (I, T)> + ExactSizeIterator {
620 self.raw.into_iter().enumerate().map(|(n, t)| (I::new(n), t))
624 pub fn iter(&self) -> slice::Iter<'_, T> {
629 pub fn iter_enumerated(
631 ) -> impl DoubleEndedIterator<Item = (I, &T)> + ExactSizeIterator + '_ {
632 self.raw.iter().enumerate().map(|(n, t)| (I::new(n), t))
636 pub fn indices(&self) -> impl DoubleEndedIterator<Item = I> + ExactSizeIterator + 'static {
637 (0..self.len()).map(|n| I::new(n))
641 pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
646 pub fn iter_enumerated_mut(
648 ) -> impl DoubleEndedIterator<Item = (I, &mut T)> + ExactSizeIterator + '_ {
649 self.raw.iter_mut().enumerate().map(|(n, t)| (I::new(n), t))
653 pub fn drain<'a, R: RangeBounds<usize>>(
656 ) -> impl Iterator<Item = T> + 'a {
657 self.raw.drain(range)
661 pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
664 ) -> impl Iterator<Item = (I, T)> + 'a {
665 self.raw.drain(range).enumerate().map(|(n, t)| (I::new(n), t))
669 pub fn last(&self) -> Option<I> {
670 self.len().checked_sub(1).map(I::new)
674 pub fn shrink_to_fit(&mut self) {
675 self.raw.shrink_to_fit()
679 pub fn swap(&mut self, a: I, b: I) {
680 self.raw.swap(a.index(), b.index())
684 pub fn truncate(&mut self, a: usize) {
689 pub fn get(&self, index: I) -> Option<&T> {
690 self.raw.get(index.index())
694 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
695 self.raw.get_mut(index.index())
698 /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
700 pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
701 let (ai, bi) = (a.index(), b.index());
705 let (c1, c2) = self.raw.split_at_mut(bi);
706 (&mut c1[ai], &mut c2[0])
708 let (c2, c1) = self.pick2_mut(b, a);
713 /// Returns mutable references to three distinct elements or panics otherwise.
715 pub fn pick3_mut(&mut self, a: I, b: I, c: I) -> (&mut T, &mut T, &mut T) {
716 let (ai, bi, ci) = (a.index(), b.index(), c.index());
717 assert!(ai != bi && bi != ci && ci != ai);
718 let len = self.raw.len();
719 assert!(ai < len && bi < len && ci < len);
720 let ptr = self.raw.as_mut_ptr();
721 unsafe { (&mut *ptr.add(ai), &mut *ptr.add(bi), &mut *ptr.add(ci)) }
724 pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
725 IndexVec { raw: self.raw, _marker: PhantomData }
728 /// Grows the index vector so that it contains an entry for
729 /// `elem`; if that is already true, then has no
730 /// effect. Otherwise, inserts new values as needed by invoking
733 pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
734 let min_new_len = elem.index() + 1;
735 if self.len() < min_new_len {
736 self.raw.resize_with(min_new_len, fill_value);
741 pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
742 let min_new_len = elem.index() + 1;
743 self.raw.resize_with(min_new_len, fill_value);
747 /// `IndexVec` is often used as a map, so it provides some map-like APIs.
748 impl<I: Idx, T> IndexVec<I, Option<T>> {
750 pub fn insert(&mut self, index: I, value: T) -> Option<T> {
751 self.ensure_contains_elem(index, || None);
752 self[index].replace(value)
756 pub fn get_or_insert_with(&mut self, index: I, value: impl FnOnce() -> T) -> &mut T {
757 self.ensure_contains_elem(index, || None);
758 self[index].get_or_insert_with(value)
762 pub fn remove(&mut self, index: I) -> Option<T> {
763 self.ensure_contains_elem(index, || None);
768 impl<I: Idx, T: Clone> IndexVec<I, T> {
770 pub fn resize(&mut self, new_len: usize, value: T) {
771 self.raw.resize(new_len, value)
775 impl<I: Idx, T: Ord> IndexVec<I, T> {
777 pub fn binary_search(&self, value: &T) -> Result<I, I> {
778 match self.raw.binary_search(value) {
779 Ok(i) => Ok(Idx::new(i)),
780 Err(i) => Err(Idx::new(i)),
785 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
789 fn index(&self, index: I) -> &T {
790 &self.raw[index.index()]
794 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
796 fn index_mut(&mut self, index: I) -> &mut T {
797 &mut self.raw[index.index()]
801 impl<I: Idx, T> Default for IndexVec<I, T> {
803 fn default() -> Self {
808 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
810 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
811 self.raw.extend(iter);
815 fn extend_one(&mut self, item: T) {
820 fn extend_reserve(&mut self, additional: usize) {
821 self.raw.reserve(additional);
825 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
827 fn from_iter<J>(iter: J) -> Self
829 J: IntoIterator<Item = T>,
831 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
835 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
837 type IntoIter = vec::IntoIter<T>;
840 fn into_iter(self) -> vec::IntoIter<T> {
845 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
847 type IntoIter = slice::Iter<'a, T>;
850 fn into_iter(self) -> slice::Iter<'a, T> {
855 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
856 type Item = &'a mut T;
857 type IntoIter = slice::IterMut<'a, T>;
860 fn into_iter(self) -> slice::IterMut<'a, T> {