1 use rustc_index::vec::{Idx, IndexVec};
4 pub trait IdFunctor: Sized {
7 fn try_map_id<F, E>(self, f: F) -> Result<Self, E>
9 F: FnMut(Self::Inner) -> Result<Self::Inner, E>;
12 impl<T> IdFunctor for Box<T> {
16 fn try_map_id<F, E>(self, mut f: F) -> Result<Self, E>
18 F: FnMut(Self::Inner) -> Result<Self::Inner, E>,
20 let raw = Box::into_raw(self);
22 // SAFETY: The raw pointer points to a valid value of type `T`.
23 let value = raw.read();
24 // SAFETY: Converts `Box<T>` to `Box<MaybeUninit<T>>` which is the
25 // inverse of `Box::assume_init()` and should be safe.
26 let raw: Box<mem::MaybeUninit<T>> = Box::from_raw(raw.cast());
27 // SAFETY: Write the mapped value back into the `Box`.
28 Box::write(raw, f(value)?)
33 impl<T> IdFunctor for Vec<T> {
37 fn try_map_id<F, E>(self, mut f: F) -> Result<Self, E>
39 F: FnMut(Self::Inner) -> Result<Self::Inner, E>,
42 vec: Vec<mem::ManuallyDrop<T>>,
46 impl<T> Drop for HoleVec<T> {
49 for (index, slot) in self.vec.iter_mut().enumerate() {
50 if self.hole != Some(index) {
51 mem::ManuallyDrop::drop(slot);
59 let (ptr, length, capacity) = self.into_raw_parts();
60 let vec = Vec::from_raw_parts(ptr.cast(), length, capacity);
61 let mut hole_vec = HoleVec { vec, hole: None };
63 for (index, slot) in hole_vec.vec.iter_mut().enumerate() {
64 hole_vec.hole = Some(index);
65 let original = mem::ManuallyDrop::take(slot);
66 let mapped = f(original)?;
67 *slot = mem::ManuallyDrop::new(mapped);
71 mem::forget(hole_vec);
72 Ok(Vec::from_raw_parts(ptr, length, capacity))
77 impl<T> IdFunctor for Box<[T]> {
81 fn try_map_id<F, E>(self, f: F) -> Result<Self, E>
83 F: FnMut(Self::Inner) -> Result<Self::Inner, E>,
85 Vec::from(self).try_map_id(f).map(Into::into)
89 impl<I: Idx, T> IdFunctor for IndexVec<I, T> {
93 fn try_map_id<F, E>(self, f: F) -> Result<Self, E>
95 F: FnMut(Self::Inner) -> Result<Self::Inner, E>,
97 self.raw.try_map_id(f).map(IndexVec::from_raw)