Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize transmute #31

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/lifetime_expansion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ pub const fn lifetime_translator<'a, 'b, T>(_val_a: &'a &'b (), val_b: &'b T) ->
}

/// This does the same thing as [`lifetime_translator`], just for mutable refs.
#[inline(never)]
pub fn lifetime_translator_mut<'a, 'b, T>(_val_a: &'a &'b (), val_b: &'b mut T) -> &'a mut T {
val_b
}
Expand Down
28 changes: 13 additions & 15 deletions src/transmute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,8 @@
/// # Safety
/// lol
///
#[allow(unused_assignments)]
pub fn transmute<A, B>(obj: A) -> B {
use std::hint::black_box;

// The layout of `DummyEnum` is approximately
// DummyEnum {
// is_a_or_b: u8,
Expand All @@ -34,23 +33,22 @@ pub fn transmute<A, B>(obj: A) -> B {
// This should hopefully be more reliable than spamming the stack with a value and hoping the memory
// is placed correctly by the compiler.
enum DummyEnum<A, B> {
A(Option<Box<A>>),
B(Option<Box<B>>),
A(Result<A, Option<Blank<A, B>>>),
B(Result<B, Option<Blank<A, B>>>),
}

#[inline(never)]
fn transmute_inner<A, B>(dummy: &mut DummyEnum<A, B>, obj: A) -> B {
let DummyEnum::B(ref_to_b) = dummy else {
unreachable!()
};
let ref_to_b = crate::lifetime_expansion::expand_mut(ref_to_b);
*dummy = DummyEnum::A(Some(Box::new(obj)));
black_box(dummy);

*ref_to_b.take().unwrap()
union Blank<A, B> {
_a: std::mem::ManuallyDrop<A>,
_b: std::mem::ManuallyDrop<B>,
}

transmute_inner(black_box(&mut DummyEnum::B(None)), obj)
let mut res = DummyEnum::B(Err(None));
let DummyEnum::B(ref_to_b) = &mut res else {
unreachable!()
};
let ref_to_b = crate::lifetime_expansion::expand_mut(ref_to_b);
res = DummyEnum::A(Ok(obj));
std::mem::replace(ref_to_b, Err(None)).ok().unwrap()
}

#[cfg(test)]
Expand Down