Can `Box::into_raw` return `NonNull`?

https://doc.rust-lang.org/std/boxed/struct.Box.html#method.into_raw

The pointer will be properly aligned and non-null.

Sometimes we take its return value for use in a NonNull. But NonNull::new returns an Option which needs an extra unwrap. I'm against unwrap in general, and in this example, it's like we are converting NonNull to * mut to NonNull itself. Is there any consideration against returning NonNull for functions like Box::into_raw that we know return a non-null pointer?

The only thing I can think of is NonNull is covariant while * mut is invariant. This raises a related question whether NonNull is losing orthogonality by combining non-null and covariance in one data structure. Is there a need for something like RawNonNull which only exhibits non-null and nothing else?

Box::into_raw doesn’t do that because it was stabilized before NonNull was.

src: https://github.com/rust-lang/rust/issues/65816#issuecomment-546405936

or

because that's the type that from_raw_parts takes
src: comments below the linked issue

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.