Skip to content

Commit

Permalink
Rewrite Box<T>::try_fold_with.
Browse files Browse the repository at this point in the history
It can be written more simply, without needing `unsafe`.
  • Loading branch information
nnethercote committed Oct 17, 2023
1 parent 0fdf384 commit fd35413
Showing 1 changed file with 3 additions and 11 deletions.
14 changes: 3 additions & 11 deletions compiler/rustc_type_ir/src/structural_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,17 +151,9 @@ impl<I: Interner, T: TypeVisitable<I>> TypeVisitable<I> for Lrc<T> {
}

impl<I: Interner, T: TypeFoldable<I>> TypeFoldable<I> for Box<T> {
fn try_fold_with<F: FallibleTypeFolder<I>>(self, folder: &mut F) -> Result<Self, F::Error> {
let raw = Box::into_raw(self);
Ok(unsafe {
// SAFETY: The raw pointer points to a valid value of type `T`.
let value = raw.read();
// SAFETY: Converts `Box<T>` to `Box<MaybeUninit<T>>` which is the
// inverse of `Box::assume_init()` and should be safe.
let raw: Box<mem::MaybeUninit<T>> = Box::from_raw(raw.cast());
// SAFETY: Write the mapped value back into the `Box`.
Box::write(raw, value.try_fold_with(folder)?)
})
fn try_fold_with<F: FallibleTypeFolder<I>>(mut self, folder: &mut F) -> Result<Self, F::Error> {
*self = (*self).try_fold_with(folder)?;
Ok(self)
}
}

Expand Down

0 comments on commit fd35413

Please sign in to comment.