@@ -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 ///
@@ -1749,9 +1767,8 @@ impl<T: ?Sized> From<&mut T> for NonNull<T> {
17491767 ///
17501768 /// This conversion is safe and infallible since references cannot be null.
17511769 #[ inline]
1752- fn from ( reference : & mut T ) -> Self {
1753- // SAFETY: A mutable reference cannot be null.
1754- unsafe { NonNull { pointer : reference as * mut T } }
1770+ fn from ( r : & mut T ) -> Self {
1771+ NonNull :: from_mut ( r)
17551772 }
17561773}
17571774
@@ -1761,8 +1778,7 @@ impl<T: ?Sized> From<&T> for NonNull<T> {
17611778 ///
17621779 /// This conversion is safe and infallible since references cannot be null.
17631780 #[ inline]
1764- fn from ( reference : & T ) -> Self {
1765- // SAFETY: A reference cannot be null.
1766- unsafe { NonNull { pointer : reference as * const T } }
1781+ fn from ( r : & T ) -> Self {
1782+ NonNull :: from_ref ( r)
17671783 }
17681784}
0 commit comments