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 ($v:vis struct $name:ident { .. }) => (
63 // Leave out derives marker so we can use its absence to ensure it comes first
65 // shave off 256 indices at the end to allow space for packing these indices into enums
68 @debug_format ["{}"]);
71 // Define any constants
72 ($v:vis struct $name:ident { $($tokens:tt)+ }) => (
74 // Leave out derives marker so we can use its absence to ensure it comes first
76 // shave off 256 indices at the end to allow space for packing these indices into enums
83 // ---- private rules ----
85 // Base case, user-defined constants (if any) have already been defined
86 (@derives [$($derives:ident,)*]
90 @debug_format [$debug_format:tt]) => (
91 #[derive(Copy, PartialEq, Eq, Hash, PartialOrd, Ord, $($derives),*)]
92 #[rustc_layout_scalar_valid_range_end($max)]
97 impl Clone for $type {
98 fn clone(&self) -> Self {
104 $v const MAX_AS_U32: u32 = $max;
106 $v const MAX: $type = $type::from_u32_const($max);
109 $v fn from_usize(value: usize) -> Self {
110 assert!(value <= ($max as usize));
112 $type::from_u32_unchecked(value as u32)
117 $v fn from_u32(value: u32) -> Self {
118 assert!(value <= $max);
120 $type::from_u32_unchecked(value)
124 /// Hacky variant of `from_u32` for use in constants.
125 /// This version checks the "max" constraint by using an
126 /// invalid array dereference.
128 $v const fn from_u32_const(value: u32) -> Self {
129 // This will fail at const eval time unless `value <=
130 // max` is true (in which case we get the index 0).
131 // It will also fail at runtime, of course, but in a
132 // kind of wacky way.
133 let _ = ["out of range value used"][
134 !(value <= $max) as usize
138 $type { private: value }
143 $v const unsafe fn from_u32_unchecked(value: u32) -> Self {
144 unsafe { $type { private: value } }
147 /// Extracts the value of this index as an integer.
149 $v fn index(self) -> usize {
153 /// Extracts the value of this index as a `u32`.
155 $v fn as_u32(self) -> u32 {
159 /// Extracts the value of this index as a `usize`.
161 $v fn as_usize(self) -> usize {
162 self.as_u32() as usize
168 fn new(value: usize) -> Self {
173 fn index(self) -> usize {
178 impl ::std::iter::Step for $type {
180 fn steps_between(start: &Self, end: &Self) -> Option<usize> {
181 <usize as ::std::iter::Step>::steps_between(
188 fn replace_one(&mut self) -> Self {
189 ::std::mem::replace(self, Self::new(1))
193 fn replace_zero(&mut self) -> Self {
194 ::std::mem::replace(self, Self::new(0))
198 fn add_one(&self) -> Self {
199 Self::new(Idx::index(*self) + 1)
203 fn sub_one(&self) -> Self {
204 Self::new(Idx::index(*self) - 1)
208 fn add_usize(&self, u: usize) -> Option<Self> {
209 Idx::index(*self).checked_add(u).map(Self::new)
213 impl From<$type> for u32 {
215 fn from(v: $type) -> u32 {
220 impl From<$type> for usize {
222 fn from(v: $type) -> usize {
227 impl From<usize> for $type {
229 fn from(value: usize) -> Self {
230 $type::from_usize(value)
234 impl From<u32> for $type {
236 fn from(value: u32) -> Self {
237 $type::from_u32(value)
243 @derives [$($derives,)*]
245 @debug_format [$debug_format]);
248 // base case for handle_debug where format is custom. No Debug implementation is emitted.
250 @derives [$($_derives:ident,)*]
252 @debug_format [custom]) => ();
254 // base case for handle_debug, no debug overrides found, so use default
258 @debug_format [$debug_format:tt]) => (
259 impl ::std::fmt::Debug for $type {
260 fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
261 write!(fmt, $debug_format, self.as_u32())
266 // Debug is requested for derive, don't generate any Debug implementation.
268 @derives [Debug, $($derives:ident,)*]
270 @debug_format [$debug_format:tt]) => ();
272 // It's not Debug, so just pop it off the front of the derives stack and check the rest.
274 @derives [$_derive:ident, $($derives:ident,)*]
276 @debug_format [$debug_format:tt]) => (
279 @derives [$($derives,)*]
281 @debug_format [$debug_format]);
284 // Append comma to end of derives list if it's missing
288 @debug_format [$debug_format:tt]
289 derive [$($derives:ident),*]
295 @debug_format [$debug_format]
296 derive [$($derives,)*]
300 // By not including the @derives marker in this list nor in the default args, we can force it
301 // to come first if it exists. When encodable is custom, just use the derives list as-is.
305 @debug_format [$debug_format:tt]
306 derive [$($derives:ident,)+]
310 @derives [$($derives,)+]
314 @debug_format [$debug_format]
318 // By not including the @derives marker in this list nor in the default args, we can force it
319 // to come first if it exists. When encodable isn't custom, add serialization traits by default.
323 @debug_format [$debug_format:tt]
324 derive [$($derives:ident,)+]
327 @derives [$($derives,)+ RustcEncodable,]
331 @debug_format [$debug_format]
333 newtype_index!(@decodable $type);
336 // The case where no derives are added, but encodable is overridden. Don't
337 // derive serialization traits
341 @debug_format [$debug_format:tt]
349 @debug_format [$debug_format]
353 // The case where no derives are added, add serialization derives by default
357 @debug_format [$debug_format:tt]
360 @derives [RustcEncodable,]
364 @debug_format [$debug_format]
366 newtype_index!(@decodable $type);
369 (@decodable $type:ident) => (
371 fn __decodable__impl__hack() {
372 mod __more_hacks_because__self_doesnt_work_in_functions {
373 extern crate serialize;
374 use self::serialize::{Decodable, Decoder};
375 impl Decodable for super::$type {
376 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
377 d.read_u32().map(Self::from)
385 // Rewrite final without comma to one that includes comma
386 (@derives [$($derives:ident,)*]
390 @debug_format [$debug_format:tt]
391 $name:ident = $constant:expr) => (
393 @derives [$($derives,)*]
397 @debug_format [$debug_format]
401 // Rewrite final const without comma to one that includes comma
402 (@derives [$($derives:ident,)*]
406 @debug_format [$debug_format:tt]
407 $(#[doc = $doc:expr])*
408 const $name:ident = $constant:expr) => (
410 @derives [$($derives,)*]
414 @debug_format [$debug_format]
415 $(#[doc = $doc])* const $name = $constant,);
418 // Replace existing default for max
419 (@derives [$($derives:ident,)*]
423 @debug_format [$debug_format:tt]
427 @derives [$($derives,)*]
431 @debug_format [$debug_format]
435 // Replace existing default for debug_format
436 (@derives [$($derives:ident,)*]
440 @debug_format [$_debug_format:tt]
441 DEBUG_FORMAT = $debug_format:tt,
444 @derives [$($derives,)*]
448 @debug_format [$debug_format]
452 // Assign a user-defined constant
453 (@derives [$($derives:ident,)*]
457 @debug_format [$debug_format:tt]
458 $(#[doc = $doc:expr])*
459 const $name:ident = $constant:expr,
462 pub const $name: $type = $type::from_u32_const($constant);
464 @derives [$($derives,)*]
468 @debug_format [$debug_format]
473 #[derive(Clone, PartialEq, Eq, Hash)]
474 pub struct IndexVec<I: Idx, T> {
476 _marker: PhantomData<fn(&I)>
479 // Whether `IndexVec` is `Send` depends only on the data,
480 // not the phantom data.
481 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
483 impl<I: Idx, T: serialize::Encodable> serialize::Encodable for IndexVec<I, T> {
484 fn encode<S: serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
485 serialize::Encodable::encode(&self.raw, s)
489 impl<I: Idx, T: serialize::Decodable> serialize::Decodable for IndexVec<I, T> {
490 fn decode<D: serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
491 serialize::Decodable::decode(d).map(|v| {
492 IndexVec { raw: v, _marker: PhantomData }
497 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
498 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
499 fmt::Debug::fmt(&self.raw, fmt)
503 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
505 impl<I: Idx, T> IndexVec<I, T> {
507 pub fn new() -> Self {
508 IndexVec { raw: Vec::new(), _marker: PhantomData }
512 pub fn from_raw(raw: Vec<T>) -> Self {
513 IndexVec { raw, _marker: PhantomData }
517 pub fn with_capacity(capacity: usize) -> Self {
518 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
522 pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
525 IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
529 pub fn from_elem_n(elem: T, n: usize) -> Self
532 IndexVec { raw: vec![elem; n], _marker: PhantomData }
536 pub fn push(&mut self, d: T) -> I {
537 let idx = I::new(self.len());
543 pub fn pop(&mut self) -> Option<T> {
548 pub fn len(&self) -> usize {
552 /// Gives the next index that will be assigned when `push` is
555 pub fn next_index(&self) -> I {
560 pub fn is_empty(&self) -> bool {
565 pub fn into_iter(self) -> vec::IntoIter<T> {
570 pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>>
572 self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
576 pub fn iter(&self) -> slice::Iter<'_, T> {
581 pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>>
583 self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
587 pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
588 (0..self.len()).map(IntoIdx { _marker: PhantomData })
592 pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
597 pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>>
599 self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
603 pub fn drain<'a, R: RangeBounds<usize>>(
604 &'a mut self, range: R) -> impl Iterator<Item=T> + 'a {
605 self.raw.drain(range)
609 pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
610 &'a mut self, range: R) -> impl Iterator<Item=(I, T)> + 'a {
611 self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
615 pub fn last(&self) -> Option<I> {
616 self.len().checked_sub(1).map(I::new)
620 pub fn shrink_to_fit(&mut self) {
621 self.raw.shrink_to_fit()
625 pub fn swap(&mut self, a: I, b: I) {
626 self.raw.swap(a.index(), b.index())
630 pub fn truncate(&mut self, a: usize) {
635 pub fn get(&self, index: I) -> Option<&T> {
636 self.raw.get(index.index())
640 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
641 self.raw.get_mut(index.index())
644 /// Returns mutable references to two distinct elements, a and b. Panics if a == b.
646 pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
647 let (ai, bi) = (a.index(), b.index());
651 let (c1, c2) = self.raw.split_at_mut(bi);
652 (&mut c1[ai], &mut c2[0])
654 let (c2, c1) = self.pick2_mut(b, a);
659 pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
662 _marker: PhantomData,
667 impl<I: Idx, T: Clone> IndexVec<I, T> {
668 /// Grows the index vector so that it contains an entry for
669 /// `elem`; if that is already true, then has no
670 /// effect. Otherwise, inserts new values as needed by invoking
673 pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
674 let min_new_len = elem.index() + 1;
675 if self.len() < min_new_len {
676 self.raw.resize_with(min_new_len, fill_value);
681 pub fn resize(&mut self, new_len: usize, value: T) {
682 self.raw.resize(new_len, value)
686 pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
687 let min_new_len = elem.index() + 1;
688 self.raw.resize_with(min_new_len, fill_value);
692 impl<I: Idx, T: Ord> IndexVec<I, T> {
694 pub fn binary_search(&self, value: &T) -> Result<I, I> {
695 match self.raw.binary_search(value) {
696 Ok(i) => Ok(Idx::new(i)),
697 Err(i) => Err(Idx::new(i)),
702 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
706 fn index(&self, index: I) -> &T {
707 &self.raw[index.index()]
711 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
713 fn index_mut(&mut self, index: I) -> &mut T {
714 &mut self.raw[index.index()]
718 impl<I: Idx, T> Default for IndexVec<I, T> {
720 fn default() -> Self {
725 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
727 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
728 self.raw.extend(iter);
732 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
734 fn from_iter<J>(iter: J) -> Self where J: IntoIterator<Item=T> {
735 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
739 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
741 type IntoIter = vec::IntoIter<T>;
744 fn into_iter(self) -> vec::IntoIter<T> {
750 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
752 type IntoIter = slice::Iter<'a, T>;
755 fn into_iter(self) -> slice::Iter<'a, T> {
760 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
761 type Item = &'a mut T;
762 type IntoIter = slice::IterMut<'a, T>;
765 fn into_iter(self) -> slice::IterMut<'a, T> {
770 pub struct IntoIdx<I: Idx> { _marker: PhantomData<fn(&I)> }
771 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
772 type Output = (I, T);
774 extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
779 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
780 extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
785 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
788 extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
793 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
794 extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {