Skip to content

Commit 1bcb831

Browse files
committed
Add 'from_ref' and 'from_mut' constructors to 'core::ptr::NonNull';
1 parent 4c62024 commit 1bcb831

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

library/core/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@
174174
#![feature(isqrt)]
175175
#![feature(lazy_get)]
176176
#![feature(link_cfg)]
177+
#![feature(non_null_from_ref)]
177178
#![feature(offset_of_enum)]
178179
#![feature(panic_internals)]
179180
#![feature(ptr_alignment_type)]

library/core/src/ptr/non_null.rs

+22-6
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,24 @@ impl<T: ?Sized> NonNull<T> {
230230
}
231231
}
232232

233+
/// Converts a reference to a `NonNull` pointer.
234+
#[unstable(feature = "non_null_from_ref", issue = "130823")]
235+
#[rustc_const_unstable(feature = "non_null_from_ref", issue = "130823")]
236+
#[inline]
237+
pub const fn from_ref(r: &T) -> Self {
238+
// SAFETY: A reference cannot be null.
239+
unsafe { NonNull { pointer: r as *const T } }
240+
}
241+
242+
/// Converts a mutable reference to a `NonNull` pointer.
243+
#[unstable(feature = "non_null_from_ref", issue = "130823")]
244+
#[rustc_const_unstable(feature = "non_null_from_ref", issue = "130823")]
245+
#[inline]
246+
pub const fn from_mut(r: &mut T) -> Self {
247+
// SAFETY: A mutable reference cannot be null.
248+
unsafe { NonNull { pointer: r as *mut T } }
249+
}
250+
233251
/// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a
234252
/// `NonNull` pointer is returned, as opposed to a raw `*const` pointer.
235253
///
@@ -1753,9 +1771,8 @@ impl<T: ?Sized> From<&mut T> for NonNull<T> {
17531771
///
17541772
/// This conversion is safe and infallible since references cannot be null.
17551773
#[inline]
1756-
fn from(reference: &mut T) -> Self {
1757-
// SAFETY: A mutable reference cannot be null.
1758-
unsafe { NonNull { pointer: reference as *mut T } }
1774+
fn from(r: &mut T) -> Self {
1775+
NonNull::from_mut(r)
17591776
}
17601777
}
17611778

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

0 commit comments

Comments
 (0)