@@ -230,6 +230,24 @@ impl<T: ?Sized> NonNull<T> {
230
230
}
231
231
}
232
232
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
+
233
251
/// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a
234
252
/// `NonNull` pointer is returned, as opposed to a raw `*const` pointer.
235
253
///
@@ -1753,9 +1771,8 @@ impl<T: ?Sized> From<&mut T> for NonNull<T> {
1753
1771
///
1754
1772
/// This conversion is safe and infallible since references cannot be null.
1755
1773
#[ 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)
1759
1776
}
1760
1777
}
1761
1778
@@ -1765,8 +1782,7 @@ impl<T: ?Sized> From<&T> for NonNull<T> {
1765
1782
///
1766
1783
/// This conversion is safe and infallible since references cannot be null.
1767
1784
#[ 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)
1771
1787
}
1772
1788
}
0 commit comments