1 use crate::convert::From;
2 use crate::ops::{CoerceUnsized, DispatchFromDyn};
5 use crate::marker::Unsize;
7 use crate::ptr::Unique;
8 use crate::cmp::Ordering;
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 #[cfg_attr(not(stage0), 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")]
68 pub const fn dangling() -> Self {
70 let ptr = mem::align_of::<T>() as *mut T;
71 NonNull::new_unchecked(ptr)
76 impl<T: ?Sized> NonNull<T> {
77 /// Creates a new `NonNull`.
81 /// `ptr` must be non-null.
82 #[stable(feature = "nonnull", since = "1.25.0")]
84 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
85 NonNull { pointer: ptr as _ }
88 /// Creates a new `NonNull` if `ptr` is non-null.
89 #[stable(feature = "nonnull", since = "1.25.0")]
91 pub fn new(ptr: *mut T) -> Option<Self> {
93 Some(unsafe { Self::new_unchecked(ptr) })
99 /// Acquires the underlying `*mut` pointer.
100 #[stable(feature = "nonnull", since = "1.25.0")]
102 pub const fn as_ptr(self) -> *mut T {
103 self.pointer as *mut T
106 /// Dereferences the content.
108 /// The resulting lifetime is bound to self so this behaves "as if"
109 /// it were actually an instance of T that is getting borrowed. If a longer
110 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
111 #[stable(feature = "nonnull", since = "1.25.0")]
113 pub unsafe fn as_ref(&self) -> &T {
117 /// Mutably dereferences the content.
119 /// The resulting lifetime is bound to self so this behaves "as if"
120 /// it were actually an instance of T that is getting borrowed. If a longer
121 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
122 #[stable(feature = "nonnull", since = "1.25.0")]
124 pub unsafe fn as_mut(&mut self) -> &mut T {
128 /// Cast to a pointer of another type
129 #[stable(feature = "nonnull_cast", since = "1.27.0")]
131 pub const fn cast<U>(self) -> NonNull<U> {
133 NonNull::new_unchecked(self.as_ptr() as *mut U)
138 #[stable(feature = "nonnull", since = "1.25.0")]
139 impl<T: ?Sized> Clone for NonNull<T> {
141 fn clone(&self) -> Self {
146 #[stable(feature = "nonnull", since = "1.25.0")]
147 impl<T: ?Sized> Copy for NonNull<T> { }
149 #[unstable(feature = "coerce_unsized", issue = "27732")]
150 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
152 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
153 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> { }
155 #[stable(feature = "nonnull", since = "1.25.0")]
156 impl<T: ?Sized> fmt::Debug for NonNull<T> {
157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158 fmt::Pointer::fmt(&self.as_ptr(), f)
162 #[stable(feature = "nonnull", since = "1.25.0")]
163 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 fmt::Pointer::fmt(&self.as_ptr(), f)
169 #[stable(feature = "nonnull", since = "1.25.0")]
170 impl<T: ?Sized> Eq for NonNull<T> {}
172 #[stable(feature = "nonnull", since = "1.25.0")]
173 impl<T: ?Sized> PartialEq for NonNull<T> {
175 fn eq(&self, other: &Self) -> bool {
176 self.as_ptr() == other.as_ptr()
180 #[stable(feature = "nonnull", since = "1.25.0")]
181 impl<T: ?Sized> Ord for NonNull<T> {
183 fn cmp(&self, other: &Self) -> Ordering {
184 self.as_ptr().cmp(&other.as_ptr())
188 #[stable(feature = "nonnull", since = "1.25.0")]
189 impl<T: ?Sized> PartialOrd for NonNull<T> {
191 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
192 self.as_ptr().partial_cmp(&other.as_ptr())
196 #[stable(feature = "nonnull", since = "1.25.0")]
197 impl<T: ?Sized> hash::Hash for NonNull<T> {
199 fn hash<H: hash::Hasher>(&self, state: &mut H) {
200 self.as_ptr().hash(state)
204 #[unstable(feature = "ptr_internals", issue = "0")]
205 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
207 fn from(unique: Unique<T>) -> Self {
208 unsafe { NonNull::new_unchecked(unique.as_ptr()) }
212 #[stable(feature = "nonnull", since = "1.25.0")]
213 impl<T: ?Sized> From<&mut T> for NonNull<T> {
215 fn from(reference: &mut T) -> Self {
216 unsafe { NonNull { pointer: reference as *mut T } }
220 #[stable(feature = "nonnull", since = "1.25.0")]
221 impl<T: ?Sized> From<&T> for NonNull<T> {
223 fn from(reference: &T) -> Self {
224 unsafe { NonNull { pointer: reference as *const T } }