Skip to content

Commit

Permalink
Experiment with transmute without black_box
Browse files Browse the repository at this point in the history
  • Loading branch information
Speykious committed Feb 24, 2024
1 parent 3d364e7 commit f213b5c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
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

0 comments on commit f213b5c

Please sign in to comment.