Skip to content

Commit

Permalink
Rollup merge of rust-lang#130822 - bjoernager:non-null-from-ref, r=dt…
Browse files Browse the repository at this point in the history
…olnay

Add `from_ref` and `from_mut` constructors to `core::ptr::NonNull`.

Relevant tracking issue: rust-lang#130823

The `core::ptr::NonNull` type should have the convenience constructors `from_ref` and `from_mut` for parity with `core::ptr::from_ref` and `core::ptr::from_mut`.

Although the type in question already implements `From<&T>` and `From<&mut T>`, these new functions also carry the ability to be used in constant expressions (due to not being behind a trait).
  • Loading branch information
matthiaskrgr authored Oct 16, 2024
2 parents cdbd127 + 9b4776b commit 1581f56
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 @@ -153,6 +153,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 1581f56

Please sign in to comment.