Skip to content
Closed
Show file tree
Hide file tree
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
Expand Up @@ -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};
Expand Down Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions library/alloc/tests/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}