1 use crate::cmp::Ordering;
2 use crate::convert::From;
5 use crate::marker::Unsize;
7 use crate::ops::{CoerceUnsized, DispatchFromDyn};
8 use crate::ptr::Unique;
10 /// `*mut T` but non-zero and covariant.
12 /// This is often the correct thing to use when building data structures using
13 /// raw pointers, but is ultimately more dangerous to use because of its additional
14 /// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
16 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
17 /// is never dereferenced. This is so that enums may use this forbidden value
18 /// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
19 /// However the pointer may still dangle if it isn't dereferenced.
21 /// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
22 /// for your use case, you should include some [`PhantomData`] in your type to
23 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
24 /// Usually this won't be necessary; covariance is correct for most safe abstractions,
25 /// such as `Box`, `Rc`, `Arc`, `Vec`, and `LinkedList`. This is the case because they
26 /// provide a public API that follows the normal shared XOR mutable rules of Rust.
28 /// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
29 /// not change the fact that mutating through a (pointer derived from a) shared
30 /// reference is undefined behavior unless the mutation happens inside an
31 /// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
32 /// reference. When using this `From` instance without an `UnsafeCell<T>`,
33 /// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
34 /// is never used for mutation.
36 /// [`PhantomData`]: ../marker/struct.PhantomData.html
37 /// [`UnsafeCell<T>`]: ../cell/struct.UnsafeCell.html
38 #[stable(feature = "nonnull", since = "1.25.0")]
40 #[rustc_layout_scalar_valid_range_start(1)]
41 #[rustc_nonnull_optimization_guaranteed]
42 pub struct NonNull<T: ?Sized> {
46 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
47 // N.B., this impl is unnecessary, but should provide better error messages.
48 #[stable(feature = "nonnull", since = "1.25.0")]
49 impl<T: ?Sized> !Send for NonNull<T> {}
51 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
52 // N.B., this impl is unnecessary, but should provide better error messages.
53 #[stable(feature = "nonnull", since = "1.25.0")]
54 impl<T: ?Sized> !Sync for NonNull<T> {}
56 impl<T: Sized> NonNull<T> {
57 /// Creates a new `NonNull` that is dangling, but well-aligned.
59 /// This is useful for initializing types which lazily allocate, like
62 /// Note that the pointer value may potentially represent a valid pointer to
63 /// a `T`, which means this must not be used as a "not yet initialized"
64 /// sentinel value. Types that lazily allocate must track initialization by
66 #[stable(feature = "nonnull", since = "1.25.0")]
67 #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.32.0")]
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.
74 let ptr = mem::align_of::<T>() as *mut T;
75 NonNull::new_unchecked(ptr)
80 impl<T: ?Sized> NonNull<T> {
81 /// Creates a new `NonNull`.
85 /// `ptr` must be non-null.
86 #[stable(feature = "nonnull", since = "1.25.0")]
87 #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.32.0")]
89 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
90 NonNull { pointer: ptr as _ }
93 /// Creates a new `NonNull` if `ptr` is non-null.
94 #[stable(feature = "nonnull", since = "1.25.0")]
96 pub fn new(ptr: *mut T) -> Option<Self> {
98 // SAFETY: The pointer is already checked and is not null
99 Some(unsafe { Self::new_unchecked(ptr) })
105 /// Acquires the underlying `*mut` pointer.
106 #[stable(feature = "nonnull", since = "1.25.0")]
107 #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
109 pub const fn as_ptr(self) -> *mut T {
110 self.pointer as *mut T
113 /// Dereferences the content.
115 /// The resulting lifetime is bound to self so this behaves "as if"
116 /// it were actually an instance of T that is getting borrowed. If a longer
117 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
118 #[stable(feature = "nonnull", since = "1.25.0")]
120 pub unsafe fn as_ref(&self) -> &T {
124 /// Mutably dereferences the content.
126 /// The resulting lifetime is bound to self so this behaves "as if"
127 /// it were actually an instance of T that is getting borrowed. If a longer
128 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
129 #[stable(feature = "nonnull", since = "1.25.0")]
131 pub unsafe fn as_mut(&mut self) -> &mut T {
135 /// Casts to a pointer of another type.
136 #[stable(feature = "nonnull_cast", since = "1.27.0")]
137 #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.32.0")]
139 pub const fn cast<U>(self) -> NonNull<U> {
140 // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
141 unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) }
145 impl<T> NonNull<[T]> {
146 /// Creates a non-null raw slice from a thin pointer and a length.
148 /// The `len` argument is the number of **elements**, not the number of bytes.
150 /// This function is safe, but dereferencing the return value is unsafe.
151 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
153 /// [`slice::from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
158 /// #![feature(nonnull_slice_from_raw_parts)]
160 /// use std::ptr::NonNull;
162 /// // create a slice pointer when starting out with a pointer to the first element
163 /// let mut x = [5, 6, 7];
164 /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
165 /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
166 /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
169 /// (Note that this example artifically demonstrates a use of this method,
170 /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
171 #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
172 #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
174 pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
175 // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
176 unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
179 /// Returns the length of a non-null raw slice.
181 /// The returned value is the number of **elements**, not the number of bytes.
183 /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
184 /// because the pointer does not have a valid address.
189 /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
191 /// use std::ptr::NonNull;
193 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
194 /// assert_eq!(slice.len(), 3);
196 #[unstable(feature = "slice_ptr_len", issue = "71146")]
197 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
199 pub const fn len(self) -> usize {
204 #[stable(feature = "nonnull", since = "1.25.0")]
205 impl<T: ?Sized> Clone for NonNull<T> {
207 fn clone(&self) -> Self {
212 #[stable(feature = "nonnull", since = "1.25.0")]
213 impl<T: ?Sized> Copy for NonNull<T> {}
215 #[unstable(feature = "coerce_unsized", issue = "27732")]
216 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
218 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
219 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
221 #[stable(feature = "nonnull", since = "1.25.0")]
222 impl<T: ?Sized> fmt::Debug for NonNull<T> {
223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224 fmt::Pointer::fmt(&self.as_ptr(), f)
228 #[stable(feature = "nonnull", since = "1.25.0")]
229 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
230 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231 fmt::Pointer::fmt(&self.as_ptr(), f)
235 #[stable(feature = "nonnull", since = "1.25.0")]
236 impl<T: ?Sized> Eq for NonNull<T> {}
238 #[stable(feature = "nonnull", since = "1.25.0")]
239 impl<T: ?Sized> PartialEq for NonNull<T> {
241 fn eq(&self, other: &Self) -> bool {
242 self.as_ptr() == other.as_ptr()
246 #[stable(feature = "nonnull", since = "1.25.0")]
247 impl<T: ?Sized> Ord for NonNull<T> {
249 fn cmp(&self, other: &Self) -> Ordering {
250 self.as_ptr().cmp(&other.as_ptr())
254 #[stable(feature = "nonnull", since = "1.25.0")]
255 impl<T: ?Sized> PartialOrd for NonNull<T> {
257 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
258 self.as_ptr().partial_cmp(&other.as_ptr())
262 #[stable(feature = "nonnull", since = "1.25.0")]
263 impl<T: ?Sized> hash::Hash for NonNull<T> {
265 fn hash<H: hash::Hasher>(&self, state: &mut H) {
266 self.as_ptr().hash(state)
270 #[unstable(feature = "ptr_internals", issue = "none")]
271 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
273 fn from(unique: Unique<T>) -> Self {
274 // SAFETY: A Unique pointer cannot be null, so the conditions for
275 // new_unchecked() are respected.
276 unsafe { NonNull::new_unchecked(unique.as_ptr()) }
280 #[stable(feature = "nonnull", since = "1.25.0")]
281 impl<T: ?Sized> From<&mut T> for NonNull<T> {
283 fn from(reference: &mut T) -> Self {
284 // SAFETY: A mutable reference cannot be null.
285 unsafe { NonNull { pointer: reference as *mut T } }
289 #[stable(feature = "nonnull", since = "1.25.0")]
290 impl<T: ?Sized> From<&T> for NonNull<T> {
292 fn from(reference: &T) -> Self {
293 // SAFETY: A reference cannot be null, so the conditions for
294 // new_unchecked() are respected.
295 unsafe { NonNull { pointer: reference as *const T } }