Skip to content

CTFE: there is no way to compute the difference between two ptrs in the same allocation if they might be out-of-bounds #92512

Open
@RalfJung

Description

@RalfJung

offset_from is the only way to do pointer subtraction during CTFE (since casting pointers to integers is not possible). However, offset_from requires both pointers to be in-bounds of the same allocation, making it unsuited for code that handles possibly out-of-bounds pointers. The need for this arises, for example, in the typical way that array/slice iterators support ZSTs, see e.g. slightlyoutofphase/staticvec#48.

We should provide some way for const code to subtract pointers to the same allocation even if they are not in-bounds. Example code:

const C: isize = {
    let start_ptr = &() as *const ();
    let length = 10;
    let end_ptr = (start_ptr as *const u8).wrapping_add(length) as *const ();
    unsafe { (end_ptr as *const u8).offset_from(start_ptr as *const u8) }
};

Also see this Zulip discussion.
Cc @rust-lang/wg-const-eval

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)A-raw-pointersArea: raw pointers, MaybeUninit, NonNullT-opsemRelevant to the opsem team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions