rust-lang / rust-lang/rust

std::mem::size_of::<Result<char,u16>>() says 8 when 4 should be feasible

Open
#118,367 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-layout C-enhancement T-compiler
Dominant language
Rust
Stars
119k
Forks
16.2k
PR merge metrics
PR metrics pending

Description

I tried this code:

fn main() {
    println!("{}", std::mem::size_of::<Result<char,u16>>());
}

I expected to see this happen:

Expected it to print 4. Expected the Ok case to have the same representation as char. Expected the Err case to have a non-zero discriminant value in the upper 11 bits (upper 11 bits for char are always zero) and expected the u16 to reside in the two least significant bytes.

Instead, this happened:
Got 8, i.e. the compiler didn't make good use the top 11 bits of 32 bits that u16 doesn't occupy at all and that are zero for char, since char only uses the lower 21 bits.

There should be enough available discriminant bits that Option<Result<char,u16>> could have size 4, too.

Use case: Surfacing the unpaired surrogate as Err when decoding UTF-16.

Meta

Tried the current stable and nightly on https://play.rust-lang.org/?version=nightly&mode=release&edition=2021

It said:
Stable channel

Build using the Stable version: 1.74.0
Beta channel

Build using the Beta version: 1.75.0-beta.3

(2023-11-20 b66b7951b9b4258fc433)
Nightly channel

Build using the Nightly version: 1.76.0-nightly

(2023-11-26 6cf088810f66fff15d05)

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

Reproduce the reported layout with the provided std::mem::size_of::<Result<char,u16>>() example on the Rust Playground or a local nightly compiler. Investigate Rust's enum layout and niche optimization behavior; done means the requested Result and Option<Result<char,u16>> representations use 4 bytes without breaking layout guarantees.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
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.