Skip to content

Missed layout optimisation with multiple niches #119507

Open

Description

@GnomedDev

I tried this code:

use std::num::NonZeroU8;

struct Test {
    niche_one: NonZeroU8,
    niche_two: NonZeroU8,
}

fn main() {
    assert_eq!(
        std::mem::size_of::<Test>(),
        std::mem::size_of::<Option<Option<Test>>>()
    );
}

I expected this program to exit fine, and fit the tag of the second option in the available niche.
Instead, the program panics, as the second option wastes a byte of memory making it's own tag byte.

Meta

rustc --version --verbose:

rustc 1.77.0-nightly (e51e98dde 2023-12-31)
binary: rustc
commit-hash: e51e98dde6a60637b6a71b8105245b629ac3fe77
commit-date: 2023-12-31
host: x86_64-unknown-linux-gnu
release: 1.77.0-nightly
LLVM version: 17.0.6

Activity

  1. added
    needs-triageThis issue may need triage. Remove when done. See docs forge.rust-lang.org/release/issue-triaging
    on Jan 2, 2024
  2. added a commit that references this issue on Jan 2, 2024
  3. saethlin commented on Jan 2, 2024

    @saethlin
    Member

    I'm pretty sure we already have an issue for this, but I can't find one that's written clearly. #101567 was the first one that clearly looks like a duplicate when I was scrolling.

    The problem is that the rustc layout representation (in this case of Test) only represents a single contiguous niche with a single contiuous (albeit wrapping) range of niche values. That should be (probably is somewhere) tracked in an issue.

  4. added
    T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.
    A-layoutArea: Memory layout of types
    C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing such
    and removed
    C-bugCategory: This is a bug.
    needs-triageThis issue may need triage. Remove when done. See docs forge.rust-lang.org/release/issue-triaging
    on Jan 2, 2024
  5. added a commit that references this issue on Jan 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-layoutArea: Memory layout of typesC-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions