Pointer with niche for unaligned values?

⚓ rust    📅 2025-06-13    👤 surdeus    👁️ 2      

surdeus

I have a struct containing only a pointer to an allocated thing on the heap (think of it kind of like a Box with a fixed inner type), and that allocated thing has an alignment greater than 1. So I know that the pointer will never be null, nor will it ever have an odd address. I'd like to figure out how to express this in a way that the compiler is able to use as a niche for optimizing the layout of structs/enums.

I've found that NonNull<MyTy> enforces the pointer to not be null, such that Option<NonNull<MyTy>> also only needs 8 bytes (and same for things that wrap it, like Box<MyTy>). So right now I have this:

#[align(2)]
struct MyTy { .. }

#[repr(transparent)]
struct MyTyWrapper {
    my_ty_ptr: NonNull<MyTy>,
}

Result<i32, MyTyWrapper> should be able to fit in the same 8 byte space, by using the niche where the pointer is unaligned, but I can't figure out if there's a way to write this in code such that the compiler will actually use it (since nothing forces NonNull<MyTy> or *mut MyTy to actually be aligned, so those types don't have this niche). Is there a way to express this that I'm missing?

6 posts - 3 participants

Read full topic

🏷️ rust_feed