]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/non_null.rs
Merge branch 'master' into feature/incorporate-tracing
[rust.git] / library / core / src / 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 use crate::slice::SliceIndex;
10
11 /// `*mut T` but non-zero and covariant.
12 ///
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`!
16 ///
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.
21 ///
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.
28 ///
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.
36 ///
37 /// [`PhantomData`]: ../marker/struct.PhantomData.html
38 /// [`UnsafeCell<T>`]: ../cell/struct.UnsafeCell.html
39 #[stable(feature = "nonnull", since = "1.25.0")]
40 #[repr(transparent)]
41 #[rustc_layout_scalar_valid_range_start(1)]
42 #[rustc_nonnull_optimization_guaranteed]
43 pub struct NonNull<T: ?Sized> {
44     pointer: *const T,
45 }
46
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> {}
51
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> {}
56
57 impl<T: Sized> NonNull<T> {
58     /// Creates a new `NonNull` that is dangling, but well-aligned.
59     ///
60     /// This is useful for initializing types which lazily allocate, like
61     /// `Vec::new` does.
62     ///
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
66     /// some other means.
67     #[stable(feature = "nonnull", since = "1.25.0")]
68     #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.32.0")]
69     #[inline]
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.
74         unsafe {
75             let ptr = mem::align_of::<T>() as *mut T;
76             NonNull::new_unchecked(ptr)
77         }
78     }
79 }
80
81 impl<T: ?Sized> NonNull<T> {
82     /// Creates a new `NonNull`.
83     ///
84     /// # Safety
85     ///
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")]
89     #[inline]
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 _ } }
93     }
94
95     /// Creates a new `NonNull` if `ptr` is non-null.
96     #[stable(feature = "nonnull", since = "1.25.0")]
97     #[inline]
98     pub fn new(ptr: *mut T) -> Option<Self> {
99         if !ptr.is_null() {
100             // SAFETY: The pointer is already checked and is not null
101             Some(unsafe { Self::new_unchecked(ptr) })
102         } else {
103             None
104         }
105     }
106
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")]
110     #[inline]
111     pub const fn as_ptr(self) -> *mut T {
112         self.pointer as *mut T
113     }
114
115     /// Dereferences the content.
116     ///
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")]
121     #[inline]
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() }
126     }
127
128     /// Mutably dereferences the content.
129     ///
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")]
134     #[inline]
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() }
139     }
140
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")]
144     #[inline]
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) }
148     }
149 }
150
151 impl<T> NonNull<[T]> {
152     /// Creates a non-null raw slice from a thin pointer and a length.
153     ///
154     /// The `len` argument is the number of **elements**, not the number of bytes.
155     ///
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.
158     ///
159     /// [`slice::from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
160     ///
161     /// # Examples
162     ///
163     /// ```rust
164     /// #![feature(nonnull_slice_from_raw_parts)]
165     ///
166     /// use std::ptr::NonNull;
167     ///
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);
173     /// ```
174     ///
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")]
179     #[inline]
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)) }
183     }
184
185     /// Returns the length of a non-null raw slice.
186     ///
187     /// The returned value is the number of **elements**, not the number of bytes.
188     ///
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.
191     ///
192     /// # Examples
193     ///
194     /// ```rust
195     /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
196     /// use std::ptr::NonNull;
197     ///
198     /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
199     /// assert_eq!(slice.len(), 3);
200     /// ```
201     #[unstable(feature = "slice_ptr_len", issue = "71146")]
202     #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
203     #[inline]
204     pub const fn len(self) -> usize {
205         self.as_ptr().len()
206     }
207
208     /// Returns a non-null pointer to the slice's buffer.
209     ///
210     /// # Examples
211     ///
212     /// ```rust
213     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
214     /// use std::ptr::NonNull;
215     ///
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());
218     /// ```
219     #[inline]
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()) }
225     }
226
227     /// Returns a raw pointer to an element or subslice, without doing bounds
228     /// checking.
229     ///
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.
232     ///
233     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
234     ///
235     /// # Examples
236     ///
237     /// ```
238     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
239     /// use std::ptr::NonNull;
240     ///
241     /// let x = &mut [1, 2, 4];
242     /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
243     ///
244     /// unsafe {
245     ///     assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
246     /// }
247     /// ```
248     #[unstable(feature = "slice_ptr_get", issue = "74265")]
249     #[inline]
250     pub unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
251     where
252         I: SliceIndex<[T]>,
253     {
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)) }
257     }
258 }
259
260 #[stable(feature = "nonnull", since = "1.25.0")]
261 impl<T: ?Sized> Clone for NonNull<T> {
262     #[inline]
263     fn clone(&self) -> Self {
264         *self
265     }
266 }
267
268 #[stable(feature = "nonnull", since = "1.25.0")]
269 impl<T: ?Sized> Copy for NonNull<T> {}
270
271 #[unstable(feature = "coerce_unsized", issue = "27732")]
272 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
273
274 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
275 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
276
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)
281     }
282 }
283
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)
288     }
289 }
290
291 #[stable(feature = "nonnull", since = "1.25.0")]
292 impl<T: ?Sized> Eq for NonNull<T> {}
293
294 #[stable(feature = "nonnull", since = "1.25.0")]
295 impl<T: ?Sized> PartialEq for NonNull<T> {
296     #[inline]
297     fn eq(&self, other: &Self) -> bool {
298         self.as_ptr() == other.as_ptr()
299     }
300 }
301
302 #[stable(feature = "nonnull", since = "1.25.0")]
303 impl<T: ?Sized> Ord for NonNull<T> {
304     #[inline]
305     fn cmp(&self, other: &Self) -> Ordering {
306         self.as_ptr().cmp(&other.as_ptr())
307     }
308 }
309
310 #[stable(feature = "nonnull", since = "1.25.0")]
311 impl<T: ?Sized> PartialOrd for NonNull<T> {
312     #[inline]
313     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
314         self.as_ptr().partial_cmp(&other.as_ptr())
315     }
316 }
317
318 #[stable(feature = "nonnull", since = "1.25.0")]
319 impl<T: ?Sized> hash::Hash for NonNull<T> {
320     #[inline]
321     fn hash<H: hash::Hasher>(&self, state: &mut H) {
322         self.as_ptr().hash(state)
323     }
324 }
325
326 #[unstable(feature = "ptr_internals", issue = "none")]
327 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
328     #[inline]
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()) }
333     }
334 }
335
336 #[stable(feature = "nonnull", since = "1.25.0")]
337 impl<T: ?Sized> From<&mut T> for NonNull<T> {
338     #[inline]
339     fn from(reference: &mut T) -> Self {
340         // SAFETY: A mutable reference cannot be null.
341         unsafe { NonNull { pointer: reference as *mut T } }
342     }
343 }
344
345 #[stable(feature = "nonnull", since = "1.25.0")]
346 impl<T: ?Sized> From<&T> for NonNull<T> {
347     #[inline]
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 } }
352     }
353 }