1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
//! This crate helps with defining "newtype"-style wrappers around `usize` (or //! other integers), and `Vec<T>` so that some additional type safety can be //! gained at zero cost. //! //! It's was initially derived from some code in `rustc`, but has diverged since //! then. //! //! ## Example / Overview //! ```rust //! use index_vec::{IndexVec, index_vec}; //! //! index_vec::define_index_type! { //! // Define StrIdx to use only 32 bits internally (you can use usize, u16, //! // and even u8). //! pub struct StrIdx = u32; //! //! // The defaults are very reasonable, but this macro can let //! // you customize things quite a bit: //! //! // By default, creating a StrIdx would check an incoming `usize against //! // `u32::max_value()`, as u32 is the wrapped index type. Lets imagine that //! // StrIdx has to interface with an external system that uses signed ints. //! // We can change the checking behavior to complain on i32::max_value() //! // instead: //! MAX_INDEX = i32::max_value() as usize; //! //! // We can also disable checking all-together if we are more concerned with perf //! // than any overflow problems, or even do so, but only for debug builds: Quite //! // pointless here, but an okay example //! DISABLE_MAX_INDEX_CHECK = cfg!(not(debug_assertions)); //! //! // And more too, see this macro's docs for more info. //! } //! //! // Create a vector which can be accessed using `StrIdx`s. //! let mut strs: IndexVec<StrIdx, &'static str> = index_vec!["strs", "bar", "baz"]; //! //! // l is a `StrIdx` //! let l = strs.last_idx(); //! assert_eq!(strs[l], "baz"); //! //! let new_i = strs.push("quux"); //! assert_eq!(strs[new_i], "quux"); //! //! // Indices are mostly interoperable with `usize`, and support //! // a lot of what you might want to do to an index. //! //! // Comparison //! assert_eq!(StrIdx::new(0), 0usize); //1 //! // Addition //! assert_eq!(StrIdx::new(0) + 1, 1usize); //! //! // Subtraction //! assert_eq!(StrIdx::new(1) - 1, 0usize); //! //! // Wrapping //! assert_eq!(StrIdx::new(5) % strs.len(), 1usize); //! // ... //! ``` //! ## Background //! //! The goal is to help with the pattern of using a `type FooIdx = usize` to //! access a `Vec<Foo>` with something that can statically prevent using a //! `FooIdx` in a `Vec<Bar>`. It's most useful if you have a bunch of indices //! referring to different sorts of vectors. //! //! Much of the code for this is taken from `rustc`'s `IndexVec` code, however //! it's diverged a decent amount at this point. Some notable changes: //! //! - No usage of unstable features. //! - Different syntax for defining index types. //! - More complete mirroring of Vec's API. //! - Allows use of using other index types than `u32`/`usize`. //! - More flexible behavior around how strictly some checks are performed, //! //! ## Other crates //! //! The [`indexed_vec`](https://crates.io/crates/indexed_vec) crate predates //! this, and is a much closer copy of the code from `rustc`. Unfortunately, //! this means it does not compile on stable. //! //! If you're looking for something further from a vec and closer to a map, you //! might find [`handy`](https://crates.io/crates/handy), //! [`slotmap`](https://crates.io/crates/slotmap), or //! [`slab`](https://crates.io/crates/slab) to be closer what you want. #![no_std] extern crate alloc; use alloc::vec; use alloc::vec::Vec; use core::fmt; use core::fmt::Debug; use core::hash::Hash; use core::iter::{self, FromIterator}; use core::marker::PhantomData; use core::ops::{Index, IndexMut, Range, RangeBounds}; use core::slice; use core::u32; #[macro_use] mod macros; pub use macros::*; #[cfg(feature = "example_generated")] pub mod example_generated; /// Represents a wrapped value convertable to and from a `usize`. /// /// Generally you implement this via the [`define_index_type!`] macro, rather /// than manually implementing it. /// /// # Overflow /// /// `Idx` impls are allowed to be smaller than `usize`, which means converting /// `usize` to an `Idx` implementation might have to handle overflow. /// /// The way overflow is handled is up to the implementation of `Idx`, but it's /// generally panicing, unless it was turned off via the `CHECK_MAX_INDEX_IF` /// parameter in `define_index_type`. /// /// This trait, as you can see, doesn't have a `try_from_usize`. The `IndexVec` /// type doesn't have additional functions exposing ways to handle index /// overflow. I'm open to adding these, but at the moment you should pick a size /// large enough that you won't hit problems, or verify the size cannot overflow /// elsewhere. pub trait Idx: Copy + 'static + Ord + Debug + Hash { /// Equivalent to From<usize> fn from_usize(idx: usize) -> Self; /// Equivalent to Into<usize> fn index(self) -> usize; } // XXX: Hrm... impl Idx for usize { #[inline] fn from_usize(idx: usize) -> Self { idx } #[inline] fn index(self) -> usize { self } } impl Idx for u32 { #[inline] fn from_usize(idx: usize) -> Self { assert!(idx <= u32::max_value() as usize); idx as u32 } #[inline] fn index(self) -> usize { self as usize } } /// A Vec that only accepts indices of a specific type. /// /// This is a thin wrapper around `Vec`, to the point where the backing vec is a /// public property. This is in part because I know this API is not a complete /// mirror of Vec's (patches welcome). In the worst case, you can always do what /// you need to the Vec itself. #[derive(Clone, PartialEq, Eq, Hash)] pub struct IndexVec<I: Idx, T> { /// Our wrapped Vec. pub vec: Vec<T>, _marker: PhantomData<fn(&I)>, } // Whether `IndexVec` is `Send` depends only on the data, // not the phantom data. unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {} impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self.vec, fmt) } } type Enumerated<Iter, I, T> = iter::Map<iter::Enumerate<Iter>, (fn((usize, T)) -> (I, T))>; impl<I: Idx, T> IndexVec<I, T> { /// Construct a new IndexVec. #[inline] pub fn new() -> Self { IndexVec { vec: Vec::new(), _marker: PhantomData, } } /// Construct a `IndexVec` from a `Vec<T>`. /// /// Panics if it's length is too large for our index type. #[inline] pub fn from_vec(vec: Vec<T>) -> Self { // See if `I::from_usize` might be upset by this length. let _ = I::from_usize(vec.len()); IndexVec { vec, _marker: PhantomData, } } /// Construct an IndexVec that can hold at least `capacity` items before /// reallocating. See [`Vec::with_capacity`]. #[inline] pub fn with_capacity(capacity: usize) -> Self { IndexVec { vec: Vec::with_capacity(capacity), _marker: PhantomData, } } /// Get a the storage as a `&[T]` #[inline] pub fn as_slice(&self) -> &[T] { self.vec.as_slice() } /// Get a the storage as a `&mut [T]` #[inline] pub fn as_mut_slice(&mut self) -> &mut [T] { self.vec.as_mut_slice() } /// Push a new item onto the vector, and return it's index. #[inline] pub fn push(&mut self, d: T) -> I { let idx = I::from_usize(self.len()); self.vec.push(d); idx } /// Pops the last item off, returning it. See [`Vec::pop`]. #[inline] pub fn pop(&mut self) -> Option<T> { self.vec.pop() } /// Returns the length of our vector. #[inline] pub fn len(&self) -> usize { self.vec.len() } /// Returns true if we're empty. #[inline] pub fn is_empty(&self) -> bool { self.vec.is_empty() } /// Similar to `self.into_iter().enumerate()` but with indices of `I` and /// not `usize`. #[inline] pub fn into_iter_enumerated(self) -> Enumerated<vec::IntoIter<T>, I, T> { self.vec .into_iter() .enumerate() .map(|(i, t)| (Idx::from_usize(i), t)) } /// Get a iterator over reverences to our values. #[inline] pub fn iter(&self) -> slice::Iter<'_, T> { self.vec.iter() } /// Similar to `self.iter().enumerate()` but with indices of `I` and not /// `usize`. #[inline] pub fn iter_enumerated(&self) -> Enumerated<slice::Iter<'_, T>, I, &T> { self.vec .iter() .enumerate() .map(|(i, t)| (Idx::from_usize(i), t)) } /// Get an interator over all our indices. #[inline] pub fn indices(&self) -> iter::Map<Range<usize>, fn(usize) -> I> { (0..self.len()).map(Idx::from_usize) } /// Get a iterator over mut reverences to our values. #[inline] pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> { self.vec.iter_mut() } /// Similar to `self.iter_mut().enumerate()` but with indices of `I` and not /// `usize`. #[inline] pub fn iter_mut_enumerated(&mut self) -> Enumerated<slice::IterMut<'_, T>, I, &mut T> { self.vec .iter_mut() .enumerate() .map(|(i, t)| (Idx::from_usize(i), t)) } /// Return an iterator that removes the items from the requested range. See /// [`Vec::drain`]. #[inline] pub fn drain<R: RangeBounds<usize>>(&mut self, range: R) -> vec::Drain<'_, T> { self.vec.drain(range) } /// Similar to `self.drain(r).enumerate()` but with indices of `I` and not /// `usize`. #[inline] pub fn drain_enumerated<R: RangeBounds<usize>>( &mut self, range: R, ) -> Enumerated<vec::Drain<'_, T>, I, T> { self.vec .drain(range) .enumerate() .map(|(i, t)| (Idx::from_usize(i), t)) } /// Return the index of the last element, if we are not empty. #[inline] pub fn last(&self) -> Option<I> { self.len().checked_sub(1).map(I::from_usize) } /// Shrinks the capacity of the vector as much as possible. #[inline] pub fn shrink_to_fit(&mut self) { self.vec.shrink_to_fit() } /// Swaps two elements in our vector. #[inline] pub fn swap(&mut self, a: I, b: I) { self.vec.swap(a.index(), b.index()) } /// Shortens the vector, keeping the first `len` elements and dropping /// the rest. See [`Vec::truncate`] #[inline] pub fn truncate(&mut self, a: usize) { self.vec.truncate(a) } /// Clear our vector. See [`Vec::clear`]. #[inline] pub fn clear(&mut self) { self.vec.clear() } /// Reserve capacity for `c` more elements. See [`Vec::reserve`] #[inline] pub fn reserve(&mut self, c: usize) { self.vec.reserve(c) } /// Gives the next index that will be assigned when `push` is /// called. #[inline] pub fn next_idx(&self) -> I { I::from_usize(self.len()) } /// Return the index of the last element, or panic. #[inline] pub fn last_idx(&self) -> I { assert!(!self.is_empty()); I::from_usize(self.len() - 1) } /// Get a ref to the item at the provided index, or None for out of bounds. #[inline] pub fn get(&self, index: I) -> Option<&T> { self.vec.get(index.index()) } /// Get a mut ref to the item at the provided index, or None for out of /// bounds #[inline] pub fn get_mut(&mut self, index: I) -> Option<&mut T> { self.vec.get_mut(index.index()) } /// Resize ourselves in-place to `new_len`. See [`Vec::resize`]. #[inline] pub fn resize(&mut self, new_len: usize, value: T) where T: Clone, { self.vec.resize(new_len, value) } /// Resize ourselves in-place to `new_len`. See [`Vec::resize_with`]. #[inline] pub fn resize_with<F: FnMut() -> T>(&mut self, new_len: usize, f: F) { self.vec.resize_with(new_len, f) } /// Moves all the elements of `other` into `Self`, leaving `other` empty. /// See [`Vec::append`]. #[inline] pub fn append(&mut self, other: &mut Self) { self.vec.append(&mut other.vec) } /// Splits the collection into two at the given index. See /// [`Vec::split_off`]. #[inline] pub fn split_off(&mut self, idx: I) -> Self { Self::from_vec(self.vec.split_off(idx.index())) } /// Remove the item at `index`. See [`Vec::remove`]. #[inline] pub fn remove(&mut self, index: I) -> T { self.vec.remove(index.index()) } /// Insert an item at `index`. See [`Vec::insert`]. #[inline] pub fn insert(&mut self, index: I, element: T) { self.vec.insert(index.index(), element) } /// Remove the item at `index` without maintaining order. See [`Vec::swap_remove`]. #[inline] pub fn swap_remove(&mut self, index: I) -> T { self.vec.swap_remove(index.index()) } /// Call `slice::binary_search` converting the indices it gives us back as /// needed. #[inline] pub fn binary_search(&self, value: &T) -> Result<I, I> where T: Ord, { match self.vec.binary_search(value) { Ok(i) => Ok(Idx::from_usize(i)), Err(i) => Err(Idx::from_usize(i)), } } /// Append all items in the slice to the end of our vector. /// /// See [`Vec::extend_from_slice`]. #[inline] pub fn extend_from_slice(&mut self, other: &[T]) where T: Clone, { self.vec.extend_from_slice(other) } } impl<I: Idx, T> Index<I> for IndexVec<I, T> { type Output = T; #[inline] fn index(&self, index: I) -> &T { &self.vec[index.index()] } } impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> { #[inline] fn index_mut(&mut self, index: I) -> &mut T { &mut self.vec[index.index()] } } impl<I: Idx, T> Default for IndexVec<I, T> { #[inline] fn default() -> Self { Self::new() } } impl<I: Idx, T> Extend<T> for IndexVec<I, T> { #[inline] fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) { self.vec.extend(iter); } } impl<'a, I: Idx, T: 'a + Copy> Extend<&'a T> for IndexVec<I, T> { #[inline] fn extend<J: IntoIterator<Item = &'a T>>(&mut self, iter: J) { self.vec.extend(iter); } } impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> { #[inline] fn from_iter<J>(iter: J) -> Self where J: IntoIterator<Item = T>, { IndexVec { vec: FromIterator::from_iter(iter), _marker: PhantomData, } } } impl<I: Idx, T> IntoIterator for IndexVec<I, T> { type Item = T; type IntoIter = vec::IntoIter<T>; #[inline] fn into_iter(self) -> vec::IntoIter<T> { self.vec.into_iter() } } impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> { type Item = &'a T; type IntoIter = slice::Iter<'a, T>; #[inline] fn into_iter(self) -> slice::Iter<'a, T> { self.vec.iter() } } impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> { type Item = &'a mut T; type IntoIter = slice::IterMut<'a, T>; #[inline] fn into_iter(self) -> slice::IterMut<'a, T> { self.vec.iter_mut() } } impl<I: Idx, T> From<Vec<T>> for IndexVec<I, T> { #[inline] fn from(v: Vec<T>) -> Self { Self { vec: v, _marker: PhantomData, } } }