@@ -191,6 +191,7 @@ impl<T: ?Sized> NonNull<T> {
191
191
/// ```
192
192
#[ stable( feature = "nonnull" , since = "1.25.0" ) ]
193
193
#[ rustc_const_stable( feature = "const_nonnull_new_unchecked" , since = "1.25.0" ) ]
194
+ #[ must_use]
194
195
#[ inline]
195
196
pub const unsafe fn new_unchecked ( ptr : * mut T ) -> Self {
196
197
// SAFETY: the caller must guarantee that `ptr` is non-null.
@@ -220,6 +221,7 @@ impl<T: ?Sized> NonNull<T> {
220
221
/// ```
221
222
#[ stable( feature = "nonnull" , since = "1.25.0" ) ]
222
223
#[ rustc_const_unstable( feature = "const_nonnull_new" , issue = "93235" ) ]
224
+ #[ must_use]
223
225
#[ inline]
224
226
pub const fn new ( ptr : * mut T ) -> Option < Self > {
225
227
if !ptr. is_null ( ) {
@@ -230,6 +232,26 @@ impl<T: ?Sized> NonNull<T> {
230
232
}
231
233
}
232
234
235
+ /// Converts a reference to a `NonNull` pointer.
236
+ #[ unstable( feature = "non_null_from_ref" , issue = "130823" ) ]
237
+ #[ rustc_const_unstable( feature = "non_null_from_ref" , issue = "130823" ) ]
238
+ #[ must_use]
239
+ #[ inline]
240
+ pub const fn from_ref ( r : & T ) -> Self {
241
+ // SAFETY: A reference cannot be null.
242
+ unsafe { NonNull { pointer : r as * const T } }
243
+ }
244
+
245
+ /// Converts a mutable reference to a `NonNull` pointer.
246
+ #[ unstable( feature = "non_null_from_ref" , issue = "130823" ) ]
247
+ #[ rustc_const_unstable( feature = "non_null_from_ref" , issue = "130823" ) ]
248
+ #[ must_use]
249
+ #[ inline]
250
+ pub const fn from_mut ( r : & mut T ) -> Self {
251
+ // SAFETY: A mutable reference cannot be null.
252
+ unsafe { NonNull { pointer : r as * mut T } }
253
+ }
254
+
233
255
/// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a
234
256
/// `NonNull` pointer is returned, as opposed to a raw `*const` pointer.
235
257
///
@@ -1753,9 +1775,8 @@ impl<T: ?Sized> From<&mut T> for NonNull<T> {
1753
1775
///
1754
1776
/// This conversion is safe and infallible since references cannot be null.
1755
1777
#[ inline]
1756
- fn from ( reference : & mut T ) -> Self {
1757
- // SAFETY: A mutable reference cannot be null.
1758
- unsafe { NonNull { pointer : reference as * mut T } }
1778
+ fn from ( r : & mut T ) -> Self {
1779
+ NonNull :: from_mut ( r)
1759
1780
}
1760
1781
}
1761
1782
@@ -1765,8 +1786,7 @@ impl<T: ?Sized> From<&T> for NonNull<T> {
1765
1786
///
1766
1787
/// This conversion is safe and infallible since references cannot be null.
1767
1788
#[ inline]
1768
- fn from ( reference : & T ) -> Self {
1769
- // SAFETY: A reference cannot be null.
1770
- unsafe { NonNull { pointer : reference as * const T } }
1789
+ fn from ( r : & T ) -> Self {
1790
+ NonNull :: from_ref ( r)
1771
1791
}
1772
1792
}
0 commit comments