]> git.proxmox.com Git - rustc.git/blob - library/core/src/ptr/non_null.rs
New upstream version 1.54.0+dfsg1
[rustc.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::{self, MaybeUninit};
7 use crate::ops::{CoerceUnsized, DispatchFromDyn};
8 use crate::ptr::Unique;
9 use crate::slice::{self, 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>` was chosen to be covariant over `T`. This makes it
23 /// possible to use `NonNull<T>` when building covariant types, but introduces the
24 /// risk of unsoundness if used in a type that shouldn't actually be covariant.
25 /// (The opposite choice was made for `*mut T` even though technically the unsoundness
26 /// could only be caused by calling unsafe functions.)
27 ///
28 /// Covariance is correct for most safe abstractions, such as `Box`, `Rc`, `Arc`, `Vec`,
29 /// and `LinkedList`. This is the case because they provide a public API that follows the
30 /// normal shared XOR mutable rules of Rust.
31 ///
32 /// If your type cannot safely be covariant, you must ensure it contains some
33 /// additional field to provide invariance. Often this field will be a [`PhantomData`]
34 /// type like `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
35 ///
36 /// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
37 /// not change the fact that mutating through a (pointer derived from a) shared
38 /// reference is undefined behavior unless the mutation happens inside an
39 /// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
40 /// reference. When using this `From` instance without an `UnsafeCell<T>`,
41 /// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
42 /// is never used for mutation.
43 ///
44 /// [`PhantomData`]: crate::marker::PhantomData
45 /// [`UnsafeCell<T>`]: crate::cell::UnsafeCell
46 #[stable(feature = "nonnull", since = "1.25.0")]
47 #[repr(transparent)]
48 #[rustc_layout_scalar_valid_range_start(1)]
49 #[rustc_nonnull_optimization_guaranteed]
50 pub struct NonNull<T: ?Sized> {
51 pointer: *const T,
52 }
53
54 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
55 // N.B., this impl is unnecessary, but should provide better error messages.
56 #[stable(feature = "nonnull", since = "1.25.0")]
57 impl<T: ?Sized> !Send for NonNull<T> {}
58
59 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
60 // N.B., this impl is unnecessary, but should provide better error messages.
61 #[stable(feature = "nonnull", since = "1.25.0")]
62 impl<T: ?Sized> !Sync for NonNull<T> {}
63
64 impl<T: Sized> NonNull<T> {
65 /// Creates a new `NonNull` that is dangling, but well-aligned.
66 ///
67 /// This is useful for initializing types which lazily allocate, like
68 /// `Vec::new` does.
69 ///
70 /// Note that the pointer value may potentially represent a valid pointer to
71 /// a `T`, which means this must not be used as a "not yet initialized"
72 /// sentinel value. Types that lazily allocate must track initialization by
73 /// some other means.
74 #[stable(feature = "nonnull", since = "1.25.0")]
75 #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.36.0")]
76 #[inline]
77 pub const fn dangling() -> Self {
78 // SAFETY: mem::align_of() returns a non-zero usize which is then casted
79 // to a *mut T. Therefore, `ptr` is not null and the conditions for
80 // calling new_unchecked() are respected.
81 unsafe {
82 let ptr = mem::align_of::<T>() as *mut T;
83 NonNull::new_unchecked(ptr)
84 }
85 }
86
87 /// Returns a shared references to the value. In contrast to [`as_ref`], this does not require
88 /// that the value has to be initialized.
89 ///
90 /// For the mutable counterpart see [`as_uninit_mut`].
91 ///
92 /// [`as_ref`]: NonNull::as_ref
93 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
94 ///
95 /// # Safety
96 ///
97 /// When calling this method, you have to ensure that all of the following is true:
98 ///
99 /// * The pointer must be properly aligned.
100 ///
101 /// * It must be "dereferencable" in the sense defined in [the module documentation].
102 ///
103 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
104 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
105 /// In particular, for the duration of this lifetime, the memory the pointer points to must
106 /// not get mutated (except inside `UnsafeCell`).
107 ///
108 /// This applies even if the result of this method is unused!
109 ///
110 /// [the module documentation]: crate::ptr#safety
111 #[inline]
112 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
113 pub unsafe fn as_uninit_ref<'a>(&self) -> &'a MaybeUninit<T> {
114 // SAFETY: the caller must guarantee that `self` meets all the
115 // requirements for a reference.
116 unsafe { &*self.cast().as_ptr() }
117 }
118
119 /// Returns a unique references to the value. In contrast to [`as_mut`], this does not require
120 /// that the value has to be initialized.
121 ///
122 /// For the shared counterpart see [`as_uninit_ref`].
123 ///
124 /// [`as_mut`]: NonNull::as_mut
125 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
126 ///
127 /// # Safety
128 ///
129 /// When calling this method, you have to ensure that all of the following is true:
130 ///
131 /// * The pointer must be properly aligned.
132 ///
133 /// * It must be "dereferencable" in the sense defined in [the module documentation].
134 ///
135 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
136 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
137 /// In particular, for the duration of this lifetime, the memory the pointer points to must
138 /// not get accessed (read or written) through any other pointer.
139 ///
140 /// This applies even if the result of this method is unused!
141 ///
142 /// [the module documentation]: crate::ptr#safety
143 #[inline]
144 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
145 pub unsafe fn as_uninit_mut<'a>(&mut self) -> &'a mut MaybeUninit<T> {
146 // SAFETY: the caller must guarantee that `self` meets all the
147 // requirements for a reference.
148 unsafe { &mut *self.cast().as_ptr() }
149 }
150 }
151
152 impl<T: ?Sized> NonNull<T> {
153 /// Creates a new `NonNull`.
154 ///
155 /// # Safety
156 ///
157 /// `ptr` must be non-null.
158 #[stable(feature = "nonnull", since = "1.25.0")]
159 #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.25.0")]
160 #[inline]
161 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
162 // SAFETY: the caller must guarantee that `ptr` is non-null.
163 unsafe { NonNull { pointer: ptr as _ } }
164 }
165
166 /// Creates a new `NonNull` if `ptr` is non-null.
167 #[stable(feature = "nonnull", since = "1.25.0")]
168 #[inline]
169 pub fn new(ptr: *mut T) -> Option<Self> {
170 if !ptr.is_null() {
171 // SAFETY: The pointer is already checked and is not null
172 Some(unsafe { Self::new_unchecked(ptr) })
173 } else {
174 None
175 }
176 }
177
178 /// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a
179 /// `NonNull` pointer is returned, as opposed to a raw `*const` pointer.
180 ///
181 /// See the documentation of [`std::ptr::from_raw_parts`] for more details.
182 ///
183 /// [`std::ptr::from_raw_parts`]: crate::ptr::from_raw_parts
184 #[unstable(feature = "ptr_metadata", issue = "81513")]
185 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
186 #[inline]
187 pub const fn from_raw_parts(
188 data_address: NonNull<()>,
189 metadata: <T as super::Pointee>::Metadata,
190 ) -> NonNull<T> {
191 // SAFETY: The result of `ptr::from::raw_parts_mut` is non-null because `data_address` is.
192 unsafe {
193 NonNull::new_unchecked(super::from_raw_parts_mut(data_address.as_ptr(), metadata))
194 }
195 }
196
197 /// Decompose a (possibly wide) pointer into is address and metadata components.
198 ///
199 /// The pointer can be later reconstructed with [`NonNull::from_raw_parts`].
200 #[unstable(feature = "ptr_metadata", issue = "81513")]
201 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
202 #[inline]
203 pub const fn to_raw_parts(self) -> (NonNull<()>, <T as super::Pointee>::Metadata) {
204 (self.cast(), super::metadata(self.as_ptr()))
205 }
206
207 /// Acquires the underlying `*mut` pointer.
208 #[stable(feature = "nonnull", since = "1.25.0")]
209 #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
210 #[inline]
211 pub const fn as_ptr(self) -> *mut T {
212 self.pointer as *mut T
213 }
214
215 /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`]
216 /// must be used instead.
217 ///
218 /// For the mutable counterpart see [`as_mut`].
219 ///
220 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
221 /// [`as_mut`]: NonNull::as_mut
222 ///
223 /// # Safety
224 ///
225 /// When calling this method, you have to ensure that all of the following is true:
226 ///
227 /// * The pointer must be properly aligned.
228 ///
229 /// * It must be "dereferencable" in the sense defined in [the module documentation].
230 ///
231 /// * The pointer must point to an initialized instance of `T`.
232 ///
233 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
234 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
235 /// In particular, for the duration of this lifetime, the memory the pointer points to must
236 /// not get mutated (except inside `UnsafeCell`).
237 ///
238 /// This applies even if the result of this method is unused!
239 /// (The part about being initialized is not yet fully decided, but until
240 /// it is, the only safe approach is to ensure that they are indeed initialized.)
241 ///
242 /// [the module documentation]: crate::ptr#safety
243 #[stable(feature = "nonnull", since = "1.25.0")]
244 #[inline]
245 pub unsafe fn as_ref<'a>(&self) -> &'a T {
246 // SAFETY: the caller must guarantee that `self` meets all the
247 // requirements for a reference.
248 unsafe { &*self.as_ptr() }
249 }
250
251 /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
252 /// must be used instead.
253 ///
254 /// For the shared counterpart see [`as_ref`].
255 ///
256 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
257 /// [`as_ref`]: NonNull::as_ref
258 ///
259 /// # Safety
260 ///
261 /// When calling this method, you have to ensure that all of the following is true:
262 ///
263 /// * The pointer must be properly aligned.
264 ///
265 /// * It must be "dereferencable" in the sense defined in [the module documentation].
266 ///
267 /// * The pointer must point to an initialized instance of `T`.
268 ///
269 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
270 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
271 /// In particular, for the duration of this lifetime, the memory the pointer points to must
272 /// not get accessed (read or written) through any other pointer.
273 ///
274 /// This applies even if the result of this method is unused!
275 /// (The part about being initialized is not yet fully decided, but until
276 /// it is, the only safe approach is to ensure that they are indeed initialized.)
277 ///
278 /// [the module documentation]: crate::ptr#safety
279 #[stable(feature = "nonnull", since = "1.25.0")]
280 #[inline]
281 pub unsafe fn as_mut<'a>(&mut self) -> &'a mut T {
282 // SAFETY: the caller must guarantee that `self` meets all the
283 // requirements for a mutable reference.
284 unsafe { &mut *self.as_ptr() }
285 }
286
287 /// Casts to a pointer of another type.
288 #[stable(feature = "nonnull_cast", since = "1.27.0")]
289 #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.36.0")]
290 #[inline]
291 pub const fn cast<U>(self) -> NonNull<U> {
292 // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
293 unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) }
294 }
295 }
296
297 impl<T> NonNull<[T]> {
298 /// Creates a non-null raw slice from a thin pointer and a length.
299 ///
300 /// The `len` argument is the number of **elements**, not the number of bytes.
301 ///
302 /// This function is safe, but dereferencing the return value is unsafe.
303 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
304 ///
305 /// # Examples
306 ///
307 /// ```rust
308 /// #![feature(nonnull_slice_from_raw_parts)]
309 ///
310 /// use std::ptr::NonNull;
311 ///
312 /// // create a slice pointer when starting out with a pointer to the first element
313 /// let mut x = [5, 6, 7];
314 /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
315 /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
316 /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
317 /// ```
318 ///
319 /// (Note that this example artificially demonstrates a use of this method,
320 /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
321 #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
322 #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
323 #[inline]
324 pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
325 // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
326 unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
327 }
328
329 /// Returns the length of a non-null raw slice.
330 ///
331 /// The returned value is the number of **elements**, not the number of bytes.
332 ///
333 /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
334 /// because the pointer does not have a valid address.
335 ///
336 /// # Examples
337 ///
338 /// ```rust
339 /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
340 /// use std::ptr::NonNull;
341 ///
342 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
343 /// assert_eq!(slice.len(), 3);
344 /// ```
345 #[unstable(feature = "slice_ptr_len", issue = "71146")]
346 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
347 #[inline]
348 pub const fn len(self) -> usize {
349 self.as_ptr().len()
350 }
351
352 /// Returns a non-null pointer to the slice's buffer.
353 ///
354 /// # Examples
355 ///
356 /// ```rust
357 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
358 /// use std::ptr::NonNull;
359 ///
360 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
361 /// assert_eq!(slice.as_non_null_ptr(), NonNull::new(1 as *mut i8).unwrap());
362 /// ```
363 #[inline]
364 #[unstable(feature = "slice_ptr_get", issue = "74265")]
365 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
366 pub const fn as_non_null_ptr(self) -> NonNull<T> {
367 // SAFETY: We know `self` is non-null.
368 unsafe { NonNull::new_unchecked(self.as_ptr().as_mut_ptr()) }
369 }
370
371 /// Returns a raw pointer to the slice's buffer.
372 ///
373 /// # Examples
374 ///
375 /// ```rust
376 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
377 /// use std::ptr::NonNull;
378 ///
379 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
380 /// assert_eq!(slice.as_mut_ptr(), 1 as *mut i8);
381 /// ```
382 #[inline]
383 #[unstable(feature = "slice_ptr_get", issue = "74265")]
384 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
385 pub const fn as_mut_ptr(self) -> *mut T {
386 self.as_non_null_ptr().as_ptr()
387 }
388
389 /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to
390 /// [`as_ref`], this does not require that the value has to be initialized.
391 ///
392 /// For the mutable counterpart see [`as_uninit_slice_mut`].
393 ///
394 /// [`as_ref`]: NonNull::as_ref
395 /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
396 ///
397 /// # Safety
398 ///
399 /// When calling this method, you have to ensure that all of the following is true:
400 ///
401 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
402 /// and it must be properly aligned. This means in particular:
403 ///
404 /// * The entire memory range of this slice must be contained within a single allocated object!
405 /// Slices can never span across multiple allocated objects.
406 ///
407 /// * The pointer must be aligned even for zero-length slices. One
408 /// reason for this is that enum layout optimizations may rely on references
409 /// (including slices of any length) being aligned and non-null to distinguish
410 /// them from other data. You can obtain a pointer that is usable as `data`
411 /// for zero-length slices using [`NonNull::dangling()`].
412 ///
413 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
414 /// See the safety documentation of [`pointer::offset`].
415 ///
416 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
417 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
418 /// In particular, for the duration of this lifetime, the memory the pointer points to must
419 /// not get mutated (except inside `UnsafeCell`).
420 ///
421 /// This applies even if the result of this method is unused!
422 ///
423 /// See also [`slice::from_raw_parts`].
424 ///
425 /// [valid]: crate::ptr#safety
426 #[inline]
427 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
428 pub unsafe fn as_uninit_slice<'a>(&self) -> &'a [MaybeUninit<T>] {
429 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
430 unsafe { slice::from_raw_parts(self.cast().as_ptr(), self.len()) }
431 }
432
433 /// Returns a unique reference to a slice of possibly uninitialized values. In contrast to
434 /// [`as_mut`], this does not require that the value has to be initialized.
435 ///
436 /// For the shared counterpart see [`as_uninit_slice`].
437 ///
438 /// [`as_mut`]: NonNull::as_mut
439 /// [`as_uninit_slice`]: NonNull::as_uninit_slice
440 ///
441 /// # Safety
442 ///
443 /// When calling this method, you have to ensure that all of the following is true:
444 ///
445 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
446 /// many bytes, and it must be properly aligned. This means in particular:
447 ///
448 /// * The entire memory range of this slice must be contained within a single allocated object!
449 /// Slices can never span across multiple allocated objects.
450 ///
451 /// * The pointer must be aligned even for zero-length slices. One
452 /// reason for this is that enum layout optimizations may rely on references
453 /// (including slices of any length) being aligned and non-null to distinguish
454 /// them from other data. You can obtain a pointer that is usable as `data`
455 /// for zero-length slices using [`NonNull::dangling()`].
456 ///
457 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
458 /// See the safety documentation of [`pointer::offset`].
459 ///
460 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
461 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
462 /// In particular, for the duration of this lifetime, the memory the pointer points to must
463 /// not get accessed (read or written) through any other pointer.
464 ///
465 /// This applies even if the result of this method is unused!
466 ///
467 /// See also [`slice::from_raw_parts_mut`].
468 ///
469 /// [valid]: crate::ptr#safety
470 ///
471 /// # Examples
472 ///
473 /// ```rust
474 /// #![feature(allocator_api, ptr_as_uninit)]
475 ///
476 /// use std::alloc::{Allocator, Layout, Global};
477 /// use std::mem::MaybeUninit;
478 /// use std::ptr::NonNull;
479 ///
480 /// let memory: NonNull<[u8]> = Global.allocate(Layout::new::<[u8; 32]>())?;
481 /// // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes.
482 /// // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized.
483 /// # #[allow(unused_variables)]
484 /// let slice: &mut [MaybeUninit<u8>] = unsafe { memory.as_uninit_slice_mut() };
485 /// # Ok::<_, std::alloc::AllocError>(())
486 /// ```
487 #[inline]
488 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
489 pub unsafe fn as_uninit_slice_mut<'a>(&self) -> &'a mut [MaybeUninit<T>] {
490 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
491 unsafe { slice::from_raw_parts_mut(self.cast().as_ptr(), self.len()) }
492 }
493
494 /// Returns a raw pointer to an element or subslice, without doing bounds
495 /// checking.
496 ///
497 /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
498 /// is *[undefined behavior]* even if the resulting pointer is not used.
499 ///
500 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
501 ///
502 /// # Examples
503 ///
504 /// ```
505 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
506 /// use std::ptr::NonNull;
507 ///
508 /// let x = &mut [1, 2, 4];
509 /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
510 ///
511 /// unsafe {
512 /// assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
513 /// }
514 /// ```
515 #[unstable(feature = "slice_ptr_get", issue = "74265")]
516 #[inline]
517 pub unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
518 where
519 I: SliceIndex<[T]>,
520 {
521 // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
522 // As a consequence, the resulting pointer cannot be null.
523 unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
524 }
525 }
526
527 #[stable(feature = "nonnull", since = "1.25.0")]
528 impl<T: ?Sized> Clone for NonNull<T> {
529 #[inline]
530 fn clone(&self) -> Self {
531 *self
532 }
533 }
534
535 #[stable(feature = "nonnull", since = "1.25.0")]
536 impl<T: ?Sized> Copy for NonNull<T> {}
537
538 #[unstable(feature = "coerce_unsized", issue = "27732")]
539 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
540
541 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
542 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
543
544 #[stable(feature = "nonnull", since = "1.25.0")]
545 impl<T: ?Sized> fmt::Debug for NonNull<T> {
546 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
547 fmt::Pointer::fmt(&self.as_ptr(), f)
548 }
549 }
550
551 #[stable(feature = "nonnull", since = "1.25.0")]
552 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
553 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
554 fmt::Pointer::fmt(&self.as_ptr(), f)
555 }
556 }
557
558 #[stable(feature = "nonnull", since = "1.25.0")]
559 impl<T: ?Sized> Eq for NonNull<T> {}
560
561 #[stable(feature = "nonnull", since = "1.25.0")]
562 impl<T: ?Sized> PartialEq for NonNull<T> {
563 #[inline]
564 fn eq(&self, other: &Self) -> bool {
565 self.as_ptr() == other.as_ptr()
566 }
567 }
568
569 #[stable(feature = "nonnull", since = "1.25.0")]
570 impl<T: ?Sized> Ord for NonNull<T> {
571 #[inline]
572 fn cmp(&self, other: &Self) -> Ordering {
573 self.as_ptr().cmp(&other.as_ptr())
574 }
575 }
576
577 #[stable(feature = "nonnull", since = "1.25.0")]
578 impl<T: ?Sized> PartialOrd for NonNull<T> {
579 #[inline]
580 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
581 self.as_ptr().partial_cmp(&other.as_ptr())
582 }
583 }
584
585 #[stable(feature = "nonnull", since = "1.25.0")]
586 impl<T: ?Sized> hash::Hash for NonNull<T> {
587 #[inline]
588 fn hash<H: hash::Hasher>(&self, state: &mut H) {
589 self.as_ptr().hash(state)
590 }
591 }
592
593 #[unstable(feature = "ptr_internals", issue = "none")]
594 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
595 #[inline]
596 fn from(unique: Unique<T>) -> Self {
597 // SAFETY: A Unique pointer cannot be null, so the conditions for
598 // new_unchecked() are respected.
599 unsafe { NonNull::new_unchecked(unique.as_ptr()) }
600 }
601 }
602
603 #[stable(feature = "nonnull", since = "1.25.0")]
604 impl<T: ?Sized> From<&mut T> for NonNull<T> {
605 #[inline]
606 fn from(reference: &mut T) -> Self {
607 // SAFETY: A mutable reference cannot be null.
608 unsafe { NonNull { pointer: reference as *mut T } }
609 }
610 }
611
612 #[stable(feature = "nonnull", since = "1.25.0")]
613 impl<T: ?Sized> From<&T> for NonNull<T> {
614 #[inline]
615 fn from(reference: &T) -> Self {
616 // SAFETY: A reference cannot be null, so the conditions for
617 // new_unchecked() are respected.
618 unsafe { NonNull { pointer: reference as *const T } }
619 }
620 }