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 NonNullref, not a raw pointer value as a NonNullvalue.
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.
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.