Skip to content

Implement From<&[T]> and From<&mut [T]> for NonNull #69319

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 1 commit 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
20 changes: 18 additions & 2 deletions src/libcore/ptr/non_null.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ use crate::ptr::Unique;
/// such as `Box`, `Rc`, `Arc`, `Vec`, and `LinkedList`. This is the case because they
/// provide a public API that follows the normal shared XOR mutable rules of Rust.
///
/// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
/// not change the fact that mutating through a (pointer derived from a) shared
/// Notice that `NonNull<T>` has `From` instances for `&T` and `&[T]`. However, this
/// does not change the fact that mutating through a (pointer derived from a) shared
/// reference is undefined behavior unless the mutation happens inside an
/// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
/// reference. When using this `From` instance without an `UnsafeCell<T>`,
Expand Down Expand Up @@ -224,3 +224,19 @@ impl<T: ?Sized> From<&T> for NonNull<T> {
unsafe { NonNull { pointer: reference as *const T } }
}
}

#[stable(feature = "nonnull_from_slice", since = "1.43.0")]
impl<T> From<&mut [T]> for NonNull<T> {
#[inline]
fn from(slice: &mut [T]) -> Self {
unsafe { NonNull { pointer: slice.as_mut_ptr() } }
}
}

#[stable(feature = "nonnull_from_slice", since = "1.43.0")]
impl<T> From<&[T]> for NonNull<T> {
#[inline]
fn from(slice: &[T]) -> Self {
unsafe { NonNull { pointer: slice.as_ptr() } }
}
}