rust-lang / rust-lang/rust

`size_of_val_raw` doesn't assume that `[u8]` has size at most `isize::MAX`

Open
#159,754 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-layout A-raw-pointers C-optimization needs-triage T-compiler T-opsem
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

#![feature(layout_for_ptr)]
use std::mem::size_of_val_raw;

#[unsafe(no_mangle)]
pub fn a(x: *const [u8]) -> bool {
    unsafe { size_of_val_raw(x) <= isize::MAX.cast_unsigned() }
}

#[unsafe(no_mangle)]
pub fn b(x: *const [u16]) -> bool {
    unsafe { size_of_val_raw(x) <= isize::MAX.cast_unsigned() }
}

I expected both functions to optimize to returning true, since the documentation for size_of_val_raw states that, for the operation to not be UB, the size of the slice must be at most isize::MAX.

Instead, only the b function optimizes to returning true.

Godbolt link

a:
        test    rsi, rsi
        setns   al
        ret

b:
        mov     al, 1
        ret
Meta

Reproducible on godbolt with version info:

rustc 1.99.0-nightly (0e29c21d9 2026-07-21)
binary: rustc
commit-hash: 0e29c21d93abc9bdc330182be1fbd33cfd5fee68
commit-date: 2026-07-21
host: x86_64-unknown-linux-gnu
release: 1.99.0-nightly
LLVM version: 22.1.8
Internal compiler ID: nightly

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 reduced functions a and b and compare their optimized output using the linked Godbolt reproduction. Read the documentation and implementation path for size_of_val_raw, focusing on how slice element types affect the isize::MAX validity assumption. Done means [u8] receives the same guaranteed-true optimization as [u16], with coverage for both cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.