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, f: F) -> Result<Self, E>
39 F: FnMut(Self::Inner) -> Result<Self::Inner, E>,
41 self.into_iter().map(f).collect()
45 impl<T> IdFunctor for Box<[T]> {
49 fn try_map_id<F, E>(self, f: F) -> Result<Self, E>
51 F: FnMut(Self::Inner) -> Result<Self::Inner, E>,
53 Vec::from(self).try_map_id(f).map(Into::into)
57 impl<I: Idx, T> IdFunctor for IndexVec<I, T> {
61 fn try_map_id<F, E>(self, f: F) -> Result<Self, E>
63 F: FnMut(Self::Inner) -> Result<Self::Inner, E>,
65 self.raw.try_map_id(f).map(IndexVec::from_raw)