Convert ref-to-raw-pointer to ref-to-NonNull without transmute?

Consider this toy function:

fn ptr_as_nonnull<T: ?Sized>(input: &*mut T) -> Option<&NonNull<T>> {
    if input.is_null() {
        None
    } else {
        // Is it possible to implement this without transmute?
        Some(unsafe { std::mem::transmute(input) })
    }
}

Is that function sound? I know that NonNull is repr(transparent), but that function is transmuting a raw pointer ref as a NonNull ref, not a raw pointer value as a NonNull value.

Is it possible to implement that function without using std::mem::transmute()?

I can restructure my code (playground) to avoid this, but I'm curious.

Yes. Transmuting a reference requires less than #[repr(transparent)] in fact, layout equivalence (e.g. #[repr(C)]) is enough.

Do note though that #[repr(transparent)] is not a public guarantee. NonNull however is documented to have the same layout and ABI as a pointer.

Not really, except maybe using external crates.

Do the Rust docs make that guarantee anywhere? I didn't see anything in pointer section of the reference. The layout section says that all refs/pointers to sized types have the same size and alignment, but it doesn't say anything about representation. The representation subsection doesn't talk about representation of references/pointers. I'd be surprised if the representation differed, but maybe some future version of Rust might decide to store a flag in the least significant bit of an address for an alginment > 1 type.

That is good to know! I thought it was a public guarantee, so I'm glad you mentioned it.

if you mean to implement without the specific transmute() function, then yes, you can avoid it in this case, you can use raw pointer casts instead.

if you mean is it possible to implement it without unsafe, the anser is no.

fn ptr_as_nonnull<T: ?Sized>(input: &*mut T) -> Option<&NonNull<T>> {
    if input.is_null() {
        None
    } else {
        // be **EXTREMELY** careful!!!
        Some(unsafe { &*(&raw const *input).cast() })
    }
}

There's documentation here.

For those familiar with pointers, a reference is just a pointer that is assumed to be aligned, not null, and pointing to memory containing a valid value of T [...] In fact, Option<&T> has the same memory representation as a nullable but aligned pointer, and can be passed across FFI boundaries as such.

Though *mut T has a lot of helper functions already, this seems like something that would be worthwhile putting into the standard library.

No, it is too specific. Ideally this will be resolved by the Safe Transmute Project in the future :trade_mark: