rust-lang / rust-lang/rust

less-than ideal representation for enums that contain a large element with multiple niches

Open
#145,128 1 comment 0 reactions 0 assignees View on GitHub

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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.