Skip to content

Commit

Permalink
Add 'from_ref' and 'from_mut' constructors to 'core::ptr::NonNull';
Browse files Browse the repository at this point in the history
  • Loading branch information
bjoernager committed Sep 27, 2024
1 parent 4a7aeff commit 9b4776b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
1 change: 1 addition & 0 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@
#![feature(isqrt)]
#![feature(lazy_get)]
#![feature(link_cfg)]
#![feature(non_null_from_ref)]
#![feature(offset_of_enum)]
#![feature(panic_internals)]
#![feature(ptr_alignment_type)]
Expand Down
28 changes: 22 additions & 6 deletions core/src/ptr/non_null.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,24 @@ impl<T: ?Sized> NonNull<T> {
}
}

/// Converts a reference to a `NonNull` pointer.
#[unstable(feature = "non_null_from_ref", issue = "130823")]
#[rustc_const_unstable(feature = "non_null_from_ref", issue = "130823")]
#[inline]
pub const fn from_ref(r: &T) -> Self {
// SAFETY: A reference cannot be null.
unsafe { NonNull { pointer: r as *const T } }
}

/// Converts a mutable reference to a `NonNull` pointer.
#[unstable(feature = "non_null_from_ref", issue = "130823")]
#[rustc_const_unstable(feature = "non_null_from_ref", issue = "130823")]
#[inline]
pub const fn from_mut(r: &mut T) -> Self {
// SAFETY: A mutable reference cannot be null.
unsafe { NonNull { pointer: r as *mut T } }
}

/// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a
/// `NonNull` pointer is returned, as opposed to a raw `*const` pointer.
///
Expand Down Expand Up @@ -1753,9 +1771,8 @@ impl<T: ?Sized> From<&mut T> for NonNull<T> {
///
/// This conversion is safe and infallible since references cannot be null.
#[inline]
fn from(reference: &mut T) -> Self {
// SAFETY: A mutable reference cannot be null.
unsafe { NonNull { pointer: reference as *mut T } }
fn from(r: &mut T) -> Self {
NonNull::from_mut(r)
}
}

Expand All @@ -1765,8 +1782,7 @@ impl<T: ?Sized> From<&T> for NonNull<T> {
///
/// This conversion is safe and infallible since references cannot be null.
#[inline]
fn from(reference: &T) -> Self {
// SAFETY: A reference cannot be null.
unsafe { NonNull { pointer: reference as *const T } }
fn from(r: &T) -> Self {
NonNull::from_ref(r)
}
}

0 comments on commit 9b4776b

Please sign in to comment.