|
| 1 | +//@ run-pass |
| 2 | + |
| 3 | +#![allow(dead_code)] |
| 4 | + |
| 5 | +use std::{alloc::Layout, ffi::c_int, mem::MaybeUninit, ptr}; |
| 6 | + |
| 7 | +// A simple uninhabited type. |
| 8 | +enum Void {} |
| 9 | + |
| 10 | +#[repr(C)] |
| 11 | +enum Univariant<T> { |
| 12 | + Variant(T), |
| 13 | +} |
| 14 | + |
| 15 | +#[repr(C, u8)] |
| 16 | +enum UnivariantU8<T> { |
| 17 | + Variant(T), |
| 18 | +} |
| 19 | + |
| 20 | +#[repr(C)] |
| 21 | +enum TwoVariants<T> { |
| 22 | + Variant1(T), |
| 23 | + Variant2(u8), |
| 24 | +} |
| 25 | + |
| 26 | +#[repr(C, u8)] |
| 27 | +enum TwoVariantsU8<T> { |
| 28 | + Variant1(T), |
| 29 | + Variant2(u8), |
| 30 | +} |
| 31 | + |
| 32 | +#[repr(C, u8)] |
| 33 | +enum DeadBranchHasOtherField<T> { |
| 34 | + Variant1(T, u64), |
| 35 | + Variant2(u8), |
| 36 | +} |
| 37 | + |
| 38 | +macro_rules! assert_layout_eq { |
| 39 | + ($a:ty, $b:ty) => { |
| 40 | + assert_eq!(Layout::new::<$a>(), Layout::new::<$b>()); |
| 41 | + }; |
| 42 | +} |
| 43 | + |
| 44 | +fn main() { |
| 45 | + // Compiler must not remove dead variants of `#[repr(C)]` ADTs. |
| 46 | + assert_layout_eq!(Univariant<Void>, c_int); |
| 47 | + // This should also hold for `#[repr(C, int)]` ADTs. |
| 48 | + assert_layout_eq!(UnivariantU8<Void>, u8); |
| 49 | + // And for ADTs with more than one variant. |
| 50 | + // These are twice the size: a tag plus the field in a second branch. |
| 51 | + assert_layout_eq!(TwoVariants<Void>, [c_int; 2]); |
| 52 | + assert_layout_eq!(TwoVariantsU8<Void>, [u8; 2]); |
| 53 | + // This one is 2 x u64: we reserve space for fields in a dead branch. |
| 54 | + assert_layout_eq!(DeadBranchHasOtherField<Void>, [u64; 2]); |
| 55 | + |
| 56 | + // Some other useful invariants. See this UCG thread for more context: |
| 57 | + // https://github.com/rust-lang/unsafe-code-guidelines/issues/500 |
| 58 | + assert_layout_eq!(Univariant<Void>, Univariant<MaybeUninit<Void>>); |
| 59 | + assert_layout_eq!(UnivariantU8<Void>, UnivariantU8<MaybeUninit<Void>>); |
| 60 | + assert_layout_eq!(TwoVariants<Void>, TwoVariants<MaybeUninit<Void>>); |
| 61 | + assert_layout_eq!(TwoVariantsU8<Void>, TwoVariantsU8<MaybeUninit<Void>>); |
| 62 | + assert_layout_eq!(DeadBranchHasOtherField<Void>, DeadBranchHasOtherField<MaybeUninit<Void>>); |
| 63 | + |
| 64 | + // Check that discriminants are allocated properly. |
| 65 | + // SAFETY: |
| 66 | + // 1. We checked that layout requires proper alignment. |
| 67 | + // 2. Discriminant is guaranteed to be the first field of a `#[repr(C)]` enum. |
| 68 | + unsafe { |
| 69 | + assert_eq!(*ptr::from_ref(&TwoVariants::<Void>::Variant2(42)).cast::<c_int>(), 1); |
| 70 | + assert_eq!(*ptr::from_ref(&TwoVariantsU8::<Void>::Variant2(42)).cast::<u8>(), 1); |
| 71 | + assert_eq!(*ptr::from_ref(&DeadBranchHasOtherField::<Void>::Variant2(42)).cast::<u8>(), 1); |
| 72 | + } |
| 73 | +} |
0 commit comments