]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/non_null.rs
d876ab23653f367925b8f904ad1891705a080356
[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     ///
121     /// # Safety
122     ///
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].
127     ///
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.)
131     ///
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`).
136     ///
137     /// [here]: crate::ptr#safety
138     #[stable(feature = "nonnull", since = "1.25.0")]
139     #[inline]
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() }
144     }
145
146     /// Mutably dereferences the content.
147     ///
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()`.
151     ///
152     /// # Safety
153     ///
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].
158     ///
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.)
162     ///
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.
167     ///
168     /// [here]: crate::ptr#safety
169     #[stable(feature = "nonnull", since = "1.25.0")]
170     #[inline]
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() }
175     }
176
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")]
180     #[inline]
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) }
184     }
185 }
186
187 impl<T> NonNull<[T]> {
188     /// Creates a non-null raw slice from a thin pointer and a length.
189     ///
190     /// The `len` argument is the number of **elements**, not the number of bytes.
191     ///
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.
194     ///
195     /// [`slice::from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
196     ///
197     /// # Examples
198     ///
199     /// ```rust
200     /// #![feature(nonnull_slice_from_raw_parts)]
201     ///
202     /// use std::ptr::NonNull;
203     ///
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);
209     /// ```
210     ///
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")]
215     #[inline]
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)) }
219     }
220
221     /// Returns the length of a non-null raw slice.
222     ///
223     /// The returned value is the number of **elements**, not the number of bytes.
224     ///
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.
227     ///
228     /// # Examples
229     ///
230     /// ```rust
231     /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
232     /// use std::ptr::NonNull;
233     ///
234     /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
235     /// assert_eq!(slice.len(), 3);
236     /// ```
237     #[unstable(feature = "slice_ptr_len", issue = "71146")]
238     #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
239     #[inline]
240     pub const fn len(self) -> usize {
241         self.as_ptr().len()
242     }
243
244     /// Returns a non-null pointer to the slice's buffer.
245     ///
246     /// # Examples
247     ///
248     /// ```rust
249     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
250     /// use std::ptr::NonNull;
251     ///
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());
254     /// ```
255     #[inline]
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()) }
261     }
262
263     /// Returns a raw pointer to the slice's buffer.
264     ///
265     /// # Examples
266     ///
267     /// ```rust
268     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
269     /// use std::ptr::NonNull;
270     ///
271     /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
272     /// assert_eq!(slice.as_mut_ptr(), 1 as *mut i8);
273     /// ```
274     #[inline]
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()
279     }
280
281     /// Returns a raw pointer to an element or subslice, without doing bounds
282     /// checking.
283     ///
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.
286     ///
287     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
288     ///
289     /// # Examples
290     ///
291     /// ```
292     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
293     /// use std::ptr::NonNull;
294     ///
295     /// let x = &mut [1, 2, 4];
296     /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
297     ///
298     /// unsafe {
299     ///     assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
300     /// }
301     /// ```
302     #[unstable(feature = "slice_ptr_get", issue = "74265")]
303     #[inline]
304     pub unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
305     where
306         I: SliceIndex<[T]>,
307     {
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)) }
311     }
312 }
313
314 #[stable(feature = "nonnull", since = "1.25.0")]
315 impl<T: ?Sized> Clone for NonNull<T> {
316     #[inline]
317     fn clone(&self) -> Self {
318         *self
319     }
320 }
321
322 #[stable(feature = "nonnull", since = "1.25.0")]
323 impl<T: ?Sized> Copy for NonNull<T> {}
324
325 #[unstable(feature = "coerce_unsized", issue = "27732")]
326 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
327
328 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
329 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
330
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)
335     }
336 }
337
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)
342     }
343 }
344
345 #[stable(feature = "nonnull", since = "1.25.0")]
346 impl<T: ?Sized> Eq for NonNull<T> {}
347
348 #[stable(feature = "nonnull", since = "1.25.0")]
349 impl<T: ?Sized> PartialEq for NonNull<T> {
350     #[inline]
351     fn eq(&self, other: &Self) -> bool {
352         self.as_ptr() == other.as_ptr()
353     }
354 }
355
356 #[stable(feature = "nonnull", since = "1.25.0")]
357 impl<T: ?Sized> Ord for NonNull<T> {
358     #[inline]
359     fn cmp(&self, other: &Self) -> Ordering {
360         self.as_ptr().cmp(&other.as_ptr())
361     }
362 }
363
364 #[stable(feature = "nonnull", since = "1.25.0")]
365 impl<T: ?Sized> PartialOrd for NonNull<T> {
366     #[inline]
367     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
368         self.as_ptr().partial_cmp(&other.as_ptr())
369     }
370 }
371
372 #[stable(feature = "nonnull", since = "1.25.0")]
373 impl<T: ?Sized> hash::Hash for NonNull<T> {
374     #[inline]
375     fn hash<H: hash::Hasher>(&self, state: &mut H) {
376         self.as_ptr().hash(state)
377     }
378 }
379
380 #[unstable(feature = "ptr_internals", issue = "none")]
381 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
382     #[inline]
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()) }
387     }
388 }
389
390 #[stable(feature = "nonnull", since = "1.25.0")]
391 impl<T: ?Sized> From<&mut T> for NonNull<T> {
392     #[inline]
393     fn from(reference: &mut T) -> Self {
394         // SAFETY: A mutable reference cannot be null.
395         unsafe { NonNull { pointer: reference as *mut T } }
396     }
397 }
398
399 #[stable(feature = "nonnull", since = "1.25.0")]
400 impl<T: ?Sized> From<&T> for NonNull<T> {
401     #[inline]
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 } }
406     }
407 }