Skip to content

Implement From<Box<T>> for NonNull<T>. #80611

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion library/alloc/src/boxed.rs
Original file line number Diff line number Diff line change
@@ -148,7 +148,7 @@ use core::ops::{
CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
};
use core::pin::Pin;
use core::ptr::{self, Unique};
use core::ptr::{self, NonNull, Unique};
use core::task::{Context, Poll};

use crate::alloc::{handle_alloc_error, AllocError, Allocator, Global, Layout};
@@ -1168,6 +1168,22 @@ impl<T> From<T> for Box<T> {
}
}

#[stable(feature = "nonnull_from_box", since = "1.51.0")]
impl<T: ?Sized, A: Allocator> From<Box<T, A>> for NonNull<T> {
/// Convert a `Box<T>` into a [`NonNull<T>`](core::ptr::NonNull).
///
/// After calling this function, the caller is responsible for eventually
/// releasing the memory previously managed by the `Box` (for example, via
/// [`Box::from_raw`]).
#[inline]
#[must_use = "this will leak memory if unused"]
fn from(b: Box<T, A>) -> Self {
// Safety: Box's pointer is guaranteed to be nonnull, so we can use
// new_unchecked.
unsafe { NonNull::new_unchecked(Box::into_raw(b)) }
}
}

#[stable(feature = "pin", since = "1.33.0")]
impl<T: ?Sized, A: Allocator> From<Box<T, A>> for Pin<Box<T, A>>
where
16 changes: 16 additions & 0 deletions library/alloc/tests/boxed.rs
Original file line number Diff line number Diff line change
@@ -57,3 +57,19 @@ fn box_deref_lval() {
x.set(1000);
assert_eq!(x.get(), 1000);
}

#[test]
fn nonnull_from_box() {
let x = Box::new(5);
let p = NonNull::from(x);
assert_eq!(unsafe { *p.as_ref() }, 5);
let _ = unsafe { Box::from_raw(p.as_ptr()) };
}

#[test]
fn nonnull_from_box_dynsized() {
let s: Box<str> = "foo".into();
let ps = NonNull::from(s);
let s_again = unsafe { Box::from_raw(ps.as_ptr()) };
assert_eq!(&*s_again, "foo");
}