]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr/non_null.rs
Deny unsafe ops in unsafe fns, part 6
[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         // SAFETY: the caller must guarantee that `ptr` is non-null.
91         unsafe { NonNull { pointer: ptr as _ } }
92     }
93
94     /// Creates a new `NonNull` if `ptr` is non-null.
95     #[stable(feature = "nonnull", since = "1.25.0")]
96     #[inline]
97     pub fn new(ptr: *mut T) -> Option<Self> {
98         if !ptr.is_null() {
99             // SAFETY: The pointer is already checked and is not null
100             Some(unsafe { Self::new_unchecked(ptr) })
101         } else {
102             None
103         }
104     }
105
106     /// Acquires the underlying `*mut` pointer.
107     #[stable(feature = "nonnull", since = "1.25.0")]
108     #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
109     #[inline]
110     pub const fn as_ptr(self) -> *mut T {
111         self.pointer as *mut T
112     }
113
114     /// Dereferences the content.
115     ///
116     /// The resulting lifetime is bound to self so this behaves "as if"
117     /// it were actually an instance of T that is getting borrowed. If a longer
118     /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
119     #[stable(feature = "nonnull", since = "1.25.0")]
120     #[inline]
121     pub unsafe fn as_ref(&self) -> &T {
122         // SAFETY: the caller must guarantee that `self` meets all the
123         // requirements for a reference.
124         unsafe { &*self.as_ptr() }
125     }
126
127     /// Mutably dereferences the content.
128     ///
129     /// The resulting lifetime is bound to self so this behaves "as if"
130     /// it were actually an instance of T that is getting borrowed. If a longer
131     /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
132     #[stable(feature = "nonnull", since = "1.25.0")]
133     #[inline]
134     pub unsafe fn as_mut(&mut self) -> &mut T {
135         // SAFETY: the caller must guarantee that `self` meets all the
136         // requirements for a mutable reference.
137         unsafe { &mut *self.as_ptr() }
138     }
139
140     /// Casts to a pointer of another type.
141     #[stable(feature = "nonnull_cast", since = "1.27.0")]
142     #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.32.0")]
143     #[inline]
144     pub const fn cast<U>(self) -> NonNull<U> {
145         // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
146         unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) }
147     }
148 }
149
150 impl<T> NonNull<[T]> {
151     /// Creates a non-null raw slice from a thin pointer and a length.
152     ///
153     /// The `len` argument is the number of **elements**, not the number of bytes.
154     ///
155     /// This function is safe, but dereferencing the return value is unsafe.
156     /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
157     ///
158     /// [`slice::from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
159     ///
160     /// # Examples
161     ///
162     /// ```rust
163     /// #![feature(nonnull_slice_from_raw_parts)]
164     ///
165     /// use std::ptr::NonNull;
166     ///
167     /// // create a slice pointer when starting out with a pointer to the first element
168     /// let mut x = [5, 6, 7];
169     /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
170     /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
171     /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
172     /// ```
173     ///
174     /// (Note that this example artifically demonstrates a use of this method,
175     /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
176     #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
177     #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
178     #[inline]
179     pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
180         // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
181         unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
182     }
183
184     /// Returns the length of a non-null raw slice.
185     ///
186     /// The returned value is the number of **elements**, not the number of bytes.
187     ///
188     /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
189     /// because the pointer does not have a valid address.
190     ///
191     /// # Examples
192     ///
193     /// ```rust
194     /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
195     ///
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
209 #[stable(feature = "nonnull", since = "1.25.0")]
210 impl<T: ?Sized> Clone for NonNull<T> {
211     #[inline]
212     fn clone(&self) -> Self {
213         *self
214     }
215 }
216
217 #[stable(feature = "nonnull", since = "1.25.0")]
218 impl<T: ?Sized> Copy for NonNull<T> {}
219
220 #[unstable(feature = "coerce_unsized", issue = "27732")]
221 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
222
223 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
224 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
225
226 #[stable(feature = "nonnull", since = "1.25.0")]
227 impl<T: ?Sized> fmt::Debug for NonNull<T> {
228     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229         fmt::Pointer::fmt(&self.as_ptr(), f)
230     }
231 }
232
233 #[stable(feature = "nonnull", since = "1.25.0")]
234 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
235     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236         fmt::Pointer::fmt(&self.as_ptr(), f)
237     }
238 }
239
240 #[stable(feature = "nonnull", since = "1.25.0")]
241 impl<T: ?Sized> Eq for NonNull<T> {}
242
243 #[stable(feature = "nonnull", since = "1.25.0")]
244 impl<T: ?Sized> PartialEq for NonNull<T> {
245     #[inline]
246     fn eq(&self, other: &Self) -> bool {
247         self.as_ptr() == other.as_ptr()
248     }
249 }
250
251 #[stable(feature = "nonnull", since = "1.25.0")]
252 impl<T: ?Sized> Ord for NonNull<T> {
253     #[inline]
254     fn cmp(&self, other: &Self) -> Ordering {
255         self.as_ptr().cmp(&other.as_ptr())
256     }
257 }
258
259 #[stable(feature = "nonnull", since = "1.25.0")]
260 impl<T: ?Sized> PartialOrd for NonNull<T> {
261     #[inline]
262     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
263         self.as_ptr().partial_cmp(&other.as_ptr())
264     }
265 }
266
267 #[stable(feature = "nonnull", since = "1.25.0")]
268 impl<T: ?Sized> hash::Hash for NonNull<T> {
269     #[inline]
270     fn hash<H: hash::Hasher>(&self, state: &mut H) {
271         self.as_ptr().hash(state)
272     }
273 }
274
275 #[unstable(feature = "ptr_internals", issue = "none")]
276 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
277     #[inline]
278     fn from(unique: Unique<T>) -> Self {
279         // SAFETY: A Unique pointer cannot be null, so the conditions for
280         // new_unchecked() are respected.
281         unsafe { NonNull::new_unchecked(unique.as_ptr()) }
282     }
283 }
284
285 #[stable(feature = "nonnull", since = "1.25.0")]
286 impl<T: ?Sized> From<&mut T> for NonNull<T> {
287     #[inline]
288     fn from(reference: &mut T) -> Self {
289         // SAFETY: A mutable reference cannot be null.
290         unsafe { NonNull { pointer: reference as *mut T } }
291     }
292 }
293
294 #[stable(feature = "nonnull", since = "1.25.0")]
295 impl<T: ?Sized> From<&T> for NonNull<T> {
296     #[inline]
297     fn from(reference: &T) -> Self {
298         // SAFETY: A reference cannot be null, so the conditions for
299         // new_unchecked() are respected.
300         unsafe { NonNull { pointer: reference as *const T } }
301     }
302 }