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

Experiment with transmute without black_box or #[inline(never)] #26

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
3 changes: 0 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@ oorandom = { version = "11.1.3", optional = true }
[dev-dependencies]
criterion = "0.5.1"

[profile.dev]
debug = false

[features]
default = []
download-more-ram = ["ureq"]
Expand Down
27 changes: 14 additions & 13 deletions src/transmute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,37 +20,38 @@
/// Finally, we take the `Box<A>`, interpreted as a `Box<B>`, out of the dangling reference and we've transmuted our data!
///
/// # Safety
///
/// lol
///
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,
// data: usize,
// }
// Note that `data` is shared between `DummyEnum::A` and `DummyEnum::B`.
// This should hopefully be more reliable than spamming the stack with a value and hoping the memory
// is placed correctly by the compiler.
/// The layout of `DummyEnum` is approximately:
///
/// ```ignore
/// DummyEnum {
/// is_a_or_b: u8,
/// data: usize,
/// }
/// ```
///
/// Note that `data` is shared between `DummyEnum::A` and `DummyEnum::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>>),
}

#[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()
}

transmute_inner(black_box(&mut DummyEnum::B(None)), obj)
transmute_inner(&mut DummyEnum::B(None), obj)
}

#[cfg(test)]
Expand Down