]> git.lizzy.rs Git - rust.git/blob - tests/ui/packed/packed-struct-optimized-enum.rs
Rollup merge of #107576 - P1n3appl3:master, r=tmandry
[rust.git] / tests / ui / packed / packed-struct-optimized-enum.rs
1 // run-pass
2 #[repr(packed)]
3 struct Packed<T: Copy>(#[allow(unused_tuple_struct_fields)] T);
4
5 impl<T: Copy> Copy for Packed<T> {}
6 impl<T: Copy> Clone for Packed<T> {
7     fn clone(&self) -> Self { *self }
8 }
9
10 fn sanity_check_size<T: Copy>(one: T) {
11     let two = [one, one];
12     let stride = (&two[1] as *const _ as usize) - (&two[0] as *const _ as usize);
13     let (size, align) = (std::mem::size_of::<T>(), std::mem::align_of::<T>());
14     assert_eq!(stride, size);
15     assert_eq!(size % align, 0);
16 }
17
18 fn main() {
19     // This can fail if rustc and LLVM disagree on the size of a type.
20     // In this case, `Option<Packed<(&(), u32)>>` was erroneously not
21     // marked as packed despite needing alignment `1` and containing
22     // its `&()` discriminant, which has alignment larger than `1`.
23     sanity_check_size((Some(Packed((&(), 0))), true));
24
25     // In #46769, `Option<(Packed<&()>, bool)>` was found to have
26     // pointer alignment, without actually being aligned in size.
27     // e.g., on 64-bit platforms, it had alignment `8` but size `9`.
28     type PackedRefAndBool<'a> = (Packed<&'a ()>, bool);
29     sanity_check_size::<Option<PackedRefAndBool>>(Some((Packed(&()), true)));
30
31     // Make sure we don't pay for the enum optimization in size,
32     // e.g., we shouldn't need extra padding after the packed data.
33     assert_eq!(std::mem::align_of::<Option<PackedRefAndBool>>(), 1);
34     assert_eq!(std::mem::size_of::<Option<PackedRefAndBool>>(),
35                std::mem::size_of::<PackedRefAndBool>());
36 }