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;
9 use crate::slice::SliceIndex;
11 /// `*mut T` but non-zero and covariant.
13 /// This is often the correct thing to use when building data structures using
14 /// raw pointers, but is ultimately more dangerous to use because of its additional
15 /// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
17 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
18 /// is never dereferenced. This is so that enums may use this forbidden value
19 /// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
20 /// However the pointer may still dangle if it isn't dereferenced.
22 /// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
23 /// for your use case, you should include some [`PhantomData`] in your type to
24 /// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
25 /// Usually this won't be necessary; covariance is correct for most safe abstractions,
26 /// such as `Box`, `Rc`, `Arc`, `Vec`, and `LinkedList`. This is the case because they
27 /// provide a public API that follows the normal shared XOR mutable rules of Rust.
29 /// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
30 /// not change the fact that mutating through a (pointer derived from a) shared
31 /// reference is undefined behavior unless the mutation happens inside an
32 /// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
33 /// reference. When using this `From` instance without an `UnsafeCell<T>`,
34 /// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
35 /// is never used for mutation.
37 /// [`PhantomData`]: ../marker/struct.PhantomData.html
38 /// [`UnsafeCell<T>`]: ../cell/struct.UnsafeCell.html
39 #[stable(feature = "nonnull", since = "1.25.0")]
41 #[rustc_layout_scalar_valid_range_start(1)]
42 #[rustc_nonnull_optimization_guaranteed]
43 pub struct NonNull<T: ?Sized> {
47 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
48 // N.B., this impl is unnecessary, but should provide better error messages.
49 #[stable(feature = "nonnull", since = "1.25.0")]
50 impl<T: ?Sized> !Send for NonNull<T> {}
52 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
53 // N.B., this impl is unnecessary, but should provide better error messages.
54 #[stable(feature = "nonnull", since = "1.25.0")]
55 impl<T: ?Sized> !Sync for NonNull<T> {}
57 impl<T: Sized> NonNull<T> {
58 /// Creates a new `NonNull` that is dangling, but well-aligned.
60 /// This is useful for initializing types which lazily allocate, like
63 /// Note that the pointer value may potentially represent a valid pointer to
64 /// a `T`, which means this must not be used as a "not yet initialized"
65 /// sentinel value. Types that lazily allocate must track initialization by
67 #[stable(feature = "nonnull", since = "1.25.0")]
68 #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.32.0")]
70 pub const fn dangling() -> Self {
71 // SAFETY: mem::align_of() returns a non-zero usize which is then casted
72 // to a *mut T. Therefore, `ptr` is not null and the conditions for
73 // calling new_unchecked() are respected.
75 let ptr = mem::align_of::<T>() as *mut T;
76 NonNull::new_unchecked(ptr)
81 impl<T: ?Sized> NonNull<T> {
82 /// Creates a new `NonNull`.
86 /// `ptr` must be non-null.
87 #[stable(feature = "nonnull", since = "1.25.0")]
88 #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.32.0")]
90 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
91 // SAFETY: the caller must guarantee that `ptr` is non-null.
92 unsafe { NonNull { pointer: ptr as _ } }
95 /// Creates a new `NonNull` if `ptr` is non-null.
96 #[stable(feature = "nonnull", since = "1.25.0")]
98 pub fn new(ptr: *mut T) -> Option<Self> {
100 // SAFETY: The pointer is already checked and is not null
101 Some(unsafe { Self::new_unchecked(ptr) })
107 /// Acquires the underlying `*mut` pointer.
108 #[stable(feature = "nonnull", since = "1.25.0")]
109 #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
111 pub const fn as_ptr(self) -> *mut T {
112 self.pointer as *mut T
115 /// Dereferences the content.
117 /// The resulting lifetime is bound to self so this behaves "as if"
118 /// it were actually an instance of T that is getting borrowed. If a longer
119 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
120 #[stable(feature = "nonnull", since = "1.25.0")]
122 pub unsafe fn as_ref(&self) -> &T {
123 // SAFETY: the caller must guarantee that `self` meets all the
124 // requirements for a reference.
125 unsafe { &*self.as_ptr() }
128 /// Mutably dereferences the content.
130 /// The resulting lifetime is bound to self so this behaves "as if"
131 /// it were actually an instance of T that is getting borrowed. If a longer
132 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
133 #[stable(feature = "nonnull", since = "1.25.0")]
135 pub unsafe fn as_mut(&mut self) -> &mut T {
136 // SAFETY: the caller must guarantee that `self` meets all the
137 // requirements for a mutable reference.
138 unsafe { &mut *self.as_ptr() }
141 /// Casts to a pointer of another type.
142 #[stable(feature = "nonnull_cast", since = "1.27.0")]
143 #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.32.0")]
145 pub const fn cast<U>(self) -> NonNull<U> {
146 // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
147 unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) }
151 impl<T> NonNull<[T]> {
152 /// Creates a non-null raw slice from a thin pointer and a length.
154 /// The `len` argument is the number of **elements**, not the number of bytes.
156 /// This function is safe, but dereferencing the return value is unsafe.
157 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
159 /// [`slice::from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
164 /// #![feature(nonnull_slice_from_raw_parts)]
166 /// use std::ptr::NonNull;
168 /// // create a slice pointer when starting out with a pointer to the first element
169 /// let mut x = [5, 6, 7];
170 /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
171 /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
172 /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
175 /// (Note that this example artificially demonstrates a use of this method,
176 /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
177 #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
178 #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
180 pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
181 // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
182 unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
185 /// Returns the length of a non-null raw slice.
187 /// The returned value is the number of **elements**, not the number of bytes.
189 /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
190 /// because the pointer does not have a valid address.
195 /// #![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 {
208 /// Returns a non-null pointer to the slice's buffer.
213 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
214 /// use std::ptr::NonNull;
216 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
217 /// assert_eq!(slice.as_non_null_ptr(), NonNull::new(1 as *mut i8).unwrap());
220 #[unstable(feature = "slice_ptr_get", issue = "74265")]
221 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
222 pub const fn as_non_null_ptr(self) -> NonNull<T> {
223 // SAFETY: We know `self` is non-null.
224 unsafe { NonNull::new_unchecked(self.as_ptr().as_mut_ptr()) }
227 /// Returns a raw pointer to an element or subslice, without doing bounds
230 /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
231 /// is *[undefined behavior]* even if the resulting pointer is not used.
233 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
238 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
239 /// use std::ptr::NonNull;
241 /// let x = &mut [1, 2, 4];
242 /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
245 /// assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
248 #[unstable(feature = "slice_ptr_get", issue = "74265")]
250 pub unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
254 // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
255 // As a consequence, the resulting pointer cannot be NULL.
256 unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
260 #[stable(feature = "nonnull", since = "1.25.0")]
261 impl<T: ?Sized> Clone for NonNull<T> {
263 fn clone(&self) -> Self {
268 #[stable(feature = "nonnull", since = "1.25.0")]
269 impl<T: ?Sized> Copy for NonNull<T> {}
271 #[unstable(feature = "coerce_unsized", issue = "27732")]
272 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
274 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
275 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
277 #[stable(feature = "nonnull", since = "1.25.0")]
278 impl<T: ?Sized> fmt::Debug for NonNull<T> {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 fmt::Pointer::fmt(&self.as_ptr(), f)
284 #[stable(feature = "nonnull", since = "1.25.0")]
285 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 fmt::Pointer::fmt(&self.as_ptr(), f)
291 #[stable(feature = "nonnull", since = "1.25.0")]
292 impl<T: ?Sized> Eq for NonNull<T> {}
294 #[stable(feature = "nonnull", since = "1.25.0")]
295 impl<T: ?Sized> PartialEq for NonNull<T> {
297 fn eq(&self, other: &Self) -> bool {
298 self.as_ptr() == other.as_ptr()
302 #[stable(feature = "nonnull", since = "1.25.0")]
303 impl<T: ?Sized> Ord for NonNull<T> {
305 fn cmp(&self, other: &Self) -> Ordering {
306 self.as_ptr().cmp(&other.as_ptr())
310 #[stable(feature = "nonnull", since = "1.25.0")]
311 impl<T: ?Sized> PartialOrd for NonNull<T> {
313 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
314 self.as_ptr().partial_cmp(&other.as_ptr())
318 #[stable(feature = "nonnull", since = "1.25.0")]
319 impl<T: ?Sized> hash::Hash for NonNull<T> {
321 fn hash<H: hash::Hasher>(&self, state: &mut H) {
322 self.as_ptr().hash(state)
326 #[unstable(feature = "ptr_internals", issue = "none")]
327 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
329 fn from(unique: Unique<T>) -> Self {
330 // SAFETY: A Unique pointer cannot be null, so the conditions for
331 // new_unchecked() are respected.
332 unsafe { NonNull::new_unchecked(unique.as_ptr()) }
336 #[stable(feature = "nonnull", since = "1.25.0")]
337 impl<T: ?Sized> From<&mut T> for NonNull<T> {
339 fn from(reference: &mut T) -> Self {
340 // SAFETY: A mutable reference cannot be null.
341 unsafe { NonNull { pointer: reference as *mut T } }
345 #[stable(feature = "nonnull", since = "1.25.0")]
346 impl<T: ?Sized> From<&T> for NonNull<T> {
348 fn from(reference: &T) -> Self {
349 // SAFETY: A reference cannot be null, so the conditions for
350 // new_unchecked() are respected.
351 unsafe { NonNull { pointer: reference as *const T } }