core/ptr/non_null.rs
1use crate::clone::TrivialClone;
2use crate::cmp::Ordering;
3use crate::marker::{Destruct, PointeeSized, Unsize};
4use crate::mem::{MaybeUninit, SizedTypeProperties, transmute};
5use crate::num::NonZero;
6use crate::ops::{CoerceUnsized, DispatchFromDyn};
7use crate::ptr::Unique;
8use crate::slice::{self, SliceIndex};
9use crate::ub_checks::assert_unsafe_precondition;
10use crate::{fmt, hash, intrinsics, mem, ptr};
11
12/// `*mut T` but non-zero and [covariant].
13///
14/// This is often the correct thing to use when building data structures using
15/// raw pointers, but is ultimately more dangerous to use because of its additional
16/// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
17///
18/// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
19/// is never dereferenced. This is so that enums may use this forbidden value
20/// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
21/// However the pointer may still dangle if it isn't dereferenced.
22///
23/// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. This is usually the correct
24/// choice for most data structures and safe abstractions, such as `Box`, `Rc`, `Arc`, `Vec`,
25/// and `LinkedList`.
26///
27/// In rare cases, if your type exposes a way to mutate the value of `T` through a `NonNull<T>`,
28/// and you need to prevent unsoundness from variance (for example, if `T` could be a reference
29/// with a shorter lifetime), you should add a field to make your type invariant, such as
30/// `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
31///
32/// Example of a type that must be invariant:
33/// ```rust
34/// use std::cell::Cell;
35/// use std::marker::PhantomData;
36/// struct Invariant<T> {
37/// ptr: std::ptr::NonNull<T>,
38/// _invariant: PhantomData<Cell<T>>,
39/// }
40/// ```
41///
42/// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
43/// not change the fact that mutating through a (pointer derived from a) shared
44/// reference is undefined behavior unless the mutation happens inside an
45/// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
46/// reference. When using this `From` instance without an `UnsafeCell<T>`,
47/// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
48/// is never used for mutation.
49///
50/// # Layout
51///
52/// `NonNull<T>` is guaranteed to have the same layout and bit validity as `*mut T`
53/// with the exception that a null pointer is invalid.
54/// `Option<NonNull<T>>` is guaranteed to be ABI-compatible with `*mut T`, including in
55/// FFI.
56///
57/// Thanks to the [null pointer optimization],
58/// `NonNull<T>` and `Option<NonNull<T>>`
59/// are guaranteed to have the same size and alignment:
60///
61/// ```
62/// use std::ptr::NonNull;
63///
64/// assert_eq!(size_of::<NonNull<i16>>(), size_of::<Option<NonNull<i16>>>());
65/// assert_eq!(align_of::<NonNull<i16>>(), align_of::<Option<NonNull<i16>>>());
66///
67/// assert_eq!(size_of::<NonNull<str>>(), size_of::<Option<NonNull<str>>>());
68/// assert_eq!(align_of::<NonNull<str>>(), align_of::<Option<NonNull<str>>>());
69/// ```
70///
71/// [covariant]: https://doc.rust-lang.org/reference/subtyping.html
72/// [`PhantomData`]: crate::marker::PhantomData
73/// [`UnsafeCell<T>`]: crate::cell::UnsafeCell
74/// [null pointer optimization]: crate::option#representation
75#[stable(feature = "nonnull", since = "1.25.0")]
76#[repr(transparent)]
77#[rustc_nonnull_optimization_guaranteed]
78#[lang = "non_null"]
79pub struct NonNull<T: PointeeSized> {
80 pointer: crate::pattern_type!(*const T is !null),
81}
82
83/// `NonNull` pointers are not `Send` because the data they reference may be aliased.
84// N.B., this impl is unnecessary, but should provide better error messages.
85#[stable(feature = "nonnull", since = "1.25.0")]
86impl<T: PointeeSized> !Send for NonNull<T> {}
87
88/// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
89// N.B., this impl is unnecessary, but should provide better error messages.
90#[stable(feature = "nonnull", since = "1.25.0")]
91impl<T: PointeeSized> !Sync for NonNull<T> {}
92
93impl<T: Sized> NonNull<T> {
94 /// Creates a pointer with the given address and no [provenance][crate::ptr#provenance].
95 ///
96 /// For more details, see the equivalent method on a raw pointer, [`ptr::without_provenance_mut`].
97 ///
98 /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
99 #[stable(feature = "nonnull_provenance", since = "1.89.0")]
100 #[rustc_const_stable(feature = "nonnull_provenance", since = "1.89.0")]
101 #[must_use]
102 #[inline]
103 pub const fn without_provenance(addr: NonZero<usize>) -> Self {
104 // SAFETY: we know `addr` is non-zero and all nonzero integers are valid raw pointers.
105 unsafe { transmute(addr) }
106 }
107
108 /// Creates a new `NonNull` that is dangling, but well-aligned.
109 ///
110 /// This is useful for initializing types which lazily allocate, like
111 /// `Vec::new` does.
112 ///
113 /// Note that the address of the returned pointer may potentially
114 /// be that of a valid pointer, which means this must not be used
115 /// as a "not yet initialized" sentinel value.
116 /// Types that lazily allocate must track initialization by some other means.
117 ///
118 /// # Examples
119 ///
120 /// ```
121 /// use std::ptr::NonNull;
122 ///
123 /// let ptr = NonNull::<u32>::dangling();
124 /// // Important: don't try to access the value of `ptr` without
125 /// // initializing it first! The pointer is not null but isn't valid either!
126 /// ```
127 #[stable(feature = "nonnull", since = "1.25.0")]
128 #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.36.0")]
129 #[must_use]
130 #[inline]
131 pub const fn dangling() -> Self {
132 let align = crate::mem::Alignment::of::<T>();
133 NonNull::without_provenance(align.as_nonzero_usize())
134 }
135
136 /// Converts an address back to a mutable pointer, picking up some previously 'exposed'
137 /// [provenance][crate::ptr#provenance].
138 ///
139 /// For more details, see the equivalent method on a raw pointer, [`ptr::with_exposed_provenance_mut`].
140 ///
141 /// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
142 #[stable(feature = "nonnull_provenance", since = "1.89.0")]
143 #[rustc_const_unstable(feature = "const_nonnull_with_exposed_provenance", issue = "154215")]
144 #[inline]
145 pub const fn with_exposed_provenance(addr: NonZero<usize>) -> Self {
146 // SAFETY: we know `addr` is non-zero.
147 unsafe {
148 let ptr = crate::ptr::with_exposed_provenance_mut(addr.get());
149 NonNull::new_unchecked(ptr)
150 }
151 }
152
153 /// Returns a shared references to the value. In contrast to [`as_ref`], this does not require
154 /// that the value has to be initialized.
155 ///
156 /// For the mutable counterpart see [`as_uninit_mut`].
157 ///
158 /// [`as_ref`]: NonNull::as_ref
159 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
160 ///
161 /// # Safety
162 ///
163 /// When calling this method, you have to ensure that
164 /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
165 /// Note that because the created reference is to `MaybeUninit<T>`, the
166 /// source pointer can point to uninitialized memory.
167 #[inline]
168 #[must_use]
169 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
170 pub const unsafe fn as_uninit_ref<'a>(self) -> &'a MaybeUninit<T> {
171 // SAFETY: the caller must guarantee that `self` meets all the
172 // requirements for a reference.
173 unsafe { &*self.cast().as_ptr() }
174 }
175
176 /// Returns a unique references to the value. In contrast to [`as_mut`], this does not require
177 /// that the value has to be initialized.
178 ///
179 /// For the shared counterpart see [`as_uninit_ref`].
180 ///
181 /// [`as_mut`]: NonNull::as_mut
182 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
183 ///
184 /// # Safety
185 ///
186 /// When calling this method, you have to ensure that
187 /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
188 /// Note that because the created reference is to `MaybeUninit<T>`, the
189 /// source pointer can point to uninitialized memory.
190 #[inline]
191 #[must_use]
192 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
193 pub const unsafe fn as_uninit_mut<'a>(self) -> &'a mut MaybeUninit<T> {
194 // SAFETY: the caller must guarantee that `self` meets all the
195 // requirements for a reference.
196 unsafe { &mut *self.cast().as_ptr() }
197 }
198
199 /// Casts from a pointer-to-`T` to a pointer-to-`[T; N]`.
200 #[inline]
201 #[unstable(feature = "ptr_cast_array", issue = "144514")]
202 pub const fn cast_array<const N: usize>(self) -> NonNull<[T; N]> {
203 self.cast()
204 }
205}
206
207impl<T: PointeeSized> NonNull<T> {
208 /// Creates a new `NonNull`.
209 ///
210 /// Note that if you have an `&mut`, you can use the safe [`from_mut`] instead.
211 ///
212 /// [`from_mut`]: NonNull::from_mut
213 ///
214 /// # Safety
215 ///
216 /// `ptr` must be non-null.
217 ///
218 /// # Examples
219 ///
220 /// ```
221 /// use std::ptr::NonNull;
222 ///
223 /// let mut x = 0u32;
224 /// let ptr = unsafe { NonNull::new_unchecked(&mut x as *mut _) };
225 /// ```
226 ///
227 /// *Incorrect* usage of this function:
228 ///
229 /// ```rust,no_run
230 /// use std::ptr::NonNull;
231 ///
232 /// // NEVER DO THAT!!! This is undefined behavior. ⚠️
233 /// let ptr = unsafe { NonNull::<u32>::new_unchecked(std::ptr::null_mut()) };
234 /// ```
235 #[stable(feature = "nonnull", since = "1.25.0")]
236 #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.25.0")]
237 #[inline]
238 #[track_caller]
239 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
240 // SAFETY: the caller must guarantee that `ptr` is non-null.
241 unsafe {
242 assert_unsafe_precondition!(
243 check_language_ub,
244 "NonNull::new_unchecked requires that the pointer is non-null",
245 (ptr: *mut () = ptr as *mut ()) => !ptr.is_null()
246 );
247 transmute(ptr)
248 }
249 }
250
251 /// Creates a new `NonNull` if `ptr` is non-null.
252 ///
253 /// Note that if you have an `&mut`, you can use [`from_mut`] instead to avoid the `Option`.
254 ///
255 /// [`from_mut`]: NonNull::from_mut
256 ///
257 /// # Panics during const evaluation
258 ///
259 /// This method will panic during const evaluation if the pointer cannot be
260 /// determined to be null or not. See [`is_null`] for more information.
261 ///
262 /// [`is_null`]: ../primitive.pointer.html#method.is_null-1
263 ///
264 /// # Examples
265 ///
266 /// ```
267 /// use std::ptr::NonNull;
268 ///
269 /// let mut x = 0u32;
270 /// let ptr = NonNull::<u32>::new(&mut x as *mut _).expect("pointer should not be null");
271 ///
272 /// if let Some(ptr) = NonNull::<u32>::new(std::ptr::null_mut()) {
273 /// unreachable!();
274 /// }
275 /// ```
276 #[stable(feature = "nonnull", since = "1.25.0")]
277 #[rustc_const_stable(feature = "const_nonnull_new", since = "1.85.0")]
278 #[inline]
279 pub const fn new(ptr: *mut T) -> Option<Self> {
280 if !ptr.is_null() {
281 // SAFETY: The pointer is already checked and is not null
282 Some(unsafe { Self::new_unchecked(ptr) })
283 } else {
284 None
285 }
286 }
287
288 /// Converts a reference to a `NonNull` pointer.
289 #[stable(feature = "non_null_from_ref", since = "1.89.0")]
290 #[rustc_const_stable(feature = "non_null_from_ref", since = "1.89.0")]
291 #[inline]
292 pub const fn from_ref(r: &T) -> Self {
293 // SAFETY: A reference cannot be null.
294 unsafe { transmute(r as *const T) }
295 }
296
297 /// Converts a mutable reference to a `NonNull` pointer.
298 #[stable(feature = "non_null_from_ref", since = "1.89.0")]
299 #[rustc_const_stable(feature = "non_null_from_ref", since = "1.89.0")]
300 #[inline]
301 pub const fn from_mut(r: &mut T) -> Self {
302 // SAFETY: A mutable reference cannot be null.
303 unsafe { transmute(r as *mut T) }
304 }
305
306 /// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a
307 /// `NonNull` pointer is returned, as opposed to a raw `*const` pointer.
308 ///
309 /// See the documentation of [`std::ptr::from_raw_parts`] for more details.
310 ///
311 /// [`std::ptr::from_raw_parts`]: crate::ptr::from_raw_parts
312 #[unstable(feature = "ptr_metadata", issue = "81513")]
313 #[inline]
314 pub const fn from_raw_parts(
315 data_pointer: NonNull<impl super::Thin>,
316 metadata: <T as super::Pointee>::Metadata,
317 ) -> NonNull<T> {
318 // SAFETY: The result of `ptr::from::raw_parts_mut` is non-null because `data_pointer` is.
319 unsafe {
320 NonNull::new_unchecked(super::from_raw_parts_mut(data_pointer.as_ptr(), metadata))
321 }
322 }
323
324 /// Decompose a (possibly wide) pointer into its data pointer and metadata components.
325 ///
326 /// The pointer can be later reconstructed with [`NonNull::from_raw_parts`].
327 #[unstable(feature = "ptr_metadata", issue = "81513")]
328 #[must_use = "this returns the result of the operation, \
329 without modifying the original"]
330 #[inline]
331 pub const fn to_raw_parts(self) -> (NonNull<()>, <T as super::Pointee>::Metadata) {
332 (self.cast(), super::metadata(self.as_ptr()))
333 }
334
335 /// Gets the "address" portion of the pointer.
336 ///
337 /// For more details, see the equivalent method on a raw pointer, [`pointer::addr`].
338 ///
339 /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
340 #[must_use]
341 #[inline]
342 #[stable(feature = "strict_provenance", since = "1.84.0")]
343 pub fn addr(self) -> NonZero<usize> {
344 // SAFETY: The pointer is guaranteed by the type to be non-null,
345 // meaning that the address will be non-zero.
346 unsafe { NonZero::new_unchecked(self.as_ptr().addr()) }
347 }
348
349 /// Exposes the ["provenance"][crate::ptr#provenance] part of the pointer for future use in
350 /// [`with_exposed_provenance`][NonNull::with_exposed_provenance] and returns the "address" portion.
351 ///
352 /// For more details, see the equivalent method on a raw pointer, [`pointer::expose_provenance`].
353 ///
354 /// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
355 #[stable(feature = "nonnull_provenance", since = "1.89.0")]
356 pub fn expose_provenance(self) -> NonZero<usize> {
357 // SAFETY: The pointer is guaranteed by the type to be non-null,
358 // meaning that the address will be non-zero.
359 unsafe { NonZero::new_unchecked(self.as_ptr().expose_provenance()) }
360 }
361
362 /// Creates a new pointer with the given address and the [provenance][crate::ptr#provenance] of
363 /// `self`.
364 ///
365 /// For more details, see the equivalent method on a raw pointer, [`pointer::with_addr`].
366 ///
367 /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
368 #[must_use]
369 #[inline]
370 #[stable(feature = "strict_provenance", since = "1.84.0")]
371 pub fn with_addr(self, addr: NonZero<usize>) -> Self {
372 // SAFETY: The result of `ptr::from::with_addr` is non-null because `addr` is guaranteed to be non-zero.
373 unsafe { NonNull::new_unchecked(self.as_ptr().with_addr(addr.get()) as *mut _) }
374 }
375
376 /// Creates a new pointer by mapping `self`'s address to a new one, preserving the
377 /// [provenance][crate::ptr#provenance] of `self`.
378 ///
379 /// For more details, see the equivalent method on a raw pointer, [`pointer::map_addr`].
380 ///
381 /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
382 #[must_use]
383 #[inline]
384 #[stable(feature = "strict_provenance", since = "1.84.0")]
385 pub fn map_addr(self, f: impl FnOnce(NonZero<usize>) -> NonZero<usize>) -> Self {
386 self.with_addr(f(self.addr()))
387 }
388
389 /// Acquires the underlying `*mut` pointer.
390 ///
391 /// # Examples
392 ///
393 /// ```
394 /// use std::ptr::NonNull;
395 ///
396 /// let mut x = 0u32;
397 /// let ptr = NonNull::from_mut(&mut x);
398 ///
399 /// let x_value = unsafe { *ptr.as_ptr() };
400 /// assert_eq!(x_value, 0);
401 ///
402 /// unsafe { *ptr.as_ptr() += 2; }
403 /// let x_value = unsafe { *ptr.as_ptr() };
404 /// assert_eq!(x_value, 2);
405 /// ```
406 #[stable(feature = "nonnull", since = "1.25.0")]
407 #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
408 #[rustc_never_returns_null_ptr]
409 #[must_use]
410 #[inline(always)]
411 pub const fn as_ptr(self) -> *mut T {
412 // This is a transmute for the same reasons as `NonZero::get`.
413
414 // SAFETY: `NonNull` is `transparent` over a `*const T`, and `*const T`
415 // and `*mut T` have the same layout, so transitively we can transmute
416 // our `NonNull` to a `*mut T` directly.
417 unsafe { mem::transmute::<Self, *mut T>(self) }
418 }
419
420 /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`]
421 /// must be used instead.
422 ///
423 /// For the mutable counterpart see [`as_mut`].
424 ///
425 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
426 /// [`as_mut`]: NonNull::as_mut
427 ///
428 /// # Safety
429 ///
430 /// When calling this method, you have to ensure that
431 /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
432 ///
433 /// # Examples
434 ///
435 /// ```
436 /// use std::ptr::NonNull;
437 ///
438 /// let mut x = 0u32;
439 /// let ptr = NonNull::from_mut(&mut x);
440 ///
441 /// let ref_x = unsafe { ptr.as_ref() };
442 /// println!("{ref_x}");
443 /// ```
444 ///
445 /// [the module documentation]: crate::ptr#safety
446 #[stable(feature = "nonnull", since = "1.25.0")]
447 #[rustc_const_stable(feature = "const_nonnull_as_ref", since = "1.73.0")]
448 #[must_use]
449 #[inline(always)]
450 pub const unsafe fn as_ref<'a>(&self) -> &'a T {
451 // SAFETY: the caller must guarantee that `self` meets all the
452 // requirements for a reference.
453 // `cast_const` avoids a mutable raw pointer deref.
454 unsafe { &*self.as_ptr().cast_const() }
455 }
456
457 /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
458 /// must be used instead.
459 ///
460 /// For the shared counterpart see [`as_ref`].
461 ///
462 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
463 /// [`as_ref`]: NonNull::as_ref
464 ///
465 /// # Safety
466 ///
467 /// When calling this method, you have to ensure that
468 /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
469 /// # Examples
470 ///
471 /// ```
472 /// use std::ptr::NonNull;
473 ///
474 /// let mut x = 0u32;
475 /// let mut ptr = NonNull::from_mut(&mut x);
476 ///
477 /// let x_ref = unsafe { ptr.as_mut() };
478 /// assert_eq!(*x_ref, 0);
479 /// *x_ref += 2;
480 /// assert_eq!(*x_ref, 2);
481 /// ```
482 ///
483 /// [the module documentation]: crate::ptr#safety
484 #[stable(feature = "nonnull", since = "1.25.0")]
485 #[rustc_const_stable(feature = "const_ptr_as_ref", since = "1.83.0")]
486 #[must_use]
487 #[inline(always)]
488 pub const unsafe fn as_mut<'a>(&mut self) -> &'a mut T {
489 // SAFETY: the caller must guarantee that `self` meets all the
490 // requirements for a mutable reference.
491 unsafe { &mut *self.as_ptr() }
492 }
493
494 /// Casts to a pointer of another type.
495 ///
496 /// # Examples
497 ///
498 /// ```
499 /// use std::ptr::NonNull;
500 ///
501 /// let mut x = 0u32;
502 /// let ptr = NonNull::from_mut(&mut x);
503 ///
504 /// let casted_ptr = ptr.cast::<i8>();
505 /// let raw_ptr: *mut i8 = casted_ptr.as_ptr();
506 /// ```
507 #[stable(feature = "nonnull_cast", since = "1.27.0")]
508 #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.36.0")]
509 #[must_use = "this returns the result of the operation, \
510 without modifying the original"]
511 #[inline]
512 pub const fn cast<U>(self) -> NonNull<U> {
513 // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
514 unsafe { transmute(self.as_ptr() as *mut U) }
515 }
516
517 /// Try to cast to a pointer of another type by checking alignment.
518 ///
519 /// If the pointer is properly aligned to the target type, it will be
520 /// cast to the target type. Otherwise, `None` is returned.
521 ///
522 /// # Examples
523 ///
524 /// ```rust
525 /// use std::ptr::NonNull;
526 ///
527 /// let mut x = 0u64;
528 ///
529 /// let aligned = NonNull::from_mut(&mut x);
530 /// let unaligned = unsafe { aligned.byte_add(1) };
531 ///
532 /// assert!(aligned.try_cast_aligned::<u32>().is_some());
533 /// assert!(unaligned.try_cast_aligned::<u32>().is_none());
534 /// ```
535 #[stable(feature = "pointer_try_cast_aligned", since = "CURRENT_RUSTC_VERSION")]
536 #[must_use = "this returns the result of the operation, \
537 without modifying the original"]
538 #[inline]
539 pub fn try_cast_aligned<U>(self) -> Option<NonNull<U>> {
540 if self.is_aligned_to(align_of::<U>()) { Some(self.cast()) } else { None }
541 }
542
543 #[doc = include_str!("./docs/offset.md")]
544 ///
545 /// # Examples
546 ///
547 /// ```
548 /// use std::ptr::NonNull;
549 ///
550 /// let mut s = [1, 2, 3];
551 /// let ptr: NonNull<u32> = NonNull::new(s.as_mut_ptr()).unwrap();
552 ///
553 /// unsafe {
554 /// println!("{}", ptr.offset(1).read());
555 /// println!("{}", ptr.offset(2).read());
556 /// }
557 /// ```
558 #[inline(always)]
559 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
560 #[must_use = "returns a new pointer rather than modifying its argument"]
561 #[stable(feature = "non_null_convenience", since = "1.80.0")]
562 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
563 pub const unsafe fn offset(self, count: isize) -> Self
564 where
565 T: Sized,
566 {
567 // SAFETY: the caller must uphold the safety contract for `offset`.
568 // Additionally safety contract of `offset` guarantees that the resulting pointer is
569 // pointing to an allocation, there can't be an allocation at null, thus it's safe to
570 // construct `NonNull`.
571 unsafe { transmute(intrinsics::offset(self.as_ptr(), count)) }
572 }
573
574 /// Calculates the offset from a pointer in bytes.
575 ///
576 /// `count` is in units of **bytes**.
577 ///
578 /// This is purely a convenience for casting to a `u8` pointer and
579 /// using [offset][pointer::offset] on it. See that method for documentation
580 /// and safety requirements.
581 ///
582 /// For non-`Sized` pointees this operation changes only the data pointer,
583 /// leaving the metadata untouched.
584 #[must_use]
585 #[inline(always)]
586 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
587 #[stable(feature = "non_null_convenience", since = "1.80.0")]
588 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
589 pub const unsafe fn byte_offset(self, count: isize) -> Self {
590 // SAFETY: the caller must uphold the safety contract for `offset` and `byte_offset` has
591 // the same safety contract.
592 // Additionally safety contract of `offset` guarantees that the resulting pointer is
593 // pointing to an allocation, there can't be an allocation at null, thus it's safe to
594 // construct `NonNull`.
595 unsafe { transmute(self.as_ptr().byte_offset(count)) }
596 }
597
598 #[doc = include_str!("./docs/add.md")]
599 ///
600 /// # Examples
601 ///
602 /// ```
603 /// use std::ptr::NonNull;
604 ///
605 /// let s: &str = "123";
606 /// let ptr: NonNull<u8> = NonNull::new(s.as_ptr().cast_mut()).unwrap();
607 ///
608 /// unsafe {
609 /// println!("{}", ptr.add(1).read() as char);
610 /// println!("{}", ptr.add(2).read() as char);
611 /// }
612 /// ```
613 #[inline(always)]
614 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
615 #[must_use = "returns a new pointer rather than modifying its argument"]
616 #[stable(feature = "non_null_convenience", since = "1.80.0")]
617 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
618 pub const unsafe fn add(self, count: usize) -> Self
619 where
620 T: Sized,
621 {
622 // SAFETY: the caller must uphold the safety contract for `offset`.
623 // Additionally safety contract of `offset` guarantees that the resulting pointer is
624 // pointing to an allocation, there can't be an allocation at null, thus it's safe to
625 // construct `NonNull`.
626 unsafe { transmute(intrinsics::offset(self.as_ptr(), count)) }
627 }
628
629 /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
630 ///
631 /// `count` is in units of bytes.
632 ///
633 /// This is purely a convenience for casting to a `u8` pointer and
634 /// using [`add`][NonNull::add] on it. See that method for documentation
635 /// and safety requirements.
636 ///
637 /// For non-`Sized` pointees this operation changes only the data pointer,
638 /// leaving the metadata untouched.
639 #[must_use]
640 #[inline(always)]
641 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
642 #[stable(feature = "non_null_convenience", since = "1.80.0")]
643 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
644 pub const unsafe fn byte_add(self, count: usize) -> Self {
645 // SAFETY: the caller must uphold the safety contract for `add` and `byte_add` has the same
646 // safety contract.
647 // Additionally safety contract of `add` guarantees that the resulting pointer is pointing
648 // to an allocation, there can't be an allocation at null, thus it's safe to construct
649 // `NonNull`.
650 unsafe { transmute(self.as_ptr().byte_add(count)) }
651 }
652
653 #[doc = include_str!("./docs/sub.md")]
654 ///
655 /// # Examples
656 ///
657 /// ```
658 /// use std::ptr::NonNull;
659 ///
660 /// let s: &str = "123";
661 ///
662 /// unsafe {
663 /// let end: NonNull<u8> = NonNull::new(s.as_ptr().cast_mut()).unwrap().add(3);
664 /// println!("{}", end.sub(1).read() as char);
665 /// println!("{}", end.sub(2).read() as char);
666 /// }
667 /// ```
668 #[inline(always)]
669 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
670 #[must_use = "returns a new pointer rather than modifying its argument"]
671 #[stable(feature = "non_null_convenience", since = "1.80.0")]
672 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
673 pub const unsafe fn sub(self, count: usize) -> Self
674 where
675 T: Sized,
676 {
677 if T::IS_ZST {
678 // Pointer arithmetic does nothing when the pointee is a ZST.
679 self
680 } else {
681 // SAFETY: the caller must uphold the safety contract for `offset`.
682 // Because the pointee is *not* a ZST, that means that `count` is
683 // at most `isize::MAX`, and thus the negation cannot overflow.
684 unsafe { self.offset((count as isize).unchecked_neg()) }
685 }
686 }
687
688 /// Calculates the offset from a pointer in bytes (convenience for
689 /// `.byte_offset((count as isize).wrapping_neg())`).
690 ///
691 /// `count` is in units of bytes.
692 ///
693 /// This is purely a convenience for casting to a `u8` pointer and
694 /// using [`sub`][NonNull::sub] on it. See that method for documentation
695 /// and safety requirements.
696 ///
697 /// For non-`Sized` pointees this operation changes only the data pointer,
698 /// leaving the metadata untouched.
699 #[must_use]
700 #[inline(always)]
701 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
702 #[stable(feature = "non_null_convenience", since = "1.80.0")]
703 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
704 pub const unsafe fn byte_sub(self, count: usize) -> Self {
705 // SAFETY: the caller must uphold the safety contract for `sub` and `byte_sub` has the same
706 // safety contract.
707 // Additionally safety contract of `sub` guarantees that the resulting pointer is pointing
708 // to an allocation, there can't be an allocation at null, thus it's safe to construct
709 // `NonNull`.
710 unsafe { transmute(self.as_ptr().byte_sub(count)) }
711 }
712
713 /// Calculates the distance between two pointers within the same allocation. The returned value is in
714 /// units of T: the distance in bytes divided by `size_of::<T>()`.
715 ///
716 /// This is equivalent to `(self as isize - origin as isize) / (size_of::<T>() as isize)`,
717 /// except that it has a lot more opportunities for UB, in exchange for the compiler
718 /// better understanding what you are doing.
719 ///
720 /// The primary motivation of this method is for computing the `len` of an array/slice
721 /// of `T` that you are currently representing as a "start" and "end" pointer
722 /// (and "end" is "one past the end" of the array).
723 /// In that case, `end.offset_from(start)` gets you the length of the array.
724 ///
725 /// All of the following safety requirements are trivially satisfied for this usecase.
726 ///
727 /// [`offset`]: #method.offset
728 ///
729 /// # Safety
730 ///
731 /// If any of the following conditions are violated, the result is Undefined Behavior:
732 ///
733 /// * `self` and `origin` must either
734 ///
735 /// * point to the same address, or
736 /// * both be *derived from* a pointer to the same [allocation], and the memory range between
737 /// the two pointers must be in bounds of that object. (See below for an example.)
738 ///
739 /// * The distance between the pointers, in bytes, must be an exact multiple
740 /// of the size of `T`.
741 ///
742 /// As a consequence, the absolute distance between the pointers, in bytes, computed on
743 /// mathematical integers (without "wrapping around"), cannot overflow an `isize`. This is
744 /// implied by the in-bounds requirement, and the fact that no allocation can be larger
745 /// than `isize::MAX` bytes.
746 ///
747 /// The requirement for pointers to be derived from the same allocation is primarily
748 /// needed for `const`-compatibility: the distance between pointers into *different* allocated
749 /// objects is not known at compile-time. However, the requirement also exists at
750 /// runtime and may be exploited by optimizations. If you wish to compute the difference between
751 /// pointers that are not guaranteed to be from the same allocation, use
752 /// `(self.addr() as isize - origin.addr() as isize) / size_of::<T>()`.
753 ///
754 /// [`add`]: #method.add
755 /// [allocation]: crate::ptr#allocation
756 ///
757 /// # Panics
758 ///
759 /// This function panics if `T` is a Zero-Sized Type ("ZST").
760 ///
761 /// # Examples
762 ///
763 /// Basic usage:
764 ///
765 /// ```
766 /// use std::ptr::NonNull;
767 ///
768 /// let a = [0; 5];
769 /// let ptr1: NonNull<u32> = NonNull::from(&a[1]);
770 /// let ptr2: NonNull<u32> = NonNull::from(&a[3]);
771 /// unsafe {
772 /// assert_eq!(ptr2.offset_from(ptr1), 2);
773 /// assert_eq!(ptr1.offset_from(ptr2), -2);
774 /// assert_eq!(ptr1.offset(2), ptr2);
775 /// assert_eq!(ptr2.offset(-2), ptr1);
776 /// }
777 /// ```
778 ///
779 /// *Incorrect* usage:
780 ///
781 /// ```rust,no_run
782 /// use std::ptr::NonNull;
783 ///
784 /// let ptr1 = NonNull::new(Box::into_raw(Box::new(0u8))).unwrap();
785 /// let ptr2 = NonNull::new(Box::into_raw(Box::new(1u8))).unwrap();
786 /// let diff = (ptr2.addr().get() as isize).wrapping_sub(ptr1.addr().get() as isize);
787 /// // Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.
788 /// let diff_plus_1 = diff.wrapping_add(1);
789 /// let ptr2_other = NonNull::new(ptr1.as_ptr().wrapping_byte_offset(diff_plus_1)).unwrap();
790 /// assert_eq!(ptr2.addr(), ptr2_other.addr());
791 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
792 /// // computing their offset is undefined behavior, even though
793 /// // they point to addresses that are in-bounds of the same object!
794 ///
795 /// let one = unsafe { ptr2_other.offset_from(ptr2) }; // Undefined Behavior! ⚠️
796 /// ```
797 #[inline]
798 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
799 #[stable(feature = "non_null_convenience", since = "1.80.0")]
800 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
801 pub const unsafe fn offset_from(self, origin: NonNull<T>) -> isize
802 where
803 T: Sized,
804 {
805 // SAFETY: the caller must uphold the safety contract for `offset_from`.
806 unsafe { self.as_ptr().offset_from(origin.as_ptr()) }
807 }
808
809 /// Calculates the distance between two pointers within the same allocation. The returned value is in
810 /// units of **bytes**.
811 ///
812 /// This is purely a convenience for casting to a `u8` pointer and
813 /// using [`offset_from`][NonNull::offset_from] on it. See that method for
814 /// documentation and safety requirements.
815 ///
816 /// For non-`Sized` pointees this operation considers only the data pointers,
817 /// ignoring the metadata.
818 #[inline(always)]
819 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
820 #[stable(feature = "non_null_convenience", since = "1.80.0")]
821 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
822 pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: NonNull<U>) -> isize {
823 // SAFETY: the caller must uphold the safety contract for `byte_offset_from`.
824 unsafe { self.as_ptr().byte_offset_from(origin.as_ptr()) }
825 }
826
827 // N.B. `wrapping_offset``, `wrapping_add`, etc are not implemented because they can wrap to null
828
829 /// Calculates the distance between two pointers within the same allocation, *where it's known that
830 /// `self` is equal to or greater than `origin`*. The returned value is in
831 /// units of T: the distance in bytes is divided by `size_of::<T>()`.
832 ///
833 /// This computes the same value that [`offset_from`](#method.offset_from)
834 /// would compute, but with the added precondition that the offset is
835 /// guaranteed to be non-negative. This method is equivalent to
836 /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`,
837 /// but it provides slightly more information to the optimizer, which can
838 /// sometimes allow it to optimize slightly better with some backends.
839 ///
840 /// This method can be though of as recovering the `count` that was passed
841 /// to [`add`](#method.add) (or, with the parameters in the other order,
842 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
843 /// that their safety preconditions are met:
844 /// ```rust
845 /// # unsafe fn blah(ptr: std::ptr::NonNull<u32>, origin: std::ptr::NonNull<u32>, count: usize) -> bool { unsafe {
846 /// ptr.offset_from_unsigned(origin) == count
847 /// # &&
848 /// origin.add(count) == ptr
849 /// # &&
850 /// ptr.sub(count) == origin
851 /// # } }
852 /// ```
853 ///
854 /// # Safety
855 ///
856 /// - The distance between the pointers must be non-negative (`self >= origin`)
857 ///
858 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
859 /// apply to this method as well; see it for the full details.
860 ///
861 /// Importantly, despite the return type of this method being able to represent
862 /// a larger offset, it's still *not permitted* to pass pointers which differ
863 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
864 /// always be less than or equal to `isize::MAX as usize`.
865 ///
866 /// # Panics
867 ///
868 /// This function panics if `T` is a Zero-Sized Type ("ZST").
869 ///
870 /// # Examples
871 ///
872 /// ```
873 /// use std::ptr::NonNull;
874 ///
875 /// let a = [0; 5];
876 /// let ptr1: NonNull<u32> = NonNull::from(&a[1]);
877 /// let ptr2: NonNull<u32> = NonNull::from(&a[3]);
878 /// unsafe {
879 /// assert_eq!(ptr2.offset_from_unsigned(ptr1), 2);
880 /// assert_eq!(ptr1.add(2), ptr2);
881 /// assert_eq!(ptr2.sub(2), ptr1);
882 /// assert_eq!(ptr2.offset_from_unsigned(ptr2), 0);
883 /// }
884 ///
885 /// // This would be incorrect, as the pointers are not correctly ordered:
886 /// // ptr1.offset_from_unsigned(ptr2)
887 /// ```
888 #[inline]
889 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
890 #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
891 #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
892 pub const unsafe fn offset_from_unsigned(self, subtracted: NonNull<T>) -> usize
893 where
894 T: Sized,
895 {
896 // SAFETY: the caller must uphold the safety contract for `offset_from_unsigned`.
897 unsafe { self.as_ptr().offset_from_unsigned(subtracted.as_ptr()) }
898 }
899
900 /// Calculates the distance between two pointers within the same allocation, *where it's known that
901 /// `self` is equal to or greater than `origin`*. The returned value is in
902 /// units of **bytes**.
903 ///
904 /// This is purely a convenience for casting to a `u8` pointer and
905 /// using [`offset_from_unsigned`][NonNull::offset_from_unsigned] on it.
906 /// See that method for documentation and safety requirements.
907 ///
908 /// For non-`Sized` pointees this operation considers only the data pointers,
909 /// ignoring the metadata.
910 #[inline(always)]
911 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
912 #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
913 #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
914 pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: NonNull<U>) -> usize {
915 // SAFETY: the caller must uphold the safety contract for `byte_offset_from_unsigned`.
916 unsafe { self.as_ptr().byte_offset_from_unsigned(origin.as_ptr()) }
917 }
918
919 /// Reads the value from `self` without moving it. This leaves the
920 /// memory in `self` unchanged.
921 ///
922 /// See [`ptr::read`] for safety concerns and examples.
923 ///
924 /// [`ptr::read`]: crate::ptr::read()
925 #[inline]
926 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
927 #[stable(feature = "non_null_convenience", since = "1.80.0")]
928 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
929 pub const unsafe fn read(self) -> T
930 where
931 T: Sized,
932 {
933 // SAFETY: the caller must uphold the safety contract for `read`.
934 unsafe { ptr::read(self.as_ptr()) }
935 }
936
937 /// Performs a volatile read of the value from `self` without moving it. This
938 /// leaves the memory in `self` unchanged.
939 ///
940 /// Volatile operations are intended to act on I/O memory, and are guaranteed
941 /// to not be elided or reordered by the compiler across other volatile
942 /// operations.
943 ///
944 /// See [`ptr::read_volatile`] for safety concerns and examples.
945 ///
946 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
947 #[inline]
948 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
949 #[stable(feature = "non_null_convenience", since = "1.80.0")]
950 #[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
951 pub const unsafe fn read_volatile(self) -> T
952 where
953 T: Sized,
954 {
955 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
956 unsafe { ptr::read_volatile(self.as_ptr()) }
957 }
958
959 /// Reads the value from `self` without moving it. This leaves the
960 /// memory in `self` unchanged.
961 ///
962 /// Unlike `read`, the pointer may be unaligned.
963 ///
964 /// See [`ptr::read_unaligned`] for safety concerns and examples.
965 ///
966 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
967 #[inline]
968 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
969 #[stable(feature = "non_null_convenience", since = "1.80.0")]
970 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
971 pub const unsafe fn read_unaligned(self) -> T
972 where
973 T: Sized,
974 {
975 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
976 unsafe { ptr::read_unaligned(self.as_ptr()) }
977 }
978
979 /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
980 /// and destination may overlap.
981 ///
982 /// NOTE: this has the *same* argument order as [`ptr::copy`].
983 ///
984 /// See [`ptr::copy`] for safety concerns and examples.
985 ///
986 /// [`ptr::copy`]: crate::ptr::copy()
987 #[inline(always)]
988 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
989 #[stable(feature = "non_null_convenience", since = "1.80.0")]
990 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
991 pub const unsafe fn copy_to(self, dest: NonNull<T>, count: usize)
992 where
993 T: Sized,
994 {
995 // SAFETY: the caller must uphold the safety contract for `copy`.
996 unsafe { ptr::copy(self.as_ptr(), dest.as_ptr(), count) }
997 }
998
999 /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1000 /// and destination may *not* overlap.
1001 ///
1002 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1003 ///
1004 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1005 ///
1006 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1007 #[inline(always)]
1008 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1009 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1010 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1011 pub const unsafe fn copy_to_nonoverlapping(self, dest: NonNull<T>, count: usize)
1012 where
1013 T: Sized,
1014 {
1015 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1016 unsafe { ptr::copy_nonoverlapping(self.as_ptr(), dest.as_ptr(), count) }
1017 }
1018
1019 /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
1020 /// and destination may overlap.
1021 ///
1022 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1023 ///
1024 /// See [`ptr::copy`] for safety concerns and examples.
1025 ///
1026 /// [`ptr::copy`]: crate::ptr::copy()
1027 #[inline(always)]
1028 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1029 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1030 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1031 pub const unsafe fn copy_from(self, src: NonNull<T>, count: usize)
1032 where
1033 T: Sized,
1034 {
1035 // SAFETY: the caller must uphold the safety contract for `copy`.
1036 unsafe { ptr::copy(src.as_ptr(), self.as_ptr(), count) }
1037 }
1038
1039 /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
1040 /// and destination may *not* overlap.
1041 ///
1042 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1043 ///
1044 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1045 ///
1046 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1047 #[inline(always)]
1048 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1049 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1050 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1051 pub const unsafe fn copy_from_nonoverlapping(self, src: NonNull<T>, count: usize)
1052 where
1053 T: Sized,
1054 {
1055 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1056 unsafe { ptr::copy_nonoverlapping(src.as_ptr(), self.as_ptr(), count) }
1057 }
1058
1059 /// Executes the destructor (if any) of the pointed-to value.
1060 ///
1061 /// See [`ptr::drop_in_place`] for safety concerns and examples.
1062 ///
1063 /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1064 #[inline(always)]
1065 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1066 #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
1067 pub const unsafe fn drop_in_place(mut self)
1068 where
1069 T: [const] Destruct,
1070 {
1071 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1072 unsafe { ptr::drop_glue(self.as_mut()) }
1073 }
1074
1075 /// Overwrites a memory location with the given value without reading or
1076 /// dropping the old value.
1077 ///
1078 /// See [`ptr::write`] for safety concerns and examples.
1079 ///
1080 /// [`ptr::write`]: crate::ptr::write()
1081 #[inline(always)]
1082 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1083 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1084 #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1085 pub const unsafe fn write(self, val: T)
1086 where
1087 T: Sized,
1088 {
1089 // SAFETY: the caller must uphold the safety contract for `write`.
1090 unsafe { ptr::write(self.as_ptr(), val) }
1091 }
1092
1093 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1094 /// bytes of memory starting at `self` to `val`.
1095 ///
1096 /// See [`ptr::write_bytes`] for safety concerns and examples.
1097 ///
1098 /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1099 #[inline(always)]
1100 #[doc(alias = "memset")]
1101 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1102 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1103 #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1104 pub const unsafe fn write_bytes(self, val: u8, count: usize)
1105 where
1106 T: Sized,
1107 {
1108 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1109 unsafe { ptr::write_bytes(self.as_ptr(), val, count) }
1110 }
1111
1112 /// Performs a volatile write of a memory location with the given value without
1113 /// reading or dropping the old value.
1114 ///
1115 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1116 /// to not be elided or reordered by the compiler across other volatile
1117 /// operations.
1118 ///
1119 /// See [`ptr::write_volatile`] for safety concerns and examples.
1120 ///
1121 /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1122 #[inline(always)]
1123 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1124 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1125 #[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
1126 pub const unsafe fn write_volatile(self, val: T)
1127 where
1128 T: Sized,
1129 {
1130 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1131 unsafe { ptr::write_volatile(self.as_ptr(), val) }
1132 }
1133
1134 /// Overwrites a memory location with the given value without reading or
1135 /// dropping the old value.
1136 ///
1137 /// Unlike `write`, the pointer may be unaligned.
1138 ///
1139 /// See [`ptr::write_unaligned`] for safety concerns and examples.
1140 ///
1141 /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1142 #[inline(always)]
1143 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1144 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1145 #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1146 pub const unsafe fn write_unaligned(self, val: T)
1147 where
1148 T: Sized,
1149 {
1150 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1151 unsafe { ptr::write_unaligned(self.as_ptr(), val) }
1152 }
1153
1154 /// Replaces the value at `self` with `src`, returning the old
1155 /// value, without dropping either.
1156 ///
1157 /// See [`ptr::replace`] for safety concerns and examples.
1158 ///
1159 /// [`ptr::replace`]: crate::ptr::replace()
1160 #[inline(always)]
1161 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1162 #[rustc_const_stable(feature = "const_inherent_ptr_replace", since = "1.88.0")]
1163 pub const unsafe fn replace(self, src: T) -> T
1164 where
1165 T: Sized,
1166 {
1167 // SAFETY: the caller must uphold the safety contract for `replace`.
1168 unsafe { ptr::replace(self.as_ptr(), src) }
1169 }
1170
1171 /// Swaps the values at two mutable locations of the same type, without
1172 /// deinitializing either. They may overlap, unlike `mem::swap` which is
1173 /// otherwise equivalent.
1174 ///
1175 /// See [`ptr::swap`] for safety concerns and examples.
1176 ///
1177 /// [`ptr::swap`]: crate::ptr::swap()
1178 #[inline(always)]
1179 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1180 #[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
1181 pub const unsafe fn swap(self, with: NonNull<T>)
1182 where
1183 T: Sized,
1184 {
1185 // SAFETY: the caller must uphold the safety contract for `swap`.
1186 unsafe { ptr::swap(self.as_ptr(), with.as_ptr()) }
1187 }
1188
1189 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1190 /// `align`.
1191 ///
1192 /// If it is not possible to align the pointer, the implementation returns
1193 /// `usize::MAX`.
1194 ///
1195 /// The offset is expressed in number of `T` elements, and not bytes.
1196 ///
1197 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1198 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1199 /// the returned offset is correct in all terms other than alignment.
1200 ///
1201 /// When this is called during compile-time evaluation (which is unstable), the implementation
1202 /// may return `usize::MAX` in cases where that can never happen at runtime. This is because the
1203 /// actual alignment of pointers is not known yet during compile-time, so an offset with
1204 /// guaranteed alignment can sometimes not be computed. For example, a buffer declared as `[u8;
1205 /// N]` might be allocated at an odd or an even address, but at compile-time this is not yet
1206 /// known, so the execution has to be correct for either choice. It is therefore impossible to
1207 /// find an offset that is guaranteed to be 2-aligned. (This behavior is subject to change, as usual
1208 /// for unstable APIs.)
1209 ///
1210 /// # Panics
1211 ///
1212 /// The function panics if `align` is not a power-of-two.
1213 ///
1214 /// # Examples
1215 ///
1216 /// Accessing adjacent `u8` as `u16`
1217 ///
1218 /// ```
1219 /// use std::ptr::NonNull;
1220 ///
1221 /// # unsafe {
1222 /// let x = [5_u8, 6, 7, 8, 9];
1223 /// let ptr = NonNull::new(x.as_ptr() as *mut u8).unwrap();
1224 /// let offset = ptr.align_offset(align_of::<u16>());
1225 ///
1226 /// if offset < x.len() - 1 {
1227 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1228 /// assert!(u16_ptr.read() == u16::from_ne_bytes([5, 6]) || u16_ptr.read() == u16::from_ne_bytes([6, 7]));
1229 /// } else {
1230 /// // while the pointer can be aligned via `offset`, it would point
1231 /// // outside the allocation
1232 /// }
1233 /// # }
1234 /// ```
1235 #[inline]
1236 #[must_use]
1237 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1238 pub fn align_offset(self, align: usize) -> usize
1239 where
1240 T: Sized,
1241 {
1242 if !align.is_power_of_two() {
1243 panic!("align_offset: align is not a power-of-two");
1244 }
1245
1246 {
1247 // SAFETY: `align` has been checked to be a power of 2 above.
1248 unsafe { ptr::align_offset(self.as_ptr(), align) }
1249 }
1250 }
1251
1252 /// Returns whether the pointer is properly aligned for `T`.
1253 ///
1254 /// # Examples
1255 ///
1256 /// ```
1257 /// use std::ptr::NonNull;
1258 ///
1259 /// // On some platforms, the alignment of i32 is less than 4.
1260 /// #[repr(align(4))]
1261 /// struct AlignedI32(i32);
1262 ///
1263 /// let data = AlignedI32(42);
1264 /// let ptr = NonNull::<AlignedI32>::from(&data);
1265 ///
1266 /// assert!(ptr.is_aligned());
1267 /// assert!(!NonNull::new(ptr.as_ptr().wrapping_byte_add(1)).unwrap().is_aligned());
1268 /// ```
1269 #[inline]
1270 #[must_use]
1271 #[stable(feature = "pointer_is_aligned", since = "1.79.0")]
1272 pub fn is_aligned(self) -> bool
1273 where
1274 T: Sized,
1275 {
1276 self.as_ptr().is_aligned()
1277 }
1278
1279 /// Returns whether the pointer is aligned to `align`.
1280 ///
1281 /// For non-`Sized` pointees this operation considers only the data pointer,
1282 /// ignoring the metadata.
1283 ///
1284 /// # Panics
1285 ///
1286 /// The function panics if `align` is not a power-of-two (this includes 0).
1287 ///
1288 /// # Examples
1289 ///
1290 /// ```
1291 /// #![feature(pointer_is_aligned_to)]
1292 ///
1293 /// // On some platforms, the alignment of i32 is less than 4.
1294 /// #[repr(align(4))]
1295 /// struct AlignedI32(i32);
1296 ///
1297 /// let data = AlignedI32(42);
1298 /// let ptr = &data as *const AlignedI32;
1299 ///
1300 /// assert!(ptr.is_aligned_to(1));
1301 /// assert!(ptr.is_aligned_to(2));
1302 /// assert!(ptr.is_aligned_to(4));
1303 ///
1304 /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1305 /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1306 ///
1307 /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1308 /// ```
1309 #[inline]
1310 #[must_use]
1311 #[unstable(feature = "pointer_is_aligned_to", issue = "96284")]
1312 pub fn is_aligned_to(self, align: usize) -> bool {
1313 self.as_ptr().is_aligned_to(align)
1314 }
1315}
1316
1317impl<T> NonNull<T> {
1318 /// Casts from a type to its maybe-uninitialized version.
1319 #[must_use]
1320 #[inline(always)]
1321 #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1322 pub const fn cast_uninit(self) -> NonNull<MaybeUninit<T>> {
1323 self.cast()
1324 }
1325
1326 /// Creates a non-null raw slice from a thin pointer and a length.
1327 ///
1328 /// The `len` argument is the number of **elements**, not the number of bytes.
1329 ///
1330 /// This function is safe, but dereferencing the return value is unsafe.
1331 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
1332 ///
1333 /// # Examples
1334 ///
1335 /// ```rust
1336 /// #![feature(ptr_cast_slice)]
1337 /// use std::ptr::NonNull;
1338 ///
1339 /// // create a slice pointer when starting out with a pointer to the first element
1340 /// let mut x = [5, 6, 7];
1341 /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
1342 /// let slice = nonnull_pointer.cast_slice(3);
1343 /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
1344 /// ```
1345 ///
1346 /// (Note that this example artificially demonstrates a use of this method,
1347 /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
1348 #[inline]
1349 #[must_use]
1350 #[unstable(feature = "ptr_cast_slice", issue = "149103")]
1351 pub const fn cast_slice(self, len: usize) -> NonNull<[T]> {
1352 NonNull::slice_from_raw_parts(self, len)
1353 }
1354}
1355impl<T> NonNull<MaybeUninit<T>> {
1356 /// Casts from a maybe-uninitialized type to its initialized version.
1357 ///
1358 /// This is always safe, since UB can only occur if the pointer is read
1359 /// before being initialized.
1360 #[must_use]
1361 #[inline(always)]
1362 #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1363 pub const fn cast_init(self) -> NonNull<T> {
1364 self.cast()
1365 }
1366}
1367
1368impl<T> NonNull<[T]> {
1369 /// Creates a non-null raw slice from a thin pointer and a length.
1370 ///
1371 /// The `len` argument is the number of **elements**, not the number of bytes.
1372 ///
1373 /// This function is safe, but dereferencing the return value is unsafe.
1374 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
1375 ///
1376 /// # Examples
1377 ///
1378 /// ```rust
1379 /// use std::ptr::NonNull;
1380 ///
1381 /// // create a slice pointer when starting out with a pointer to the first element
1382 /// let mut x = [5, 6, 7];
1383 /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
1384 /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
1385 /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
1386 /// ```
1387 ///
1388 /// (Note that this example artificially demonstrates a use of this method,
1389 /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
1390 #[stable(feature = "nonnull_slice_from_raw_parts", since = "1.70.0")]
1391 #[rustc_const_stable(feature = "const_slice_from_raw_parts_mut", since = "1.83.0")]
1392 #[must_use]
1393 #[inline]
1394 pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
1395 // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
1396 unsafe { Self::new_unchecked(data.as_ptr().cast_slice(len)) }
1397 }
1398
1399 /// Returns the length of a non-null raw slice.
1400 ///
1401 /// The returned value is the number of **elements**, not the number of bytes.
1402 ///
1403 /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
1404 /// because the pointer does not have a valid address.
1405 ///
1406 /// # Examples
1407 ///
1408 /// ```rust
1409 /// use std::ptr::NonNull;
1410 ///
1411 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1412 /// assert_eq!(slice.len(), 3);
1413 /// ```
1414 #[stable(feature = "slice_ptr_len_nonnull", since = "1.63.0")]
1415 #[rustc_const_stable(feature = "const_slice_ptr_len_nonnull", since = "1.63.0")]
1416 #[must_use]
1417 #[inline]
1418 pub const fn len(self) -> usize {
1419 self.as_ptr().len()
1420 }
1421
1422 /// Returns `true` if the non-null raw slice has a length of 0.
1423 ///
1424 /// # Examples
1425 ///
1426 /// ```rust
1427 /// use std::ptr::NonNull;
1428 ///
1429 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1430 /// assert!(!slice.is_empty());
1431 /// ```
1432 #[stable(feature = "slice_ptr_is_empty_nonnull", since = "1.79.0")]
1433 #[rustc_const_stable(feature = "const_slice_ptr_is_empty_nonnull", since = "1.79.0")]
1434 #[must_use]
1435 #[inline]
1436 pub const fn is_empty(self) -> bool {
1437 self.len() == 0
1438 }
1439
1440 /// Returns a non-null pointer to the slice's buffer.
1441 ///
1442 /// # Examples
1443 ///
1444 /// ```rust
1445 /// #![feature(slice_ptr_get)]
1446 /// use std::ptr::NonNull;
1447 ///
1448 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1449 /// assert_eq!(slice.as_non_null_ptr(), NonNull::<i8>::dangling());
1450 /// ```
1451 #[inline]
1452 #[must_use]
1453 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1454 pub const fn as_non_null_ptr(self) -> NonNull<T> {
1455 self.cast()
1456 }
1457
1458 /// Returns a raw pointer to the slice's buffer.
1459 ///
1460 /// # Examples
1461 ///
1462 /// ```rust
1463 /// #![feature(slice_ptr_get)]
1464 /// use std::ptr::NonNull;
1465 ///
1466 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1467 /// assert_eq!(slice.as_mut_ptr(), NonNull::<i8>::dangling().as_ptr());
1468 /// ```
1469 #[inline]
1470 #[must_use]
1471 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1472 #[rustc_never_returns_null_ptr]
1473 pub const fn as_mut_ptr(self) -> *mut T {
1474 self.as_non_null_ptr().as_ptr()
1475 }
1476
1477 /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to
1478 /// [`as_ref`], this does not require that the value has to be initialized.
1479 ///
1480 /// For the mutable counterpart see [`as_uninit_slice_mut`].
1481 ///
1482 /// [`as_ref`]: NonNull::as_ref
1483 /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
1484 ///
1485 /// # Safety
1486 ///
1487 /// When calling this method, you have to ensure that all of the following is true:
1488 ///
1489 /// * The pointer must be [valid] for reads for `ptr.len() * size_of::<T>()` many bytes,
1490 /// and it must be properly aligned. This means in particular:
1491 ///
1492 /// * The entire memory range of this slice must be contained within a single allocation!
1493 /// Slices can never span across multiple allocations.
1494 ///
1495 /// * The pointer must be aligned even for zero-length slices. One
1496 /// reason for this is that enum layout optimizations may rely on references
1497 /// (including slices of any length) being aligned and non-null to distinguish
1498 /// them from other data. You can obtain a pointer that is usable as `data`
1499 /// for zero-length slices using [`NonNull::dangling()`].
1500 ///
1501 /// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1502 /// See the safety documentation of [`pointer::offset`].
1503 ///
1504 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1505 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1506 /// In particular, while this reference exists, the memory the pointer points to must
1507 /// not get mutated (except inside `UnsafeCell`).
1508 ///
1509 /// This applies even if the result of this method is unused!
1510 ///
1511 /// See also [`slice::from_raw_parts`].
1512 ///
1513 /// [valid]: crate::ptr#safety
1514 #[inline]
1515 #[must_use]
1516 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1517 pub const unsafe fn as_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>] {
1518 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1519 unsafe { slice::from_raw_parts(self.cast().as_ptr(), self.len()) }
1520 }
1521
1522 /// Returns a unique reference to a slice of possibly uninitialized values. In contrast to
1523 /// [`as_mut`], this does not require that the value has to be initialized.
1524 ///
1525 /// For the shared counterpart see [`as_uninit_slice`].
1526 ///
1527 /// [`as_mut`]: NonNull::as_mut
1528 /// [`as_uninit_slice`]: NonNull::as_uninit_slice
1529 ///
1530 /// # Safety
1531 ///
1532 /// When calling this method, you have to ensure that all of the following is true:
1533 ///
1534 /// * The pointer must be [valid] for reads and writes for `ptr.len() * size_of::<T>()`
1535 /// many bytes, and it must be properly aligned. This means in particular:
1536 ///
1537 /// * The entire memory range of this slice must be contained within a single allocation!
1538 /// Slices can never span across multiple allocations.
1539 ///
1540 /// * The pointer must be aligned even for zero-length slices. One
1541 /// reason for this is that enum layout optimizations may rely on references
1542 /// (including slices of any length) being aligned and non-null to distinguish
1543 /// them from other data. You can obtain a pointer that is usable as `data`
1544 /// for zero-length slices using [`NonNull::dangling()`].
1545 ///
1546 /// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1547 /// See the safety documentation of [`pointer::offset`].
1548 ///
1549 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1550 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1551 /// In particular, while this reference exists, the memory the pointer points to must
1552 /// not get accessed (read or written) through any other pointer.
1553 ///
1554 /// This applies even if the result of this method is unused!
1555 ///
1556 /// See also [`slice::from_raw_parts_mut`].
1557 ///
1558 /// [valid]: crate::ptr#safety
1559 ///
1560 /// # Examples
1561 ///
1562 /// ```rust
1563 /// #![feature(ptr_as_uninit)]
1564 ///
1565 /// use std::alloc::{Allocator, Layout, Global};
1566 /// use std::mem::MaybeUninit;
1567 /// use std::ptr::NonNull;
1568 ///
1569 /// let memory: NonNull<[u8]> = Global.allocate(Layout::new::<[u8; 32]>())?;
1570 /// // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes.
1571 /// // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized.
1572 /// # #[allow(unused_variables)]
1573 /// let slice: &mut [MaybeUninit<u8>] = unsafe { memory.as_uninit_slice_mut() };
1574 /// # // Prevent leaks for Miri.
1575 /// # unsafe { Global.deallocate(memory.cast(), Layout::new::<[u8; 32]>()); }
1576 /// # Ok::<_, std::alloc::AllocError>(())
1577 /// ```
1578 #[inline]
1579 #[must_use]
1580 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1581 pub const unsafe fn as_uninit_slice_mut<'a>(self) -> &'a mut [MaybeUninit<T>] {
1582 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
1583 unsafe { slice::from_raw_parts_mut(self.cast().as_ptr(), self.len()) }
1584 }
1585
1586 /// Returns a raw pointer to an element or subslice, without doing bounds
1587 /// checking.
1588 ///
1589 /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
1590 /// is *[undefined behavior]* even if the resulting pointer is not used.
1591 ///
1592 /// [out-of-bounds index]: #method.add
1593 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1594 ///
1595 /// # Examples
1596 ///
1597 /// ```
1598 /// #![feature(slice_ptr_get)]
1599 /// use std::ptr::NonNull;
1600 ///
1601 /// let x = &mut [1, 2, 4];
1602 /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
1603 ///
1604 /// unsafe {
1605 /// assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
1606 /// }
1607 /// ```
1608 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1609 #[rustc_const_unstable(feature = "const_index", issue = "143775")]
1610 #[inline]
1611 pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
1612 where
1613 I: [const] SliceIndex<[T]>,
1614 {
1615 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1616 // As a consequence, the resulting pointer cannot be null.
1617 unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
1618 }
1619}
1620
1621#[stable(feature = "nonnull", since = "1.25.0")]
1622impl<T: PointeeSized> Clone for NonNull<T> {
1623 #[inline(always)]
1624 fn clone(&self) -> Self {
1625 *self
1626 }
1627}
1628
1629#[stable(feature = "nonnull", since = "1.25.0")]
1630impl<T: PointeeSized> Copy for NonNull<T> {}
1631
1632#[doc(hidden)]
1633#[unstable(feature = "trivial_clone", issue = "none")]
1634unsafe impl<T: PointeeSized> TrivialClone for NonNull<T> {}
1635
1636#[unstable(feature = "coerce_unsized", issue = "18598")]
1637impl<T: PointeeSized, U: PointeeSized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
1638
1639#[unstable(feature = "dispatch_from_dyn", issue = "none")]
1640impl<T: PointeeSized, U: PointeeSized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
1641
1642#[stable(feature = "nonnull", since = "1.25.0")]
1643impl<T: PointeeSized> fmt::Debug for NonNull<T> {
1644 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1645 fmt::Pointer::fmt(&self.as_ptr(), f)
1646 }
1647}
1648
1649#[stable(feature = "nonnull", since = "1.25.0")]
1650impl<T: PointeeSized> fmt::Pointer for NonNull<T> {
1651 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1652 fmt::Pointer::fmt(&self.as_ptr(), f)
1653 }
1654}
1655
1656#[stable(feature = "nonnull", since = "1.25.0")]
1657impl<T: PointeeSized> Eq for NonNull<T> {}
1658
1659#[stable(feature = "nonnull", since = "1.25.0")]
1660impl<T: PointeeSized> PartialEq for NonNull<T> {
1661 #[inline]
1662 #[allow(ambiguous_wide_pointer_comparisons)]
1663 fn eq(&self, other: &Self) -> bool {
1664 self.as_ptr() == other.as_ptr()
1665 }
1666}
1667
1668#[stable(feature = "nonnull", since = "1.25.0")]
1669impl<T: PointeeSized> Ord for NonNull<T> {
1670 #[inline]
1671 #[allow(ambiguous_wide_pointer_comparisons)]
1672 fn cmp(&self, other: &Self) -> Ordering {
1673 self.as_ptr().cmp(&other.as_ptr())
1674 }
1675}
1676
1677#[stable(feature = "nonnull", since = "1.25.0")]
1678impl<T: PointeeSized> PartialOrd for NonNull<T> {
1679 #[inline]
1680 #[allow(ambiguous_wide_pointer_comparisons)]
1681 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1682 self.as_ptr().partial_cmp(&other.as_ptr())
1683 }
1684}
1685
1686#[stable(feature = "nonnull", since = "1.25.0")]
1687impl<T: PointeeSized> hash::Hash for NonNull<T> {
1688 #[inline]
1689 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1690 self.as_ptr().hash(state)
1691 }
1692}
1693
1694#[unstable(feature = "ptr_internals", issue = "none")]
1695#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1696const impl<T: PointeeSized> From<Unique<T>> for NonNull<T> {
1697 #[inline]
1698 fn from(unique: Unique<T>) -> Self {
1699 unique.as_non_null_ptr()
1700 }
1701}
1702
1703#[stable(feature = "nonnull", since = "1.25.0")]
1704#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1705const impl<T: PointeeSized> From<&mut T> for NonNull<T> {
1706 /// Converts a `&mut T` to a `NonNull<T>`.
1707 ///
1708 /// This conversion is safe and infallible since references cannot be null.
1709 #[inline]
1710 fn from(r: &mut T) -> Self {
1711 NonNull::from_mut(r)
1712 }
1713}
1714
1715#[stable(feature = "nonnull", since = "1.25.0")]
1716#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1717const impl<T: PointeeSized> From<&T> for NonNull<T> {
1718 /// Converts a `&T` to a `NonNull<T>`.
1719 ///
1720 /// This conversion is safe and infallible since references cannot be null.
1721 #[inline]
1722 fn from(r: &T) -> Self {
1723 NonNull::from_ref(r)
1724 }
1725}