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 let v = self.index() + amount;
29 fn new(idx: usize) -> Self { idx }
31 fn index(self) -> usize { self }
36 fn new(idx: usize) -> Self { assert!(idx <= u32::MAX as usize); idx as u32 }
38 fn index(self) -> usize { self as usize }
41 /// Creates a struct type `S` that can be used as an index with
42 /// `IndexVec` and so on.
44 /// There are two ways of interacting with these indices:
46 /// - The `From` impls are the preferred way. So you can do
47 /// `S::from(v)` with a `usize` or `u32`. And you can convert back
48 /// to an integer with `u32::from(s)`.
50 /// - Alternatively, you can use the methods `S::new(v)` and `s.index()`
51 /// to create/return a value.
53 /// Internally, the index uses a u32, so the index must not exceed
54 /// `u32::MAX`. You can also customize things like the `Debug` impl,
55 /// what traits are derived, and so forth via the macro.
57 macro_rules! newtype_index {
58 // ---- public rules ----
60 // Use default constants
61 ($(#[$attrs:meta])* $v:vis struct $name:ident { .. }) => (
63 // Leave out derives marker so we can use its absence to ensure it comes first
64 @attrs [$(#[$attrs])*]
66 // shave off 256 indices at the end to allow space for packing these indices into enums
69 @debug_format ["{}"]);
72 // Define any constants
73 ($(#[$attrs:meta])* $v:vis struct $name:ident { $($tokens:tt)+ }) => (
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
85 // ---- private rules ----
87 // Base case, user-defined constants (if any) have already been defined
88 (@derives [$($derives:ident,)*]
89 @attrs [$(#[$attrs:meta])*]
93 @debug_format [$debug_format:tt]) => (
95 #[derive(Copy, PartialEq, Eq, Hash, PartialOrd, Ord, $($derives),*)]
96 #[rustc_layout_scalar_valid_range_end($max)]
101 impl Clone for $type {
102 fn clone(&self) -> Self {
108 $v const MAX_AS_U32: u32 = $max;
110 $v const MAX: $type = $type::from_u32_const($max);
113 $v fn from_usize(value: usize) -> Self {
114 assert!(value <= ($max as usize));
116 $type::from_u32_unchecked(value as u32)
121 $v fn from_u32(value: u32) -> Self {
122 assert!(value <= $max);
124 $type::from_u32_unchecked(value)
128 /// Hacky variant of `from_u32` for use in constants.
129 /// This version checks the "max" constraint by using an
130 /// invalid array dereference.
132 $v const fn from_u32_const(value: u32) -> Self {
133 // This will fail at const eval time unless `value <=
134 // max` is true (in which case we get the index 0).
135 // It will also fail at runtime, of course, but in a
136 // kind of wacky way.
137 let _ = ["out of range value used"][
138 !(value <= $max) as usize
142 $type { private: value }
147 $v const unsafe fn from_u32_unchecked(value: u32) -> Self {
148 unsafe { $type { private: value } }
151 /// Extracts the value of this index as an integer.
153 $v fn index(self) -> usize {
157 /// Extracts the value of this index as a `u32`.
159 $v fn as_u32(self) -> u32 {
163 /// Extracts the value of this index as a `usize`.
165 $v fn as_usize(self) -> usize {
166 self.as_u32() as usize
172 fn new(value: usize) -> Self {
177 fn index(self) -> usize {
182 impl ::std::iter::Step for $type {
184 fn steps_between(start: &Self, end: &Self) -> Option<usize> {
185 <usize as ::std::iter::Step>::steps_between(
192 fn replace_one(&mut self) -> Self {
193 ::std::mem::replace(self, Self::new(1))
197 fn replace_zero(&mut self) -> Self {
198 ::std::mem::replace(self, Self::new(0))
202 fn add_one(&self) -> Self {
203 Self::new(Idx::index(*self) + 1)
207 fn sub_one(&self) -> Self {
208 Self::new(Idx::index(*self) - 1)
212 fn add_usize(&self, u: usize) -> Option<Self> {
213 Idx::index(*self).checked_add(u).map(Self::new)
217 fn sub_usize(&self, u: usize) -> Option<Self> {
218 Idx::index(*self).checked_sub(u).map(Self::new)
222 impl From<$type> for u32 {
224 fn from(v: $type) -> u32 {
229 impl From<$type> for usize {
231 fn from(v: $type) -> usize {
236 impl From<usize> for $type {
238 fn from(value: usize) -> Self {
239 $type::from_usize(value)
243 impl From<u32> for $type {
245 fn from(value: u32) -> Self {
246 $type::from_u32(value)
252 @derives [$($derives,)*]
254 @debug_format [$debug_format]);
257 // base case for handle_debug where format is custom. No Debug implementation is emitted.
259 @derives [$($_derives:ident,)*]
261 @debug_format [custom]) => ();
263 // base case for handle_debug, no debug overrides found, so use default
267 @debug_format [$debug_format:tt]) => (
268 impl ::std::fmt::Debug for $type {
269 fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
270 write!(fmt, $debug_format, self.as_u32())
275 // Debug is requested for derive, don't generate any Debug implementation.
277 @derives [Debug, $($derives:ident,)*]
279 @debug_format [$debug_format:tt]) => ();
281 // It's not Debug, so just pop it off the front of the derives stack and check the rest.
283 @derives [$_derive:ident, $($derives:ident,)*]
285 @debug_format [$debug_format:tt]) => (
288 @derives [$($derives,)*]
290 @debug_format [$debug_format]);
293 // Append comma to end of derives list if it's missing
294 (@attrs [$(#[$attrs:meta])*]
298 @debug_format [$debug_format:tt]
299 derive [$($derives:ident),*]
302 @attrs [$(#[$attrs])*]
306 @debug_format [$debug_format]
307 derive [$($derives,)*]
311 // By not including the @derives marker in this list nor in the default args, we can force it
312 // to come first if it exists. When encodable is custom, just use the derives list as-is.
313 (@attrs [$(#[$attrs:meta])*]
317 @debug_format [$debug_format:tt]
318 derive [$($derives:ident,)+]
322 @attrs [$(#[$attrs])*]
323 @derives [$($derives,)+]
327 @debug_format [$debug_format]
331 // By not including the @derives marker in this list nor in the default args, we can force it
332 // to come first if it exists. When encodable isn't custom, add serialization traits by default.
333 (@attrs [$(#[$attrs:meta])*]
337 @debug_format [$debug_format:tt]
338 derive [$($derives:ident,)+]
341 @derives [$($derives,)+ RustcEncodable,]
342 @attrs [$(#[$attrs])*]
346 @debug_format [$debug_format]
348 newtype_index!(@decodable $type);
351 // The case where no derives are added, but encodable is overridden. Don't
352 // derive serialization traits
353 (@attrs [$(#[$attrs:meta])*]
357 @debug_format [$debug_format:tt]
362 @attrs [$(#[$attrs])*]
366 @debug_format [$debug_format]
370 // The case where no derives are added, add serialization derives by default
371 (@attrs [$(#[$attrs:meta])*]
375 @debug_format [$debug_format:tt]
378 @derives [RustcEncodable,]
379 @attrs [$(#[$attrs])*]
383 @debug_format [$debug_format]
385 newtype_index!(@decodable $type);
388 (@decodable $type:ident) => (
390 fn __decodable__impl__hack() {
391 mod __more_hacks_because__self_doesnt_work_in_functions {
392 extern crate serialize;
393 use self::serialize::{Decodable, Decoder};
394 impl Decodable for super::$type {
395 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
396 d.read_u32().map(Self::from)
404 // Rewrite final without comma to one that includes comma
405 (@derives [$($derives:ident,)*]
406 @attrs [$(#[$attrs:meta])*]
410 @debug_format [$debug_format:tt]
411 $name:ident = $constant:expr) => (
413 @derives [$($derives,)*]
414 @attrs [$(#[$attrs])*]
418 @debug_format [$debug_format]
422 // Rewrite final const without comma to one that includes comma
423 (@derives [$($derives:ident,)*]
424 @attrs [$(#[$attrs:meta])*]
428 @debug_format [$debug_format:tt]
429 $(#[doc = $doc:expr])*
430 const $name:ident = $constant:expr) => (
432 @derives [$($derives,)*]
433 @attrs [$(#[$attrs])*]
437 @debug_format [$debug_format]
438 $(#[doc = $doc])* const $name = $constant,);
441 // Replace existing default for max
442 (@derives [$($derives:ident,)*]
443 @attrs [$(#[$attrs:meta])*]
447 @debug_format [$debug_format:tt]
451 @derives [$($derives,)*]
452 @attrs [$(#[$attrs])*]
456 @debug_format [$debug_format]
460 // Replace existing default for debug_format
461 (@derives [$($derives:ident,)*]
462 @attrs [$(#[$attrs:meta])*]
466 @debug_format [$_debug_format:tt]
467 DEBUG_FORMAT = $debug_format:tt,
470 @derives [$($derives,)*]
471 @attrs [$(#[$attrs])*]
475 @debug_format [$debug_format]
479 // Assign a user-defined constant
480 (@derives [$($derives:ident,)*]
481 @attrs [$(#[$attrs:meta])*]
485 @debug_format [$debug_format:tt]
486 $(#[doc = $doc:expr])*
487 const $name:ident = $constant:expr,
490 pub const $name: $type = $type::from_u32_const($constant);
492 @derives [$($derives,)*]
493 @attrs [$(#[$attrs])*]
497 @debug_format [$debug_format]
502 #[derive(Clone, PartialEq, Eq, Hash)]
503 pub struct IndexVec<I: Idx, T> {
505 _marker: PhantomData<fn(&I)>
508 // Whether `IndexVec` is `Send` depends only on the data,
509 // not the phantom data.
510 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
512 impl<I: Idx, T: serialize::Encodable> serialize::Encodable for IndexVec<I, T> {
513 fn encode<S: serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
514 serialize::Encodable::encode(&self.raw, s)
518 impl<I: Idx, T: serialize::Decodable> serialize::Decodable for IndexVec<I, T> {
519 fn decode<D: serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
520 serialize::Decodable::decode(d).map(|v| {
521 IndexVec { raw: v, _marker: PhantomData }
526 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
527 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
528 fmt::Debug::fmt(&self.raw, fmt)
532 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
534 impl<I: Idx, T> IndexVec<I, T> {
536 pub fn new() -> Self {
537 IndexVec { raw: Vec::new(), _marker: PhantomData }
541 pub fn from_raw(raw: Vec<T>) -> Self {
542 IndexVec { raw, _marker: PhantomData }
546 pub fn with_capacity(capacity: usize) -> Self {
547 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
551 pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
554 IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
558 pub fn from_elem_n(elem: T, n: usize) -> Self
561 IndexVec { raw: vec![elem; n], _marker: PhantomData }
565 pub fn push(&mut self, d: T) -> I {
566 let idx = I::new(self.len());
572 pub fn pop(&mut self) -> Option<T> {
577 pub fn len(&self) -> usize {
581 /// Gives the next index that will be assigned when `push` is
584 pub fn next_index(&self) -> I {
589 pub fn is_empty(&self) -> bool {
594 pub fn into_iter(self) -> vec::IntoIter<T> {
599 pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>>
601 self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
605 pub fn iter(&self) -> slice::Iter<'_, T> {
610 pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>>
612 self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
616 pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
617 (0..self.len()).map(IntoIdx { _marker: PhantomData })
621 pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
626 pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>>
628 self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
632 pub fn drain<'a, R: RangeBounds<usize>>(
633 &'a mut self, range: R) -> impl Iterator<Item=T> + 'a {
634 self.raw.drain(range)
638 pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
639 &'a mut self, range: R) -> impl Iterator<Item=(I, T)> + 'a {
640 self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
644 pub fn last(&self) -> Option<I> {
645 self.len().checked_sub(1).map(I::new)
649 pub fn shrink_to_fit(&mut self) {
650 self.raw.shrink_to_fit()
654 pub fn swap(&mut self, a: I, b: I) {
655 self.raw.swap(a.index(), b.index())
659 pub fn truncate(&mut self, a: usize) {
664 pub fn get(&self, index: I) -> Option<&T> {
665 self.raw.get(index.index())
669 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
670 self.raw.get_mut(index.index())
673 /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
675 pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
676 let (ai, bi) = (a.index(), b.index());
680 let (c1, c2) = self.raw.split_at_mut(bi);
681 (&mut c1[ai], &mut c2[0])
683 let (c2, c1) = self.pick2_mut(b, a);
688 pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
691 _marker: PhantomData,
696 impl<I: Idx, T: Clone> IndexVec<I, T> {
697 /// Grows the index vector so that it contains an entry for
698 /// `elem`; if that is already true, then has no
699 /// effect. Otherwise, inserts new values as needed by invoking
702 pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
703 let min_new_len = elem.index() + 1;
704 if self.len() < min_new_len {
705 self.raw.resize_with(min_new_len, fill_value);
710 pub fn resize(&mut self, new_len: usize, value: T) {
711 self.raw.resize(new_len, value)
715 pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
716 let min_new_len = elem.index() + 1;
717 self.raw.resize_with(min_new_len, fill_value);
721 impl<I: Idx, T: Ord> IndexVec<I, T> {
723 pub fn binary_search(&self, value: &T) -> Result<I, I> {
724 match self.raw.binary_search(value) {
725 Ok(i) => Ok(Idx::new(i)),
726 Err(i) => Err(Idx::new(i)),
731 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
735 fn index(&self, index: I) -> &T {
736 &self.raw[index.index()]
740 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
742 fn index_mut(&mut self, index: I) -> &mut T {
743 &mut self.raw[index.index()]
747 impl<I: Idx, T> Default for IndexVec<I, T> {
749 fn default() -> Self {
754 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
756 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
757 self.raw.extend(iter);
761 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
763 fn from_iter<J>(iter: J) -> Self where J: IntoIterator<Item=T> {
764 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
768 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
770 type IntoIter = vec::IntoIter<T>;
773 fn into_iter(self) -> vec::IntoIter<T> {
779 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
781 type IntoIter = slice::Iter<'a, T>;
784 fn into_iter(self) -> slice::Iter<'a, T> {
789 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
790 type Item = &'a mut T;
791 type IntoIter = slice::IterMut<'a, T>;
794 fn into_iter(self) -> slice::IterMut<'a, T> {
799 pub struct IntoIdx<I: Idx> { _marker: PhantomData<fn(&I)> }
800 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
801 type Output = (I, T);
803 extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
808 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
809 extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
814 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
817 extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
822 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
823 extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {