Get a NonNull<T> from UnsafeCell<T>

UnsafeCell::get returns a *mut T. However, since the address of the value inside the UnsafeCell is never null, it should be fine to get the pointer as a NonNull<T>.

Besides the fact that NonNull was stabilized later than UnsafeCell is there any reason such an API doesn't exist?

something like:

fn non_null(&self) -> NonNull<T> {
   NonNull::From(self)
}

I'd be willing to create a PR (it seems small enough not to need an RFC) to create such a function, although I'm not sure what a good name for the function would be.

1 Like

This function can written like this:

pub fn non_null<T>(unsafe_cell: &UnsafeCell<T>) -> NonNull<T> {
   NonNull::new(unsafe_cell.get()).unwrap()
}

Rust compiler will realize that UnsafeCell::get can never actually point to null (references are never null) and the resulting assembly won't have null check.

That said, there is a problem with such an API as it's error-prone as NonNull is covariant. In most cases users are probably better using &UnsafeCell<T>. Is there any particular use-case for such a conversion method that you cannot do with &UnsafeCell<T>?

In terms of name of a method, I think get_non_null_ptr should be fine for an unstable method name. This can be changed while the method is unstable anyway.

1 Like