|
| 1 | +use crate::{Idx, IndexSlice, IndexVec}; |
| 2 | +use std::fmt::{Debug, Formatter}; |
| 3 | +use std::marker::PhantomData; |
| 4 | +use std::ops::{Deref, DerefMut}; |
| 5 | + |
| 6 | +/// A structurally immutable sequence of `T` indexed by `I`. |
| 7 | +#[derive(Clone, PartialEq, Eq, Hash, get_size2::GetSize)] |
| 8 | +pub struct FrozenIndexVec<I, T> { |
| 9 | + raw: Box<[T]>, |
| 10 | + index: PhantomData<I>, |
| 11 | +} |
| 12 | + |
| 13 | +impl<I: Idx, T> FrozenIndexVec<I, T> { |
| 14 | + #[inline] |
| 15 | + pub fn from_raw(raw: Box<[T]>) -> Self { |
| 16 | + Self { |
| 17 | + raw, |
| 18 | + index: PhantomData, |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + #[inline] |
| 23 | + pub fn as_slice(&self) -> &IndexSlice<I, T> { |
| 24 | + IndexSlice::from_raw(&self.raw) |
| 25 | + } |
| 26 | + |
| 27 | + #[inline] |
| 28 | + pub fn as_mut_slice(&mut self) -> &mut IndexSlice<I, T> { |
| 29 | + IndexSlice::from_raw_mut(&mut self.raw) |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +impl<I, T> Debug for FrozenIndexVec<I, T> |
| 34 | +where |
| 35 | + T: Debug, |
| 36 | +{ |
| 37 | + fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { |
| 38 | + std::fmt::Debug::fmt(&self.raw, f) |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +impl<I: Idx, T> Deref for FrozenIndexVec<I, T> { |
| 43 | + type Target = IndexSlice<I, T>; |
| 44 | + |
| 45 | + #[inline] |
| 46 | + fn deref(&self) -> &Self::Target { |
| 47 | + self.as_slice() |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl<I: Idx, T> DerefMut for FrozenIndexVec<I, T> { |
| 52 | + #[inline] |
| 53 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 54 | + self.as_mut_slice() |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +impl<I: Idx, T> From<IndexVec<I, T>> for FrozenIndexVec<I, T> { |
| 59 | + #[inline] |
| 60 | + fn from(vec: IndexVec<I, T>) -> Self { |
| 61 | + Self::from_raw(vec.raw.into_boxed_slice()) |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +impl<I: Idx, T> FromIterator<T> for FrozenIndexVec<I, T> { |
| 66 | + #[inline] |
| 67 | + fn from_iter<Iter: IntoIterator<Item = T>>(iter: Iter) -> Self { |
| 68 | + Self::from_raw(iter.into_iter().collect()) |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +// Whether `FrozenIndexVec` is `Send` depends only on the data, |
| 73 | +// not the phantom data. |
| 74 | +#[expect(unsafe_code)] |
| 75 | +unsafe impl<I: Idx, T> Send for FrozenIndexVec<I, T> where T: Send {} |
| 76 | + |
| 77 | +#[expect(unsafe_code)] |
| 78 | +#[cfg(feature = "salsa")] |
| 79 | +unsafe impl<I, T> salsa::Update for FrozenIndexVec<I, T> |
| 80 | +where |
| 81 | + T: salsa::Update, |
| 82 | +{ |
| 83 | + #[expect(unsafe_code)] |
| 84 | + unsafe fn maybe_update(old_pointer: *mut Self, new_value: Self) -> bool { |
| 85 | + let old_box: &mut FrozenIndexVec<I, T> = unsafe { &mut *old_pointer }; |
| 86 | + unsafe { salsa::Update::maybe_update(&raw mut old_box.raw, new_value.raw) } |
| 87 | + } |
| 88 | +} |
0 commit comments