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.
11 use std::collections::range::RangeArgument;
13 use std::iter::{self, FromIterator};
15 use std::marker::PhantomData;
16 use std::ops::{Index, IndexMut, Range};
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 + Eq + Debug {
27 fn new(idx: usize) -> Self;
28 fn index(self) -> usize;
32 fn new(idx: usize) -> Self { idx }
33 fn index(self) -> usize { self }
37 fn new(idx: usize) -> Self { assert!(idx <= u32::MAX as usize); idx as u32 }
38 fn index(self) -> usize { self as usize }
42 macro_rules! newtype_index {
43 // ---- public rules ----
45 // Use default constants
48 // Leave out derives marker so we can use its absence to ensure it comes first
51 @max [::std::u32::MAX]
52 @debug_format ["{}"]);
55 ($name:ident nopub) => (
57 // Leave out derives marker so we can use its absence to ensure it comes first
60 @max [::std::u32::MAX]
61 @debug_format ["{}"]);
64 // Define any constants
65 ($name:ident { $($tokens:tt)+ }) => (
67 // Leave out derives marker so we can use its absence to ensure it comes first
70 @max [::std::u32::MAX]
75 // Define any constants
76 ($name:ident nopub { $($tokens:tt)+ }) => (
78 // Leave out derives marker so we can use its absence to ensure it comes first
81 @max [::std::u32::MAX]
82 @debug_format [unsafe {::std::intrinsics::type_name::<$name>() }]
86 // ---- private rules ----
88 // Base case, user-defined constants (if any) have already been defined
89 (@derives [$($derives:ident,)*]
93 @debug_format [$debug_format:expr]) => (
94 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, $($derives),*)]
95 pub struct $type($($pub)* u32);
98 fn new(value: usize) -> Self {
99 assert!(value < ($max) as usize);
103 fn index(self) -> usize {
110 @derives [$($derives,)*]
112 @debug_format [$debug_format]);
115 // base case for handle_debug where format is custom. No Debug implementation is emitted.
117 @derives [$($_derives:ident,)*]
119 @debug_format [custom]) => ();
121 // base case for handle_debug, no debug overrides found, so use default
125 @debug_format [$debug_format:expr]) => (
126 impl ::std::fmt::Debug for $type {
127 fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
128 write!(fmt, $debug_format, self.0)
133 // Debug is requested for derive, don't generate any Debug implementation.
135 @derives [Debug, $($derives:ident,)*]
137 @debug_format [$debug_format:expr]) => ();
139 // It's not Debug, so just pop it off the front of the derives stack and check the rest.
141 @derives [$_derive:ident, $($derives:ident,)*]
143 @debug_format [$debug_format:expr]) => (
146 @derives [$($derives,)*]
148 @debug_format [$debug_format]);
151 // Append comma to end of derives list if it's missing
155 @debug_format [$debug_format:expr]
156 derive [$($derives:ident),*]
162 @debug_format [$debug_format]
163 derive [$($derives,)*]
167 // By not including the @derives marker in this list nor in the default args, we can force it
168 // to come first if it exists. When encodable is custom, just use the derives list as-is.
172 @debug_format [$debug_format:expr]
173 derive [$($derives:ident,)+]
177 @derives [$($derives,)+]
181 @debug_format [$debug_format]
185 // By not including the @derives marker in this list nor in the default args, we can force it
186 // to come first if it exists. When encodable isn't custom, add serialization traits by default.
190 @debug_format [$debug_format:expr]
191 derive [$($derives:ident,)+]
194 @derives [$($derives,)+ RustcDecodable, RustcEncodable,]
198 @debug_format [$debug_format]
202 // The case where no derives are added, but encodable is overriden. Don't
203 // derive serialization traits
207 @debug_format [$debug_format:expr]
215 @debug_format [$debug_format]
219 // The case where no derives are added, add serialization derives by default
223 @debug_format [$debug_format:expr]
226 @derives [RustcDecodable, RustcEncodable,]
230 @debug_format [$debug_format]
234 // Rewrite final without comma to one that includes comma
235 (@derives [$($derives:ident,)*]
239 @debug_format [$debug_format:expr]
240 $name:ident = $constant:expr) => (
242 @derives [$($derives,)*]
246 @debug_format [$debug_format]
250 // Rewrite final const without comma to one that includes comma
251 (@derives [$($derives:ident,)*]
255 @debug_format [$debug_format:expr]
256 $(#[doc = $doc:expr])*
257 const $name:ident = $constant:expr) => (
259 @derives [$($derives,)*]
263 @debug_format [$debug_format]
264 $(#[doc = $doc])* const $name = $constant,);
267 // Replace existing default for max
268 (@derives [$($derives:ident,)*]
272 @debug_format [$debug_format:expr]
276 @derives [$($derives,)*]
280 @debug_format [$debug_format]
284 // Replace existing default for debug_format
285 (@derives [$($derives:ident,)*]
289 @debug_format [$_debug_format:expr]
290 DEBUG_FORMAT = $debug_format:expr,
293 @derives [$($derives,)*]
297 @debug_format [$debug_format]
301 // Assign a user-defined constant
302 (@derives [$($derives:ident,)*]
306 @debug_format [$debug_format:expr]
307 $(#[doc = $doc:expr])*
308 const $name:ident = $constant:expr,
311 pub const $name: $type = $type($constant);
313 @derives [$($derives,)*]
317 @debug_format [$debug_format]
322 #[derive(Clone, PartialEq, Eq)]
323 pub struct IndexVec<I: Idx, T> {
325 _marker: PhantomData<Fn(&I)>
328 impl<I: Idx, T: serialize::Encodable> serialize::Encodable for IndexVec<I, T> {
329 fn encode<S: serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
330 serialize::Encodable::encode(&self.raw, s)
334 impl<I: Idx, T: serialize::Decodable> serialize::Decodable for IndexVec<I, T> {
335 fn decode<D: serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
336 serialize::Decodable::decode(d).map(|v| {
337 IndexVec { raw: v, _marker: PhantomData }
342 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
343 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
344 fmt::Debug::fmt(&self.raw, fmt)
348 pub type Enumerated<I, J> = iter::Map<iter::Enumerate<J>, IntoIdx<I>>;
350 impl<I: Idx, T> IndexVec<I, T> {
352 pub fn new() -> Self {
353 IndexVec { raw: Vec::new(), _marker: PhantomData }
357 pub fn with_capacity(capacity: usize) -> Self {
358 IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
362 pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
365 IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
369 pub fn from_elem_n(elem: T, n: usize) -> Self
372 IndexVec { raw: vec![elem; n], _marker: PhantomData }
376 pub fn push(&mut self, d: T) -> I {
377 let idx = I::new(self.len());
383 pub fn len(&self) -> usize {
388 pub fn is_empty(&self) -> bool {
393 pub fn into_iter(self) -> vec::IntoIter<T> {
398 pub fn into_iter_enumerated(self) -> Enumerated<I, vec::IntoIter<T>>
400 self.raw.into_iter().enumerate().map(IntoIdx { _marker: PhantomData })
404 pub fn iter(&self) -> slice::Iter<T> {
409 pub fn iter_enumerated(&self) -> Enumerated<I, slice::Iter<T>>
411 self.raw.iter().enumerate().map(IntoIdx { _marker: PhantomData })
415 pub fn indices(&self) -> iter::Map<Range<usize>, IntoIdx<I>> {
416 (0..self.len()).map(IntoIdx { _marker: PhantomData })
420 pub fn iter_mut(&mut self) -> slice::IterMut<T> {
425 pub fn iter_enumerated_mut(&mut self) -> Enumerated<I, slice::IterMut<T>>
427 self.raw.iter_mut().enumerate().map(IntoIdx { _marker: PhantomData })
431 pub fn drain<'a, R: RangeArgument<usize>>(
432 &'a mut self, range: R) -> impl Iterator<Item=T> + 'a {
433 self.raw.drain(range)
437 pub fn drain_enumerated<'a, R: RangeArgument<usize>>(
438 &'a mut self, range: R) -> impl Iterator<Item=(I, T)> + 'a {
439 self.raw.drain(range).enumerate().map(IntoIdx { _marker: PhantomData })
443 pub fn last(&self) -> Option<I> {
444 self.len().checked_sub(1).map(I::new)
448 pub fn shrink_to_fit(&mut self) {
449 self.raw.shrink_to_fit()
453 pub fn swap(&mut self, a: usize, b: usize) {
458 pub fn truncate(&mut self, a: usize) {
463 pub fn get(&self, index: I) -> Option<&T> {
464 self.raw.get(index.index())
468 pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
469 self.raw.get_mut(index.index())
473 impl<I: Idx, T: Clone> IndexVec<I, T> {
475 pub fn resize(&mut self, new_len: usize, value: T) {
476 self.raw.resize(new_len, value)
480 impl<I: Idx, T: Ord> IndexVec<I, T> {
482 pub fn binary_search(&self, value: &T) -> Result<I, I> {
483 match self.raw.binary_search(value) {
484 Ok(i) => Ok(Idx::new(i)),
485 Err(i) => Err(Idx::new(i)),
490 impl<I: Idx, T> Index<I> for IndexVec<I, T> {
494 fn index(&self, index: I) -> &T {
495 &self.raw[index.index()]
499 impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
501 fn index_mut(&mut self, index: I) -> &mut T {
502 &mut self.raw[index.index()]
506 impl<I: Idx, T> Default for IndexVec<I, T> {
508 fn default() -> Self {
513 impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
515 fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
516 self.raw.extend(iter);
520 impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
522 fn from_iter<J>(iter: J) -> Self where J: IntoIterator<Item=T> {
523 IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
527 impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
529 type IntoIter = vec::IntoIter<T>;
532 fn into_iter(self) -> vec::IntoIter<T> {
538 impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
540 type IntoIter = slice::Iter<'a, T>;
543 fn into_iter(self) -> slice::Iter<'a, T> {
548 impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
549 type Item = &'a mut T;
550 type IntoIter = slice::IterMut<'a, T>;
553 fn into_iter(self) -> slice::IterMut<'a, T> {
558 pub struct IntoIdx<I: Idx> { _marker: PhantomData<fn(&I)> }
559 impl<I: Idx, T> FnOnce<((usize, T),)> for IntoIdx<I> {
560 type Output = (I, T);
562 extern "rust-call" fn call_once(self, ((n, t),): ((usize, T),)) -> Self::Output {
567 impl<I: Idx, T> FnMut<((usize, T),)> for IntoIdx<I> {
568 extern "rust-call" fn call_mut(&mut self, ((n, t),): ((usize, T),)) -> Self::Output {
573 impl<I: Idx> FnOnce<(usize,)> for IntoIdx<I> {
576 extern "rust-call" fn call_once(self, (n,): (usize,)) -> Self::Output {
581 impl<I: Idx> FnMut<(usize,)> for IntoIdx<I> {
582 extern "rust-call" fn call_mut(&mut self, (n,): (usize,)) -> Self::Output {