Skip to content

Alignment at const time? #370

Open
Open

Description

@joshlf

I have the following function:

fn aligned_to(bytes: &[u8], align: usize) -> bool {
    (bytes as *const _ as *const () as usize) % align == 0
}

I'd like to make it a const fn, but if I just do that without changing the implementation, the compiler complains:

error: pointers cannot be cast to integers during const eval
    --> src/lib.rs:1636:5
     |
1636 |     (bytes as *const _ as *const () as usize) % align == 0
     |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     |
     = note: at compile-time, pointers do not have an integer value
     = note: avoiding this restriction via `transmute`, `union`, or raw pointers leads to compile-time undefined behavior

This thread implies that there's no way to get this to work today (even by using unstable features). Is there intended to be a concept of alignment and const time? Will code like this ever be possible to write? This is relevant to zerocopy since I'd like to be able to do reference casts at const time where the target type has an alignment requirement greater than 1.

Activity

  1. RalfJung commented on Oct 19, 2022

    @RalfJung
    Member

    The best we could have is some kind of intrinsic guaranteed_aligned_to that can tell if the pointer is definitely sufficiently aligned, but might return false when the answer is impossible to give at const time. (This is similar to guaranteed_eq.)

  2. Lokathor commented on Oct 20, 2022

    @Lokathor
    Contributor

    This is needed to be able to safely re-interpret slice references and single references at compile time. I don't know what the answer is, but this is a huge deal for ergonomics if it can happen.

  3. RalfJung commented on Oct 20, 2022

    @RalfJung
    Member

    Also see rust-lang/rust#102795

    Note that even the thing that can happen will be much more limited than the runtime version. For example, when allocating a slice of u8, then no part of it will be 2-aligned. That is fundamental during const-eval and will never change. We simply cannot know if at runtime, the slice will be at an odd or even address, so any element on it might have an odd address and thus fail to be aligned.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions