@@ -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