use crate::slice::IndexSlice; use crate::Idx; use std::borrow::{Borrow, BorrowMut}; use std::fmt::{Debug, Formatter}; use std::marker::PhantomData; use std::ops::{Deref, DerefMut, RangeBounds}; /// An owned sequence of `T` indexed by `I` #[derive(Clone, PartialEq, Eq, Hash)] #[repr(transparent)] pub struct IndexVec { pub raw: Vec, index: PhantomData, } impl IndexVec { #[inline] pub fn new() -> Self { Self { raw: Vec::new(), index: PhantomData, } } #[inline] pub fn with_capacity(capacity: usize) -> Self { Self { raw: Vec::with_capacity(capacity), index: PhantomData, } } #[inline] pub fn from_raw(raw: Vec) -> Self { Self { raw, index: PhantomData, } } #[inline] pub fn drain>(&mut self, range: R) -> impl Iterator + '_ { self.raw.drain(range) } #[inline] pub fn truncate(&mut self, a: usize) { self.raw.truncate(a); } #[inline] pub fn as_slice(&self) -> &IndexSlice { IndexSlice::from_raw(&self.raw) } #[inline] pub fn as_mut_slice(&mut self) -> &mut IndexSlice { IndexSlice::from_raw_mut(&mut self.raw) } #[inline] pub fn push(&mut self, data: T) -> I { let index = self.next_index(); self.raw.push(data); index } #[inline] pub fn next_index(&self) -> I { I::new(self.raw.len()) } } impl Debug for IndexVec where T: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { std::fmt::Debug::fmt(&self.raw, f) } } impl Deref for IndexVec { type Target = IndexSlice; fn deref(&self) -> &Self::Target { self.as_slice() } } impl DerefMut for IndexVec { fn deref_mut(&mut self) -> &mut Self::Target { self.as_mut_slice() } } impl Borrow> for IndexVec { fn borrow(&self) -> &IndexSlice { self } } impl BorrowMut> for IndexVec { fn borrow_mut(&mut self) -> &mut IndexSlice { self } } impl Extend for IndexVec { #[inline] fn extend>(&mut self, iter: Iter) { self.raw.extend(iter); } } impl FromIterator for IndexVec { #[inline] fn from_iter>(iter: Iter) -> Self { Self::from_raw(Vec::from_iter(iter)) } } impl IntoIterator for IndexVec { type IntoIter = std::vec::IntoIter; type Item = T; #[inline] fn into_iter(self) -> std::vec::IntoIter { self.raw.into_iter() } } impl<'a, I: Idx, T> IntoIterator for &'a IndexVec { type IntoIter = std::slice::Iter<'a, T>; type Item = &'a T; #[inline] fn into_iter(self) -> std::slice::Iter<'a, T> { self.iter() } } impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec { type IntoIter = std::slice::IterMut<'a, T>; type Item = &'a mut T; #[inline] fn into_iter(self) -> std::slice::IterMut<'a, T> { self.iter_mut() } } impl Default for IndexVec { #[inline] fn default() -> Self { IndexVec::new() } } impl From<[T; N]> for IndexVec { #[inline] fn from(array: [T; N]) -> Self { IndexVec::from_raw(array.into()) } } // Whether `IndexVec` is `Send` depends only on the data, // not the phantom data. #[allow(unsafe_code)] unsafe impl Send for IndexVec where T: Send {}