Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alignment at const time? #370

Open
joshlf opened this issue Oct 19, 2022 · 3 comments
Open

Alignment at const time? #370

joshlf opened this issue Oct 19, 2022 · 3 comments

Comments

@joshlf
Copy link

joshlf commented Oct 19, 2022

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.

@RalfJung
Copy link
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.)

@Lokathor
Copy link
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.

@RalfJung
Copy link
Member

RalfJung commented Oct 20, 2022

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants