less-than ideal representation for enums that contain a large element with multiple niches
Open
Nobody has claimed this yet.
A-enum
A-layout
C-optimization
T-compiler
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
I tried this code:
use std::num::NonZero;
enum Enum {
BigWithNiches((NonZero<u32>, NonZero<u32>)),
Small1(u16),
Small2(u16),
}
fn main() {
dbg!(size_of::<Enum>(), size_of::<Union>());
}
#[repr(C)]
union Union {
big_with_niches: (NonZero<u32>, NonZero<u32>),
small: (u32, u16, u16),
}
impl Union {
fn as_enum(self) -> Enum {
let (niche, tag, val) = unsafe { self.small };
if niche == 0 {
if tag == 0 {
Enum::Small1(val)
} else {
Enum::Small2(val)
}
} else {
Enum::BigWithNiches(unsafe { self.big_with_niches })
}
}
}
I expected to see this happen: Both datatypes are the same size
Instead, this happened: rustc is not able to find the optimization that the union implements manually
Meta
rustc --version --verbose:
1.91.0-nightly
(2025-08-07 2fd855fbfc8239285aa2)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the provided Rust reproducer and run it with the reported nightly compiler, comparing the sizes printed for Enum and Union. Trace rustc's enum layout and niche optimization handling; done means the compiler can represent these types at the same size, or the limitation is clearly documented.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100