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