This challenge was quite fun and tricky but I eventually found a way to do it. The most important trick was to exploit Implied bounds on nested references + variance = soundness hole · Issue #25860 to transform &'a T
to &'static T
just as the fake_static
crate does. That can then be combined with enums to implement transmute
with only safe Rust code, something like:
pub fn transmute<T, U>(e: T) -> U {
// Store a None `U` value and get a reference to it:
let mut value: Result<Cell<Option<U>>, Cell<Option<T>>> = Ok(Cell::new(None));
let u_ref: &Cell<Option<U>> = if let Ok(v) = &value { make_static(v) } else { unreachable!() };
// Store a Some `T` value:
value = Err(Cell::new(Some(e)));
// Use our previous `U` reference to access the stored `T` value:
u_ref.take().unwrap()
}