Get rid of niche selection's dependence on fields's order

This commit is contained in:
Adwin White 2024-09-18 17:30:27 +08:00
parent f6bcd094ab
commit 9ac23dde37
2 changed files with 24 additions and 9 deletions

View File

@ -527,15 +527,10 @@ struct TmpLayout<FieldIdx: Idx, VariantIdx: Idx> {
let count = let count =
(niche_variants.end().index() as u128 - niche_variants.start().index() as u128) + 1; (niche_variants.end().index() as u128 - niche_variants.start().index() as u128) + 1;
// Find the field with the largest niche // Use the largest niche in the largest variant.
let (field_index, niche, (niche_start, niche_scalar)) = variants[largest_variant_index] let niche = variant_layouts[largest_variant_index].largest_niche?;
.iter() let (niche_start, niche_scalar) = niche.reserve(dl, count)?;
.enumerate() let niche_offset = niche.offset;
.filter_map(|(j, field)| Some((j, field.largest_niche?)))
.max_by_key(|(_, niche)| niche.available(dl))
.and_then(|(j, niche)| Some((j, niche, niche.reserve(dl, count)?)))?;
let niche_offset =
niche.offset + variant_layouts[largest_variant_index].fields.offset(field_index);
let niche_size = niche.value.size(dl); let niche_size = niche.value.size(dl);
let size = variant_layouts[largest_variant_index].size.align_to(align.abi); let size = variant_layouts[largest_variant_index].size.align_to(align.abi);

View File

@ -209,6 +209,23 @@ struct ReorderEndNiche {
b: MiddleNiche4, b: MiddleNiche4,
} }
// We want that the niche selection doesn't depend on order of the fields. See issue #125630.
pub enum NicheFieldOrder1 {
A {
x: NonZero<u64>,
y: [NonZero<u64>; 2],
},
B([u64; 2]),
}
pub enum NicheFieldOrder2 {
A {
y: [NonZero<u64>; 2],
x: NonZero<u64>,
},
B([u64; 2]),
}
// standins for std types which we want to be laid out in a reasonable way // standins for std types which we want to be laid out in a reasonable way
struct RawVecDummy { struct RawVecDummy {
@ -260,6 +277,9 @@ pub fn main() {
size_of::<EnumWithMaybeUninhabitedVariant<()>>()); size_of::<EnumWithMaybeUninhabitedVariant<()>>());
assert_eq!(size_of::<NicheFilledEnumWithAbsentVariant>(), size_of::<&'static ()>()); assert_eq!(size_of::<NicheFilledEnumWithAbsentVariant>(), size_of::<&'static ()>());
assert_eq!(size_of::<NicheFieldOrder1>(), 24);
assert_eq!(size_of::<NicheFieldOrder2>(), 24);
assert_eq!(size_of::<Option<Option<(bool, &())>>>(), size_of::<(bool, &())>()); assert_eq!(size_of::<Option<Option<(bool, &())>>>(), size_of::<(bool, &())>());
assert_eq!(size_of::<Option<Option<(&(), bool)>>>(), size_of::<(bool, &())>()); assert_eq!(size_of::<Option<Option<(&(), bool)>>>(), size_of::<(bool, &())>());
assert_eq!(size_of::<Option<Option2<bool, &()>>>(), size_of::<(bool, &())>()); assert_eq!(size_of::<Option<Option2<bool, &()>>>(), size_of::<(bool, &())>());