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()`.
123 /// When calling this method, you have to ensure that all of the following is true:
124 /// - `self` is properly aligned
125 /// - `self` must point to an initialized instance of T; in particular, the pointer must be
126 /// "dereferencable" in the sense defined [here].
128 /// This applies even if the result of this method is unused!
129 /// (The part about being initialized is not yet fully decided, but until
130 /// it is, the only safe approach is to ensure that they are indeed initialized.)
132 /// Additionally, the lifetime of `self` does not necessarily reflect the actual
133 /// lifetime of the data. *You* must enforce Rust's aliasing rules. In particular,
134 /// for the duration of this lifetime, the memory the pointer points to must not
135 /// get mutated (except inside `UnsafeCell`).
137 /// [here]: crate::ptr#safety
138 #[stable(feature = "nonnull", since = "1.25.0")]
140 pub unsafe fn as_ref(&self) -> &T {
141 // SAFETY: the caller must guarantee that `self` meets all the
142 // requirements for a reference.
143 unsafe { &*self.as_ptr() }
146 /// Mutably dereferences the content.
148 /// The resulting lifetime is bound to self so this behaves "as if"
149 /// it were actually an instance of T that is getting borrowed. If a longer
150 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
154 /// When calling this method, you have to ensure that all of the following is true:
155 /// - `self` is properly aligned
156 /// - `self` must point to an initialized instance of T; in particular, the pointer must be
157 /// "dereferenceable" in the sense defined [here].
159 /// This applies even if the result of this method is unused!
160 /// (The part about being initialized is not yet fully decided, but until
161 /// it is the only safe approach is to ensure that they are indeed initialized.)
163 /// Additionally, the lifetime of `self` does not necessarily reflect the actual
164 /// lifetime of the data. *You* must enforce Rust's aliasing rules. In particular,
165 /// for the duration of this lifetime, the memory this pointer points to must not
166 /// get accessed (read or written) through any other pointer.
168 /// [here]: crate::ptr#safety
169 #[stable(feature = "nonnull", since = "1.25.0")]
171 pub unsafe fn as_mut(&mut self) -> &mut T {
172 // SAFETY: the caller must guarantee that `self` meets all the
173 // requirements for a mutable reference.
174 unsafe { &mut *self.as_ptr() }
177 /// Casts to a pointer of another type.
178 #[stable(feature = "nonnull_cast", since = "1.27.0")]
179 #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.32.0")]
181 pub const fn cast<U>(self) -> NonNull<U> {
182 // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
183 unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) }
187 impl<T> NonNull<[T]> {
188 /// Creates a non-null raw slice from a thin pointer and a length.
190 /// The `len` argument is the number of **elements**, not the number of bytes.
192 /// This function is safe, but dereferencing the return value is unsafe.
193 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
195 /// [`slice::from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
200 /// #![feature(nonnull_slice_from_raw_parts)]
202 /// use std::ptr::NonNull;
204 /// // create a slice pointer when starting out with a pointer to the first element
205 /// let mut x = [5, 6, 7];
206 /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
207 /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
208 /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
211 /// (Note that this example artificially demonstrates a use of this method,
212 /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
213 #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
214 #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
216 pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
217 // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
218 unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
221 /// Returns the length of a non-null raw slice.
223 /// The returned value is the number of **elements**, not the number of bytes.
225 /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
226 /// because the pointer does not have a valid address.
231 /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
232 /// use std::ptr::NonNull;
234 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
235 /// assert_eq!(slice.len(), 3);
237 #[unstable(feature = "slice_ptr_len", issue = "71146")]
238 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
240 pub const fn len(self) -> usize {
244 /// Returns a non-null pointer to the slice's buffer.
249 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
250 /// use std::ptr::NonNull;
252 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
253 /// assert_eq!(slice.as_non_null_ptr(), NonNull::new(1 as *mut i8).unwrap());
256 #[unstable(feature = "slice_ptr_get", issue = "74265")]
257 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
258 pub const fn as_non_null_ptr(self) -> NonNull<T> {
259 // SAFETY: We know `self` is non-null.
260 unsafe { NonNull::new_unchecked(self.as_ptr().as_mut_ptr()) }
263 /// Returns a raw pointer to the slice's buffer.
268 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
269 /// use std::ptr::NonNull;
271 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
272 /// assert_eq!(slice.as_mut_ptr(), 1 as *mut i8);
275 #[unstable(feature = "slice_ptr_get", issue = "74265")]
276 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
277 pub const fn as_mut_ptr(self) -> *mut T {
278 self.as_non_null_ptr().as_ptr()
281 /// Returns a raw pointer to an element or subslice, without doing bounds
284 /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
285 /// is *[undefined behavior]* even if the resulting pointer is not used.
287 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
292 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
293 /// use std::ptr::NonNull;
295 /// let x = &mut [1, 2, 4];
296 /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
299 /// assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
302 #[unstable(feature = "slice_ptr_get", issue = "74265")]
304 pub unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
308 // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
309 // As a consequence, the resulting pointer cannot be NULL.
310 unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
314 #[stable(feature = "nonnull", since = "1.25.0")]
315 impl<T: ?Sized> Clone for NonNull<T> {
317 fn clone(&self) -> Self {
322 #[stable(feature = "nonnull", since = "1.25.0")]
323 impl<T: ?Sized> Copy for NonNull<T> {}
325 #[unstable(feature = "coerce_unsized", issue = "27732")]
326 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
328 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
329 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
331 #[stable(feature = "nonnull", since = "1.25.0")]
332 impl<T: ?Sized> fmt::Debug for NonNull<T> {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 fmt::Pointer::fmt(&self.as_ptr(), f)
338 #[stable(feature = "nonnull", since = "1.25.0")]
339 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341 fmt::Pointer::fmt(&self.as_ptr(), f)
345 #[stable(feature = "nonnull", since = "1.25.0")]
346 impl<T: ?Sized> Eq for NonNull<T> {}
348 #[stable(feature = "nonnull", since = "1.25.0")]
349 impl<T: ?Sized> PartialEq for NonNull<T> {
351 fn eq(&self, other: &Self) -> bool {
352 self.as_ptr() == other.as_ptr()
356 #[stable(feature = "nonnull", since = "1.25.0")]
357 impl<T: ?Sized> Ord for NonNull<T> {
359 fn cmp(&self, other: &Self) -> Ordering {
360 self.as_ptr().cmp(&other.as_ptr())
364 #[stable(feature = "nonnull", since = "1.25.0")]
365 impl<T: ?Sized> PartialOrd for NonNull<T> {
367 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
368 self.as_ptr().partial_cmp(&other.as_ptr())
372 #[stable(feature = "nonnull", since = "1.25.0")]
373 impl<T: ?Sized> hash::Hash for NonNull<T> {
375 fn hash<H: hash::Hasher>(&self, state: &mut H) {
376 self.as_ptr().hash(state)
380 #[unstable(feature = "ptr_internals", issue = "none")]
381 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
383 fn from(unique: Unique<T>) -> Self {
384 // SAFETY: A Unique pointer cannot be null, so the conditions for
385 // new_unchecked() are respected.
386 unsafe { NonNull::new_unchecked(unique.as_ptr()) }
390 #[stable(feature = "nonnull", since = "1.25.0")]
391 impl<T: ?Sized> From<&mut T> for NonNull<T> {
393 fn from(reference: &mut T) -> Self {
394 // SAFETY: A mutable reference cannot be null.
395 unsafe { NonNull { pointer: reference as *mut T } }
399 #[stable(feature = "nonnull", since = "1.25.0")]
400 impl<T: ?Sized> From<&T> for NonNull<T> {
402 fn from(reference: &T) -> Self {
403 // SAFETY: A reference cannot be null, so the conditions for
404 // new_unchecked() are respected.
405 unsafe { NonNull { pointer: reference as *const T } }