1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use std::iter::{self, FromIterator};
14 use std::marker::PhantomData;
15 use std::ops::{Index, IndexMut, Range, RangeBounds};
21 use rustc_serialize as serialize;
23 /// Represents some newtyped `usize` wrapper.
25 /// (purpose: avoid mixing indexes for different bitvector domains.)
26 pub trait Idx: Copy + 'static + Ord + Debug + Hash {
27 fn new(idx: usize) -> Self;
29 fn index(self) -> usize;
31 fn increment_by(&mut self, amount: usize) {
32 let v = self.index() + amount;
39 fn new(idx: usize) -> Self { idx }
41 fn index(self) -> usize { self }
46 fn new(idx: usize) -> Self { assert!(idx <= u32::MAX as usize); idx as u32 }
48 fn index(self) -> usize { self as usize }
51 /// Creates a struct type `S` that can be used as an index with
52 /// `IndexVec` and so on.
54 /// There are two ways of interacting with these indices:
56 /// - The `From` impls are the preferred way. So you can do
57 /// `S::from(v)` with a `usize` or `u32`. And you can convert back
58 /// to an integer with `u32::from(s)`.
60 /// - Alternatively, you can use the methods `S::new(v)` and `s.index()`
61 /// to create/return a value.
63 /// Internally, the index uses a u32, so the index must not exceed
64 /// `u32::MAX`. You can also customize things like the `Debug` impl,
65 /// what traits are derived, and so forth via the macro.
67 macro_rules! newtype_index {
68 // ---- public rules ----
70 // Use default constants
71 ($v:vis struct $name:ident { .. }) => (
73 // Leave out derives marker so we can use its absence to ensure it comes first
75 // shave off 256 indices at the end to allow space for packing these indices into enums
78 @debug_format ["{}"]);
81 // Define any constants
82 ($v:vis struct $name:ident { $($tokens:tt)+ }) => (
84 // Leave out derives marker so we can use its absence to ensure it comes first
86 // shave off 256 indices at the end to allow space for packing these indices into enums
93 // ---- private rules ----
95 // Base case, user-defined constants (if any) have already been defined
96 (@derives [$($derives:ident,)*]
100 @debug_format [$debug_format:tt]) => (
101 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, $($derives),*)]
102 #[rustc_layout_scalar_valid_range_end($max)]
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 $type { private: value }
151 /// Extract value of this index as an integer.
153 $v fn index(self) -> usize {
157 /// Extract value of this index as a usize.
159 $v fn as_u32(self) -> u32 {
163 /// Extract value of this index as a u32.
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 impl From<$type> for u32 {
219 fn from(v: $type) -> u32 {
224 impl From<$type> for usize {
226 fn from(v: $type) -> usize {
231 impl From<usize> for $type {
233 fn from(value: usize) -> Self {
234 $type::from_usize(value)
238 impl From<u32> for $type {
240 fn from(value: u32) -> Self {
241 $type::from_u32(value)
247 @derives [$($derives,)*]
249 @debug_format [$debug_format]);
252 // base case for handle_debug where format is custom. No Debug implementation is emitted.
254 @derives [$($_derives:ident,)*]
256 @debug_format [custom]) => ();
258 // base case for handle_debug, no debug overrides found, so use default
262 @debug_format [$debug_format:tt]) => (
263 impl ::std::fmt::Debug for $type {
264 fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
265 write!(fmt, $debug_format, self.as_u32())
270 // Debug is requested for derive, don't generate any Debug implementation.
272 @derives [Debug, $($derives:ident,)*]
274 @debug_format [$debug_format:tt]) => ();
276 // It's not Debug, so just pop it off the front of the derives stack and check the rest.
278 @derives [$_derive:ident, $($derives:ident,)*]
280 @debug_format [$debug_format:tt]) => (
283 @derives [$($derives,)*]
285 @debug_format [$debug_format]);
288 // Append comma to end of derives list if it's missing
292 @debug_format [$debug_format:tt]
293 derive [$($derives:ident),*]
299 @debug_format [$debug_format]
300 derive [$($derives,)*]
304 // By not including the @derives marker in this list nor in the default args, we can force it
305 // to come first if it exists. When encodable is custom, just use the derives list as-is.
309 @debug_format [$debug_format:tt]
310 derive [$($derives:ident,)+]
314 @derives [$($derives,)+]
318 @debug_format [$debug_format]
322 // By not including the @derives marker in this list nor in the default args, we can force it
323 // to come first if it exists. When encodable isn't custom, add serialization traits by default.
327 @debug_format [$debug_format:tt]
328 derive [$($derives:ident,)+]
331 @derives [$($derives,)+ RustcDecodable, RustcEncodable,]
335 @debug_format [$debug_format]
339 // The case where no derives are added, but encodable is overridden. Don't
340 // derive serialization traits
344 @debug_format [$debug_format:tt]
352 @debug_format [$debug_format]
356 // The case where no derives are added, add serialization derives by default
360 @debug_format [$debug_format:tt]
363 @derives [RustcDecodable, RustcEncodable,]
367 @debug_format [$debug_format]
371 // Rewrite final without comma to one that includes comma
372 (@derives [$($derives:ident,)*]
376 @debug_format [$debug_format:tt]
377 $name:ident = $constant:expr) => (
379 @derives [$($derives,)*]
383 @debug_format [$debug_format]
387 // Rewrite final const without comma to one that includes comma
388 (@derives [$($derives:ident,)*]
392 @debug_format [$debug_format:tt]
393 $(#[doc = $doc:expr])*
394 const $name:ident = $constant:expr) => (
396 @derives [$($derives,)*]
400 @debug_format [$debug_format]
401 $(#[doc = $doc])* const $name = $constant,);
404 // Replace existing default for max
405 (@derives [$($derives:ident,)*]
409 @debug_format [$debug_format:tt]
413 @derives [$($derives,)*]
417 @debug_format [$debug_format]
421 // Replace existing default for debug_format
422 (@derives [$($derives:ident,)*]
426 @debug_format [$_debug_format:tt]
427 DEBUG_FORMAT = $debug_format:tt,
430 @derives [$($derives,)*]
434 @debug_format [$debug_format]
438 // Assign a user-defined constant
439 (@derives [$($derives:ident,)*]
443 @debug_format [$debug_format:tt]
444 $(#[doc = $doc:expr])*
445 const $name:ident = $constant:expr,
448 pub const $name: $type = $type::from_u32_const($constant);
450 @derives [$($derives,)*]
454 @debug_format [$debug_format]
459 #[derive(Clone, PartialEq, Eq, Hash)]
460 pub struct IndexVec<I: Idx, T> {
462 _marker: PhantomData<fn(&I)>
465 // Whether `IndexVec` is `Send` depends only on the data,
466 // not the phantom data.
467 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
469 impl<I: Idx, T: serialize::Encodable> serialize::Encodable for IndexVec<I, T> {
470 fn encode<S: serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
471 serialize::Encodable::encode(&self.raw, s)
475 impl<I: Idx, T: serialize::Decodable> serialize::Decodable for IndexVec<I, T> {
476 fn decode<D: serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
477 serialize::Decodable::decode(d).map(|v| {
478 IndexVec { raw: v, _marker: PhantomData }
483 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
484 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
485 fmt::Debug::fmt(&self.raw, fmt)
489 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
491 impl<I: Idx, T> IndexVec<I, T> {
493 pub fn new() -> Self {
494 IndexVec { raw: Vec::new(), _marker: PhantomData }
498 pub fn from_raw(raw: Vec<T>) -> Self {
499 IndexVec { raw, _marker: PhantomData }
503 pub fn with_capacity(capacity: usize) -> Self {
504 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
508 pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
511 IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
515 pub fn from_elem_n(elem: T, n: usize) -> Self
518 IndexVec { raw: vec![elem; n], _marker: PhantomData }
522 pub fn push(&mut self, d: T) -> I {
523 let idx = I::new(self.len());
529 pub fn pop(&mut self) -> Option<T> {
534 pub fn len(&self) -> usize {
538 /// Gives the next index that will be assigned when `push` is
541 pub fn next_index(&self) -> I {
546 pub fn is_empty(&self) -> bool {
551 pub fn into_iter(self) -> vec::IntoIter<T> {
556 pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>>
558 self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
562 pub fn iter(&self) -> slice::Iter<T> {
567 pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>>
569 self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
573 pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
574 (0..self.len()).map(IntoIdx { _marker: PhantomData })
578 pub fn iter_mut(&mut self) -> slice::IterMut<T> {
583 pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>>
585 self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
589 pub fn drain<'a, R: RangeBounds<usize>>(
590 &'a mut self, range: R) -> impl Iterator<Item=T> + 'a {
591 self.raw.drain(range)
595 pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
596 &'a mut self, range: R) -> impl Iterator<Item=(I, T)> + 'a {
597 self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
601 pub fn last(&self) -> Option<I> {
602 self.len().checked_sub(1).map(I::new)
606 pub fn shrink_to_fit(&mut self) {
607 self.raw.shrink_to_fit()
611 pub fn swap(&mut self, a: I, b: I) {
612 self.raw.swap(a.index(), b.index())
616 pub fn truncate(&mut self, a: usize) {
621 pub fn get(&self, index: I) -> Option<&T> {
622 self.raw.get(index.index())
626 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
627 self.raw.get_mut(index.index())
630 /// Return mutable references to two distinct elements, a and b. Panics if a == b.
632 pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
633 let (ai, bi) = (a.index(), b.index());
637 let (c1, c2) = self.raw.split_at_mut(bi);
638 (&mut c1[ai], &mut c2[0])
640 let (c2, c1) = self.pick2_mut(b, a);
645 pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
648 _marker: PhantomData,
653 impl<I: Idx, T: Clone> IndexVec<I, T> {
654 /// Grows the index vector so that it contains an entry for
655 /// `elem`; if that is already true, then has no
656 /// effect. Otherwise, inserts new values as needed by invoking
659 pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
660 let min_new_len = elem.index() + 1;
661 if self.len() < min_new_len {
662 self.raw.resize_with(min_new_len, fill_value);
667 pub fn resize(&mut self, new_len: usize, value: T) {
668 self.raw.resize(new_len, value)
672 pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
673 let min_new_len = elem.index() + 1;
674 self.raw.resize_with(min_new_len, fill_value);
678 impl<I: Idx, T: Ord> IndexVec<I, T> {
680 pub fn binary_search(&self, value: &T) -> Result<I, I> {
681 match self.raw.binary_search(value) {
682 Ok(i) => Ok(Idx::new(i)),
683 Err(i) => Err(Idx::new(i)),
688 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
692 fn index(&self, index: I) -> &T {
693 &self.raw[index.index()]
697 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
699 fn index_mut(&mut self, index: I) -> &mut T {
700 &mut self.raw[index.index()]
704 impl<I: Idx, T> Default for IndexVec<I, T> {
706 fn default() -> Self {
711 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
713 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
714 self.raw.extend(iter);
718 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
720 fn from_iter<J>(iter: J) -> Self where J: IntoIterator<Item=T> {
721 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
725 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
727 type IntoIter = vec::IntoIter<T>;
730 fn into_iter(self) -> vec::IntoIter<T> {
736 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
738 type IntoIter = slice::Iter<'a, T>;
741 fn into_iter(self) -> slice::Iter<'a, T> {
746 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
747 type Item = &'a mut T;
748 type IntoIter = slice::IterMut<'a, T>;
751 fn into_iter(self) -> slice::IterMut<'a, T> {
756 pub struct IntoIdx<I: Idx> { _marker: PhantomData<fn(&I)> }
757 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
758 type Output = (I, T);
760 extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
765 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
766 extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
771 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
774 extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
779 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
780 extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {