@@ -7,8 +7,6 @@ use crate::mem;
7
7
use crate :: ops:: { CoerceUnsized , DispatchFromDyn } ;
8
8
use crate :: ptr:: Unique ;
9
9
10
- // ignore-tidy-undocumented-unsafe
11
-
12
10
/// `*mut T` but non-zero and covariant.
13
11
///
14
12
/// This is often the correct thing to use when building data structures using
@@ -69,6 +67,9 @@ impl<T: Sized> NonNull<T> {
69
67
#[ rustc_const_stable( feature = "const_nonnull_dangling" , since = "1.32.0" ) ]
70
68
#[ inline]
71
69
pub const fn dangling ( ) -> Self {
70
+ // SAFETY: mem::align_of() returns a non-zero usize which is then casted
71
+ // to a *mut T. Therefore, `ptr` is not null and the conditions for
72
+ // calling new_unchecked() are respected.
72
73
unsafe {
73
74
let ptr = mem:: align_of :: < T > ( ) as * mut T ;
74
75
NonNull :: new_unchecked ( ptr)
@@ -93,7 +94,12 @@ impl<T: ?Sized> NonNull<T> {
93
94
#[ stable( feature = "nonnull" , since = "1.25.0" ) ]
94
95
#[ inline]
95
96
pub fn new ( ptr : * mut T ) -> Option < Self > {
96
- if !ptr. is_null ( ) { Some ( unsafe { Self :: new_unchecked ( ptr) } ) } else { None }
97
+ if !ptr. is_null ( ) {
98
+ // SAFETY: The pointer is already checked and is not null
99
+ Some ( unsafe { Self :: new_unchecked ( ptr) } )
100
+ } else {
101
+ None
102
+ }
97
103
}
98
104
99
105
/// Acquires the underlying `*mut` pointer.
@@ -131,6 +137,7 @@ impl<T: ?Sized> NonNull<T> {
131
137
#[ rustc_const_stable( feature = "const_nonnull_cast" , since = "1.32.0" ) ]
132
138
#[ inline]
133
139
pub const fn cast < U > ( self ) -> NonNull < U > {
140
+ // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
134
141
unsafe { NonNull :: new_unchecked ( self . as_ptr ( ) as * mut U ) }
135
142
}
136
143
}
@@ -205,6 +212,8 @@ impl<T: ?Sized> hash::Hash for NonNull<T> {
205
212
impl < T : ?Sized > From < Unique < T > > for NonNull < T > {
206
213
#[ inline]
207
214
fn from ( unique : Unique < T > ) -> Self {
215
+ // SAFETY: A Unique pointer cannot be null, so the conditions for
216
+ // new_unchecked() are respected.
208
217
unsafe { NonNull :: new_unchecked ( unique. as_ptr ( ) ) }
209
218
}
210
219
}
@@ -213,6 +222,7 @@ impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
213
222
impl < T : ?Sized > From < & mut T > for NonNull < T > {
214
223
#[ inline]
215
224
fn from ( reference : & mut T ) -> Self {
225
+ // SAFETY: A mutable reference cannot be null.
216
226
unsafe { NonNull { pointer : reference as * mut T } }
217
227
}
218
228
}
@@ -221,6 +231,8 @@ impl<T: ?Sized> From<&mut T> for NonNull<T> {
221
231
impl < T : ?Sized > From < & T > for NonNull < T > {
222
232
#[ inline]
223
233
fn from ( reference : & T ) -> Self {
234
+ // SAFETY: A reference cannot be null, so the conditions for
235
+ // new_unchecked() are respected.
224
236
unsafe { NonNull { pointer : reference as * const T } }
225
237
}
226
238
}
0 commit comments