@@ -7,8 +7,6 @@ use crate::mem;
77use crate :: ops:: { CoerceUnsized , DispatchFromDyn } ;
88use crate :: ptr:: Unique ;
99
10- // ignore-tidy-undocumented-unsafe
11-
1210/// `*mut T` but non-zero and covariant.
1311///
1412/// This is often the correct thing to use when building data structures using
@@ -69,6 +67,9 @@ impl<T: Sized> NonNull<T> {
6967 #[ rustc_const_stable( feature = "const_nonnull_dangling" , since = "1.32.0" ) ]
7068 #[ inline]
7169 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.
7273 unsafe {
7374 let ptr = mem:: align_of :: < T > ( ) as * mut T ;
7475 NonNull :: new_unchecked ( ptr)
@@ -93,7 +94,12 @@ impl<T: ?Sized> NonNull<T> {
9394 #[ stable( feature = "nonnull" , since = "1.25.0" ) ]
9495 #[ inline]
9596 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+ }
97103 }
98104
99105 /// Acquires the underlying `*mut` pointer.
@@ -131,6 +137,7 @@ impl<T: ?Sized> NonNull<T> {
131137 #[ rustc_const_stable( feature = "const_nonnull_cast" , since = "1.32.0" ) ]
132138 #[ inline]
133139 pub const fn cast < U > ( self ) -> NonNull < U > {
140+ // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
134141 unsafe { NonNull :: new_unchecked ( self . as_ptr ( ) as * mut U ) }
135142 }
136143}
@@ -205,6 +212,8 @@ impl<T: ?Sized> hash::Hash for NonNull<T> {
205212impl < T : ?Sized > From < Unique < T > > for NonNull < T > {
206213 #[ inline]
207214 fn from ( unique : Unique < T > ) -> Self {
215+ // SAFETY: A Unique pointer cannot be null, so the conditions for
216+ // new_unchecked() are respected.
208217 unsafe { NonNull :: new_unchecked ( unique. as_ptr ( ) ) }
209218 }
210219}
@@ -213,6 +222,7 @@ impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
213222impl < T : ?Sized > From < & mut T > for NonNull < T > {
214223 #[ inline]
215224 fn from ( reference : & mut T ) -> Self {
225+ // SAFETY: A mutable reference cannot be null.
216226 unsafe { NonNull { pointer : reference as * mut T } }
217227 }
218228}
@@ -221,6 +231,8 @@ impl<T: ?Sized> From<&mut T> for NonNull<T> {
221231impl < T : ?Sized > From < & T > for NonNull < T > {
222232 #[ inline]
223233 fn from ( reference : & T ) -> Self {
234+ // SAFETY: A reference cannot be null, so the conditions for
235+ // new_unchecked() are respected.
224236 unsafe { NonNull { pointer : reference as * const T } }
225237 }
226238}
0 commit comments