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, PartialEq, Eq, Hash, PartialOrd, Ord, $($derives),*)]
102 #[rustc_layout_scalar_valid_range_end($max)]
107 impl Clone for $type {
108 fn clone(&self) -> Self {
114 $v const MAX_AS_U32: u32 = $max;
116 $v const MAX: $type = $type::from_u32_const($max);
119 $v fn from_usize(value: usize) -> Self {
120 assert!(value <= ($max as usize));
122 $type::from_u32_unchecked(value as u32)
127 $v fn from_u32(value: u32) -> Self {
128 assert!(value <= $max);
130 $type::from_u32_unchecked(value)
134 /// Hacky variant of `from_u32` for use in constants.
135 /// This version checks the "max" constraint by using an
136 /// invalid array dereference.
138 $v const fn from_u32_const(value: u32) -> Self {
139 // This will fail at const eval time unless `value <=
140 // max` is true (in which case we get the index 0).
141 // It will also fail at runtime, of course, but in a
142 // kind of wacky way.
143 let _ = ["out of range value used"][
144 !(value <= $max) as usize
148 $type { private: value }
153 $v const unsafe fn from_u32_unchecked(value: u32) -> Self {
154 unsafe { $type { private: value } }
157 /// Extract value of this index as an integer.
159 $v fn index(self) -> usize {
163 /// Extract value of this index as a usize.
165 $v fn as_u32(self) -> u32 {
169 /// Extract value of this index as a u32.
171 $v fn as_usize(self) -> usize {
172 self.as_u32() as usize
178 fn new(value: usize) -> Self {
183 fn index(self) -> usize {
188 impl ::std::iter::Step for $type {
190 fn steps_between(start: &Self, end: &Self) -> Option<usize> {
191 <usize as ::std::iter::Step>::steps_between(
198 fn replace_one(&mut self) -> Self {
199 ::std::mem::replace(self, Self::new(1))
203 fn replace_zero(&mut self) -> Self {
204 ::std::mem::replace(self, Self::new(0))
208 fn add_one(&self) -> Self {
209 Self::new(Idx::index(*self) + 1)
213 fn sub_one(&self) -> Self {
214 Self::new(Idx::index(*self) - 1)
218 fn add_usize(&self, u: usize) -> Option<Self> {
219 Idx::index(*self).checked_add(u).map(Self::new)
223 impl From<$type> for u32 {
225 fn from(v: $type) -> u32 {
230 impl From<$type> for usize {
232 fn from(v: $type) -> usize {
237 impl From<usize> for $type {
239 fn from(value: usize) -> Self {
240 $type::from_usize(value)
244 impl From<u32> for $type {
246 fn from(value: u32) -> Self {
247 $type::from_u32(value)
253 @derives [$($derives,)*]
255 @debug_format [$debug_format]);
258 // base case for handle_debug where format is custom. No Debug implementation is emitted.
260 @derives [$($_derives:ident,)*]
262 @debug_format [custom]) => ();
264 // base case for handle_debug, no debug overrides found, so use default
268 @debug_format [$debug_format:tt]) => (
269 impl ::std::fmt::Debug for $type {
270 fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
271 write!(fmt, $debug_format, self.as_u32())
276 // Debug is requested for derive, don't generate any Debug implementation.
278 @derives [Debug, $($derives:ident,)*]
280 @debug_format [$debug_format:tt]) => ();
282 // It's not Debug, so just pop it off the front of the derives stack and check the rest.
284 @derives [$_derive:ident, $($derives:ident,)*]
286 @debug_format [$debug_format:tt]) => (
289 @derives [$($derives,)*]
291 @debug_format [$debug_format]);
294 // Append comma to end of derives list if it's missing
298 @debug_format [$debug_format:tt]
299 derive [$($derives:ident),*]
305 @debug_format [$debug_format]
306 derive [$($derives,)*]
310 // By not including the @derives marker in this list nor in the default args, we can force it
311 // to come first if it exists. When encodable is custom, just use the derives list as-is.
315 @debug_format [$debug_format:tt]
316 derive [$($derives:ident,)+]
320 @derives [$($derives,)+]
324 @debug_format [$debug_format]
328 // By not including the @derives marker in this list nor in the default args, we can force it
329 // to come first if it exists. When encodable isn't custom, add serialization traits by default.
333 @debug_format [$debug_format:tt]
334 derive [$($derives:ident,)+]
337 @derives [$($derives,)+ RustcEncodable,]
341 @debug_format [$debug_format]
343 impl Decodable for $type {
344 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
350 // The case where no derives are added, but encodable is overridden. Don't
351 // derive serialization traits
355 @debug_format [$debug_format:tt]
363 @debug_format [$debug_format]
367 // The case where no derives are added, add serialization derives by default
371 @debug_format [$debug_format:tt]
374 @derives [RustcEncodable,]
378 @debug_format [$debug_format]
380 impl Decodable for $type {
381 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
382 d.read_u32().map(Self::from)
387 // Rewrite final without comma to one that includes comma
388 (@derives [$($derives:ident,)*]
392 @debug_format [$debug_format:tt]
393 $name:ident = $constant:expr) => (
395 @derives [$($derives,)*]
399 @debug_format [$debug_format]
403 // Rewrite final const without comma to one that includes comma
404 (@derives [$($derives:ident,)*]
408 @debug_format [$debug_format:tt]
409 $(#[doc = $doc:expr])*
410 const $name:ident = $constant:expr) => (
412 @derives [$($derives,)*]
416 @debug_format [$debug_format]
417 $(#[doc = $doc])* const $name = $constant,);
420 // Replace existing default for max
421 (@derives [$($derives:ident,)*]
425 @debug_format [$debug_format:tt]
429 @derives [$($derives,)*]
433 @debug_format [$debug_format]
437 // Replace existing default for debug_format
438 (@derives [$($derives:ident,)*]
442 @debug_format [$_debug_format:tt]
443 DEBUG_FORMAT = $debug_format:tt,
446 @derives [$($derives,)*]
450 @debug_format [$debug_format]
454 // Assign a user-defined constant
455 (@derives [$($derives:ident,)*]
459 @debug_format [$debug_format:tt]
460 $(#[doc = $doc:expr])*
461 const $name:ident = $constant:expr,
464 pub const $name: $type = $type::from_u32_const($constant);
466 @derives [$($derives,)*]
470 @debug_format [$debug_format]
475 #[derive(Clone, PartialEq, Eq, Hash)]
476 pub struct IndexVec<I: Idx, T> {
478 _marker: PhantomData<fn(&I)>
481 // Whether `IndexVec` is `Send` depends only on the data,
482 // not the phantom data.
483 unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}
485 impl<I: Idx, T: serialize::Encodable> serialize::Encodable for IndexVec<I, T> {
486 fn encode<S: serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
487 serialize::Encodable::encode(&self.raw, s)
491 impl<I: Idx, T: serialize::Decodable> serialize::Decodable for IndexVec<I, T> {
492 fn decode<D: serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
493 serialize::Decodable::decode(d).map(|v| {
494 IndexVec { raw: v, _marker: PhantomData }
499 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
500 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
501 fmt::Debug::fmt(&self.raw, fmt)
505 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
507 impl<I: Idx, T> IndexVec<I, T> {
509 pub fn new() -> Self {
510 IndexVec { raw: Vec::new(), _marker: PhantomData }
514 pub fn from_raw(raw: Vec<T>) -> Self {
515 IndexVec { raw, _marker: PhantomData }
519 pub fn with_capacity(capacity: usize) -> Self {
520 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
524 pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
527 IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
531 pub fn from_elem_n(elem: T, n: usize) -> Self
534 IndexVec { raw: vec![elem; n], _marker: PhantomData }
538 pub fn push(&mut self, d: T) -> I {
539 let idx = I::new(self.len());
545 pub fn pop(&mut self) -> Option<T> {
550 pub fn len(&self) -> usize {
554 /// Gives the next index that will be assigned when `push` is
557 pub fn next_index(&self) -> I {
562 pub fn is_empty(&self) -> bool {
567 pub fn into_iter(self) -> vec::IntoIter<T> {
572 pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>>
574 self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
578 pub fn iter(&self) -> slice::Iter<T> {
583 pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<'_, T>>
585 self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
589 pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
590 (0..self.len()).map(IntoIdx { _marker: PhantomData })
594 pub fn iter_mut(&mut self) -> slice::IterMut<T> {
599 pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<'_, T>>
601 self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
605 pub fn drain<'a, R: RangeBounds<usize>>(
606 &'a mut self, range: R) -> impl Iterator<Item=T> + 'a {
607 self.raw.drain(range)
611 pub fn drain_enumerated<'a, R: RangeBounds<usize>>(
612 &'a mut self, range: R) -> impl Iterator<Item=(I, T)> + 'a {
613 self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
617 pub fn last(&self) -> Option<I> {
618 self.len().checked_sub(1).map(I::new)
622 pub fn shrink_to_fit(&mut self) {
623 self.raw.shrink_to_fit()
627 pub fn swap(&mut self, a: I, b: I) {
628 self.raw.swap(a.index(), b.index())
632 pub fn truncate(&mut self, a: usize) {
637 pub fn get(&self, index: I) -> Option<&T> {
638 self.raw.get(index.index())
642 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
643 self.raw.get_mut(index.index())
646 /// Return mutable references to two distinct elements, a and b. Panics if a == b.
648 pub fn pick2_mut(&mut self, a: I, b: I) -> (&mut T, &mut T) {
649 let (ai, bi) = (a.index(), b.index());
653 let (c1, c2) = self.raw.split_at_mut(bi);
654 (&mut c1[ai], &mut c2[0])
656 let (c2, c1) = self.pick2_mut(b, a);
661 pub fn convert_index_type<Ix: Idx>(self) -> IndexVec<Ix, T> {
664 _marker: PhantomData,
669 impl<I: Idx, T: Clone> IndexVec<I, T> {
670 /// Grows the index vector so that it contains an entry for
671 /// `elem`; if that is already true, then has no
672 /// effect. Otherwise, inserts new values as needed by invoking
675 pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
676 let min_new_len = elem.index() + 1;
677 if self.len() < min_new_len {
678 self.raw.resize_with(min_new_len, fill_value);
683 pub fn resize(&mut self, new_len: usize, value: T) {
684 self.raw.resize(new_len, value)
688 pub fn resize_to_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) {
689 let min_new_len = elem.index() + 1;
690 self.raw.resize_with(min_new_len, fill_value);
694 impl<I: Idx, T: Ord> IndexVec<I, T> {
696 pub fn binary_search(&self, value: &T) -> Result<I, I> {
697 match self.raw.binary_search(value) {
698 Ok(i) => Ok(Idx::new(i)),
699 Err(i) => Err(Idx::new(i)),
704 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
708 fn index(&self, index: I) -> &T {
709 &self.raw[index.index()]
713 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
715 fn index_mut(&mut self, index: I) -> &mut T {
716 &mut self.raw[index.index()]
720 impl<I: Idx, T> Default for IndexVec<I, T> {
722 fn default() -> Self {
727 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
729 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
730 self.raw.extend(iter);
734 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
736 fn from_iter<J>(iter: J) -> Self where J: IntoIterator<Item=T> {
737 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
741 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
743 type IntoIter = vec::IntoIter<T>;
746 fn into_iter(self) -> vec::IntoIter<T> {
752 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
754 type IntoIter = slice::Iter<'a, T>;
757 fn into_iter(self) -> slice::Iter<'a, T> {
762 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
763 type Item = &'a mut T;
764 type IntoIter = slice::IterMut<'a, T>;
767 fn into_iter(self) -> slice::IterMut<'a, T> {
772 pub struct IntoIdx<I: Idx> { _marker: PhantomData<fn(&I)> }
773 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
774 type Output = (I, T);
776 extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
781 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
782 extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
787 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
790 extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
795 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
796 extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {