Skip to content

Commit

Permalink
test that coercions still work under randomization
Browse files Browse the repository at this point in the history
  • Loading branch information
the8472 committed Jan 8, 2025
1 parent 0a7f326 commit 3b702c1
Showing 1 changed file with 26 additions and 7 deletions.
33 changes: 26 additions & 7 deletions tests/ui/layout/randomize.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
//@ build-pass
//@ run-pass
//@ revisions: normal randomize-layout
//@ [randomize-layout]compile-flags: -Zrandomize-layout
//@ [randomize-layout]compile-flags: -Zrandomize-layout -Zlayout-seed=1

#![crate_type = "lib"]
use std::ptr;

struct Foo<T>(u32, T, u8);

struct Wrapper<T>(T);

// these types only have their field offsets taken, they're never constructed
#[allow(dead_code)]
pub struct Foo<T>(u32, T, u8);
#[allow(dead_code)]
pub struct Wrapper<T>(T);
#[repr(transparent)]
struct TransparentWrapper(u16);
#[allow(dead_code)]
pub struct TransparentWrapper(u16);

const _: () = {
// fn pointers are treated interchangably and don't affect layout
assert!(std::mem::offset_of!(Foo::<fn(u32)>, 1) == std::mem::offset_of!(Foo::<fn() -> usize>, 1));

// behavior of the current implementation, not guaranteed
#[cfg(not(randomize_layout))]
assert!(std::mem::offset_of!(Foo::<u16>, 1) == std::mem::offset_of!(Foo::<Wrapper<u16>>, 1));
Expand All @@ -28,3 +34,16 @@ const _: () = {
std::mem::offset_of!(Foo::<u16>, 1) != std::mem::offset_of!(Foo::<TransparentWrapper>, 1)
);
};

#[allow(dead_code)]
struct Unsizable<T: ?Sized>(usize, T);

fn main() {
// offset_of doesn't let us probe the unsized field, check at runtime.
let x = &Unsizable::<[u32; 4]>(0, [0; 4]);
let y: &Unsizable::<[u32]> = x;

// type coercion must not change the layout.
assert_eq!(ptr::from_ref(&x.1).addr(), ptr::from_ref(&y.1).addr());

}

0 comments on commit 3b702c1

Please sign in to comment.