4 // Tests that unions aren't subject to unsafe non-zero/niche-filling optimizations.
6 // For example, if a union `U` can contain both a `&T` and a `*const T`, there's definitely no
7 // bit-value that an `Option<U>` could reuse as `None`; this test makes sure that isn't done.
9 // Secondly, this tests the status quo (not a guarantee; subject to change!) to not apply such
10 // optimizations to types containing unions even if they're theoretically possible. (discussion:
11 // https://github.com/rust-lang/rust/issues/36394)
13 // Notably this nails down part of the behavior that `MaybeUninit` assumes: that a
14 // `Option<MaybeUninit<&u8>>` does not take advantage of non-zero optimization, and thus is a safe
17 use std::mem::{size_of, transmute};
23 union U2<A: Copy, B: Copy> {
28 // Option<E> uses a value other than 0 and 1 as None
36 // Unions do not participate in niche-filling/non-zero optimization...
37 assert!(size_of::<Option<U2<&u8, u8>>>() > size_of::<U2<&u8, u8>>());
38 assert!(size_of::<Option<U2<&u8, ()>>>() > size_of::<U2<&u8, ()>>());
39 assert!(size_of::<Option<U2<u8, E>>>() > size_of::<U2<u8, E>>());
41 // ...even when theoretically possible:
42 assert!(size_of::<Option<U1<&u8>>>() > size_of::<U1<&u8>>());
43 assert!(size_of::<Option<U2<&u8, &u8>>>() > size_of::<U2<&u8, &u8>>());
45 // The unused bits of the () variant can have any value.
46 let zeroed: U2<&u8, ()> = unsafe { transmute(std::ptr::null::<u8>()) };
48 if let None = Some(zeroed) {