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 // SAFETY: the caller must guarantee that `ptr` is non-null.
91 unsafe { NonNull { pointer: ptr as _ } }
94 /// Creates a new `NonNull` if `ptr` is non-null.
95 #[stable(feature = "nonnull", since = "1.25.0")]
97 pub fn new(ptr: *mut T) -> Option<Self> {
99 // SAFETY: The pointer is already checked and is not null
100 Some(unsafe { Self::new_unchecked(ptr) })
106 /// Acquires the underlying `*mut` pointer.
107 #[stable(feature = "nonnull", since = "1.25.0")]
108 #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
110 pub const fn as_ptr(self) -> *mut T {
111 self.pointer as *mut T
114 /// Dereferences the content.
116 /// The resulting lifetime is bound to self so this behaves "as if"
117 /// it were actually an instance of T that is getting borrowed. If a longer
118 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
119 #[stable(feature = "nonnull", since = "1.25.0")]
121 pub unsafe fn as_ref(&self) -> &T {
122 // SAFETY: the caller must guarantee that `self` meets all the
123 // requirements for a reference.
124 unsafe { &*self.as_ptr() }
127 /// Mutably dereferences the content.
129 /// The resulting lifetime is bound to self so this behaves "as if"
130 /// it were actually an instance of T that is getting borrowed. If a longer
131 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
132 #[stable(feature = "nonnull", since = "1.25.0")]
134 pub unsafe fn as_mut(&mut self) -> &mut T {
135 // SAFETY: the caller must guarantee that `self` meets all the
136 // requirements for a mutable reference.
137 unsafe { &mut *self.as_ptr() }
140 /// Casts to a pointer of another type.
141 #[stable(feature = "nonnull_cast", since = "1.27.0")]
142 #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.32.0")]
144 pub const fn cast<U>(self) -> NonNull<U> {
145 // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
146 unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) }
150 impl<T> NonNull<[T]> {
151 /// Creates a non-null raw slice from a thin pointer and a length.
153 /// The `len` argument is the number of **elements**, not the number of bytes.
155 /// This function is safe, but dereferencing the return value is unsafe.
156 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
158 /// [`slice::from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
163 /// #![feature(nonnull_slice_from_raw_parts)]
165 /// use std::ptr::NonNull;
167 /// // create a slice pointer when starting out with a pointer to the first element
168 /// let mut x = [5, 6, 7];
169 /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
170 /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
171 /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
174 /// (Note that this example artifically demonstrates a use of this method,
175 /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
176 #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
177 #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
179 pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
180 // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
181 unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
184 /// Returns the length of a non-null raw slice.
186 /// The returned value is the number of **elements**, not the number of bytes.
188 /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
189 /// because the pointer does not have a valid address.
194 /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
196 /// use std::ptr::NonNull;
198 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
199 /// assert_eq!(slice.len(), 3);
201 #[unstable(feature = "slice_ptr_len", issue = "71146")]
202 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
204 pub const fn len(self) -> usize {
209 #[stable(feature = "nonnull", since = "1.25.0")]
210 impl<T: ?Sized> Clone for NonNull<T> {
212 fn clone(&self) -> Self {
217 #[stable(feature = "nonnull", since = "1.25.0")]
218 impl<T: ?Sized> Copy for NonNull<T> {}
220 #[unstable(feature = "coerce_unsized", issue = "27732")]
221 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
223 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
224 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
226 #[stable(feature = "nonnull", since = "1.25.0")]
227 impl<T: ?Sized> fmt::Debug for NonNull<T> {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 fmt::Pointer::fmt(&self.as_ptr(), f)
233 #[stable(feature = "nonnull", since = "1.25.0")]
234 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236 fmt::Pointer::fmt(&self.as_ptr(), f)
240 #[stable(feature = "nonnull", since = "1.25.0")]
241 impl<T: ?Sized> Eq for NonNull<T> {}
243 #[stable(feature = "nonnull", since = "1.25.0")]
244 impl<T: ?Sized> PartialEq for NonNull<T> {
246 fn eq(&self, other: &Self) -> bool {
247 self.as_ptr() == other.as_ptr()
251 #[stable(feature = "nonnull", since = "1.25.0")]
252 impl<T: ?Sized> Ord for NonNull<T> {
254 fn cmp(&self, other: &Self) -> Ordering {
255 self.as_ptr().cmp(&other.as_ptr())
259 #[stable(feature = "nonnull", since = "1.25.0")]
260 impl<T: ?Sized> PartialOrd for NonNull<T> {
262 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
263 self.as_ptr().partial_cmp(&other.as_ptr())
267 #[stable(feature = "nonnull", since = "1.25.0")]
268 impl<T: ?Sized> hash::Hash for NonNull<T> {
270 fn hash<H: hash::Hasher>(&self, state: &mut H) {
271 self.as_ptr().hash(state)
275 #[unstable(feature = "ptr_internals", issue = "none")]
276 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
278 fn from(unique: Unique<T>) -> Self {
279 // SAFETY: A Unique pointer cannot be null, so the conditions for
280 // new_unchecked() are respected.
281 unsafe { NonNull::new_unchecked(unique.as_ptr()) }
285 #[stable(feature = "nonnull", since = "1.25.0")]
286 impl<T: ?Sized> From<&mut T> for NonNull<T> {
288 fn from(reference: &mut T) -> Self {
289 // SAFETY: A mutable reference cannot be null.
290 unsafe { NonNull { pointer: reference as *mut T } }
294 #[stable(feature = "nonnull", since = "1.25.0")]
295 impl<T: ?Sized> From<&T> for NonNull<T> {
297 fn from(reference: &T) -> Self {
298 // SAFETY: A reference cannot be null, so the conditions for
299 // new_unchecked() are respected.
300 unsafe { NonNull { pointer: reference as *const T } }