]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr/non_null.rs
Auto merge of #72562 - RalfJung:rollup-2ngjgwi, r=RalfJung
[rust.git] / src / libcore / ptr / non_null.rs
1 use crate::cmp::Ordering;
2 use crate::convert::From;
3 use crate::fmt;
4 use crate::hash;
5 use crate::marker::Unsize;
6 use crate::mem;
7 use crate::ops::{CoerceUnsized, DispatchFromDyn};
8 use crate::ptr::Unique;
9
10 /// `*mut T` but non-zero and covariant.
11 ///
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`!
15 ///
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.
20 ///
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.
27 ///
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.
35 ///
36 /// [`PhantomData`]: ../marker/struct.PhantomData.html
37 /// [`UnsafeCell<T>`]: ../cell/struct.UnsafeCell.html
38 #[stable(feature = "nonnull", since = "1.25.0")]
39 #[repr(transparent)]
40 #[rustc_layout_scalar_valid_range_start(1)]
41 #[rustc_nonnull_optimization_guaranteed]
42 pub struct NonNull<T: ?Sized> {
43     pointer: *const T,
44 }
45
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> {}
50
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> {}
55
56 impl<T: Sized> NonNull<T> {
57     /// Creates a new `NonNull` that is dangling, but well-aligned.
58     ///
59     /// This is useful for initializing types which lazily allocate, like
60     /// `Vec::new` does.
61     ///
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
65     /// some other means.
66     #[stable(feature = "nonnull", since = "1.25.0")]
67     #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.32.0")]
68     #[inline]
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.
73         unsafe {
74             let ptr = mem::align_of::<T>() as *mut T;
75             NonNull::new_unchecked(ptr)
76         }
77     }
78 }
79
80 impl<T: ?Sized> NonNull<T> {
81     /// Creates a new `NonNull`.
82     ///
83     /// # Safety
84     ///
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")]
88     #[inline]
89     pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
90         NonNull { pointer: ptr as _ }
91     }
92
93     /// Creates a new `NonNull` if `ptr` is non-null.
94     #[stable(feature = "nonnull", since = "1.25.0")]
95     #[inline]
96     pub fn new(ptr: *mut T) -> Option<Self> {
97         if !ptr.is_null() {
98             // SAFETY: The pointer is already checked and is not null
99             Some(unsafe { Self::new_unchecked(ptr) })
100         } else {
101             None
102         }
103     }
104
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")]
108     #[inline]
109     pub const fn as_ptr(self) -> *mut T {
110         self.pointer as *mut T
111     }
112
113     /// Dereferences the content.
114     ///
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")]
119     #[inline]
120     pub unsafe fn as_ref(&self) -> &T {
121         &*self.as_ptr()
122     }
123
124     /// Mutably dereferences the content.
125     ///
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")]
130     #[inline]
131     pub unsafe fn as_mut(&mut self) -> &mut T {
132         &mut *self.as_ptr()
133     }
134
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")]
138     #[inline]
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) }
142     }
143 }
144
145 impl<T> NonNull<[T]> {
146     /// Creates a non-null raw slice from a thin pointer and a length.
147     ///
148     /// The `len` argument is the number of **elements**, not the number of bytes.
149     ///
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.
152     ///
153     /// [`slice::from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
154     ///
155     /// # Examples
156     ///
157     /// ```rust
158     /// #![feature(nonnull_slice_from_raw_parts)]
159     ///
160     /// use std::ptr::NonNull;
161     ///
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);
167     /// ```
168     ///
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")]
173     #[inline]
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)) }
177     }
178
179     /// Returns the length of a non-null raw slice.
180     ///
181     /// The returned value is the number of **elements**, not the number of bytes.
182     ///
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.
185     ///
186     /// # Examples
187     ///
188     /// ```rust
189     /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
190     ///
191     /// use std::ptr::NonNull;
192     ///
193     /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
194     /// assert_eq!(slice.len(), 3);
195     /// ```
196     #[unstable(feature = "slice_ptr_len", issue = "71146")]
197     #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
198     #[inline]
199     pub const fn len(self) -> usize {
200         self.as_ptr().len()
201     }
202 }
203
204 #[stable(feature = "nonnull", since = "1.25.0")]
205 impl<T: ?Sized> Clone for NonNull<T> {
206     #[inline]
207     fn clone(&self) -> Self {
208         *self
209     }
210 }
211
212 #[stable(feature = "nonnull", since = "1.25.0")]
213 impl<T: ?Sized> Copy for NonNull<T> {}
214
215 #[unstable(feature = "coerce_unsized", issue = "27732")]
216 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
217
218 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
219 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
220
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)
225     }
226 }
227
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)
232     }
233 }
234
235 #[stable(feature = "nonnull", since = "1.25.0")]
236 impl<T: ?Sized> Eq for NonNull<T> {}
237
238 #[stable(feature = "nonnull", since = "1.25.0")]
239 impl<T: ?Sized> PartialEq for NonNull<T> {
240     #[inline]
241     fn eq(&self, other: &Self) -> bool {
242         self.as_ptr() == other.as_ptr()
243     }
244 }
245
246 #[stable(feature = "nonnull", since = "1.25.0")]
247 impl<T: ?Sized> Ord for NonNull<T> {
248     #[inline]
249     fn cmp(&self, other: &Self) -> Ordering {
250         self.as_ptr().cmp(&other.as_ptr())
251     }
252 }
253
254 #[stable(feature = "nonnull", since = "1.25.0")]
255 impl<T: ?Sized> PartialOrd for NonNull<T> {
256     #[inline]
257     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
258         self.as_ptr().partial_cmp(&other.as_ptr())
259     }
260 }
261
262 #[stable(feature = "nonnull", since = "1.25.0")]
263 impl<T: ?Sized> hash::Hash for NonNull<T> {
264     #[inline]
265     fn hash<H: hash::Hasher>(&self, state: &mut H) {
266         self.as_ptr().hash(state)
267     }
268 }
269
270 #[unstable(feature = "ptr_internals", issue = "none")]
271 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
272     #[inline]
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()) }
277     }
278 }
279
280 #[stable(feature = "nonnull", since = "1.25.0")]
281 impl<T: ?Sized> From<&mut T> for NonNull<T> {
282     #[inline]
283     fn from(reference: &mut T) -> Self {
284         // SAFETY: A mutable reference cannot be null.
285         unsafe { NonNull { pointer: reference as *mut T } }
286     }
287 }
288
289 #[stable(feature = "nonnull", since = "1.25.0")]
290 impl<T: ?Sized> From<&T> for NonNull<T> {
291     #[inline]
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 } }
296     }
297 }