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 `(self as isize -
740 /// origin as isize) / size_of::<T>()`.
741 // FIXME: recommend `addr()` instead of `as usize` once that is stable.
742 ///
743 /// [`add`]: #method.add
744 /// [allocation]: crate::ptr#allocation
745 ///
746 /// # Panics
747 ///
748 /// This function panics if `T` is a Zero-Sized Type ("ZST").
749 ///
750 /// # Examples
751 ///
752 /// Basic usage:
753 ///
754 /// ```
755 /// use std::ptr::NonNull;
756 ///
757 /// let a = [0; 5];
758 /// let ptr1: NonNull<u32> = NonNull::from(&a[1]);
759 /// let ptr2: NonNull<u32> = NonNull::from(&a[3]);
760 /// unsafe {
761 /// assert_eq!(ptr2.offset_from(ptr1), 2);
762 /// assert_eq!(ptr1.offset_from(ptr2), -2);
763 /// assert_eq!(ptr1.offset(2), ptr2);
764 /// assert_eq!(ptr2.offset(-2), ptr1);
765 /// }
766 /// ```
767 ///
768 /// *Incorrect* usage:
769 ///
770 /// ```rust,no_run
771 /// use std::ptr::NonNull;
772 ///
773 /// let ptr1 = NonNull::new(Box::into_raw(Box::new(0u8))).unwrap();
774 /// let ptr2 = NonNull::new(Box::into_raw(Box::new(1u8))).unwrap();
775 /// let diff = (ptr2.addr().get() as isize).wrapping_sub(ptr1.addr().get() as isize);
776 /// // Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.
777 /// let diff_plus_1 = diff.wrapping_add(1);
778 /// let ptr2_other = NonNull::new(ptr1.as_ptr().wrapping_byte_offset(diff_plus_1)).unwrap();
779 /// assert_eq!(ptr2.addr(), ptr2_other.addr());
780 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
781 /// // computing their offset is undefined behavior, even though
782 /// // they point to addresses that are in-bounds of the same object!
783 ///
784 /// let one = unsafe { ptr2_other.offset_from(ptr2) }; // Undefined Behavior! ⚠️
785 /// ```
786 #[inline]
787 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
788 #[stable(feature = "non_null_convenience", since = "1.80.0")]
789 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
790 pub const unsafe fn offset_from(self, origin: NonNull<T>) -> isize
791 where
792 T: Sized,
793 {
794 // SAFETY: the caller must uphold the safety contract for `offset_from`.
795 unsafe { self.as_ptr().offset_from(origin.as_ptr()) }
796 }
797
798 /// Calculates the distance between two pointers within the same allocation. The returned value is in
799 /// units of **bytes**.
800 ///
801 /// This is purely a convenience for casting to a `u8` pointer and
802 /// using [`offset_from`][NonNull::offset_from] on it. See that method for
803 /// documentation and safety requirements.
804 ///
805 /// For non-`Sized` pointees this operation considers only the data pointers,
806 /// ignoring the metadata.
807 #[inline(always)]
808 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
809 #[stable(feature = "non_null_convenience", since = "1.80.0")]
810 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
811 pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: NonNull<U>) -> isize {
812 // SAFETY: the caller must uphold the safety contract for `byte_offset_from`.
813 unsafe { self.as_ptr().byte_offset_from(origin.as_ptr()) }
814 }
815
816 // N.B. `wrapping_offset``, `wrapping_add`, etc are not implemented because they can wrap to null
817
818 /// Calculates the distance between two pointers within the same allocation, *where it's known that
819 /// `self` is equal to or greater than `origin`*. The returned value is in
820 /// units of T: the distance in bytes is divided by `size_of::<T>()`.
821 ///
822 /// This computes the same value that [`offset_from`](#method.offset_from)
823 /// would compute, but with the added precondition that the offset is
824 /// guaranteed to be non-negative. This method is equivalent to
825 /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`,
826 /// but it provides slightly more information to the optimizer, which can
827 /// sometimes allow it to optimize slightly better with some backends.
828 ///
829 /// This method can be though of as recovering the `count` that was passed
830 /// to [`add`](#method.add) (or, with the parameters in the other order,
831 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
832 /// that their safety preconditions are met:
833 /// ```rust
834 /// # unsafe fn blah(ptr: std::ptr::NonNull<u32>, origin: std::ptr::NonNull<u32>, count: usize) -> bool { unsafe {
835 /// ptr.offset_from_unsigned(origin) == count
836 /// # &&
837 /// origin.add(count) == ptr
838 /// # &&
839 /// ptr.sub(count) == origin
840 /// # } }
841 /// ```
842 ///
843 /// # Safety
844 ///
845 /// - The distance between the pointers must be non-negative (`self >= origin`)
846 ///
847 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
848 /// apply to this method as well; see it for the full details.
849 ///
850 /// Importantly, despite the return type of this method being able to represent
851 /// a larger offset, it's still *not permitted* to pass pointers which differ
852 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
853 /// always be less than or equal to `isize::MAX as usize`.
854 ///
855 /// # Panics
856 ///
857 /// This function panics if `T` is a Zero-Sized Type ("ZST").
858 ///
859 /// # Examples
860 ///
861 /// ```
862 /// use std::ptr::NonNull;
863 ///
864 /// let a = [0; 5];
865 /// let ptr1: NonNull<u32> = NonNull::from(&a[1]);
866 /// let ptr2: NonNull<u32> = NonNull::from(&a[3]);
867 /// unsafe {
868 /// assert_eq!(ptr2.offset_from_unsigned(ptr1), 2);
869 /// assert_eq!(ptr1.add(2), ptr2);
870 /// assert_eq!(ptr2.sub(2), ptr1);
871 /// assert_eq!(ptr2.offset_from_unsigned(ptr2), 0);
872 /// }
873 ///
874 /// // This would be incorrect, as the pointers are not correctly ordered:
875 /// // ptr1.offset_from_unsigned(ptr2)
876 /// ```
877 #[inline]
878 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
879 #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
880 #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
881 pub const unsafe fn offset_from_unsigned(self, subtracted: NonNull<T>) -> usize
882 where
883 T: Sized,
884 {
885 // SAFETY: the caller must uphold the safety contract for `offset_from_unsigned`.
886 unsafe { self.as_ptr().offset_from_unsigned(subtracted.as_ptr()) }
887 }
888
889 /// Calculates the distance between two pointers within the same allocation, *where it's known that
890 /// `self` is equal to or greater than `origin`*. The returned value is in
891 /// units of **bytes**.
892 ///
893 /// This is purely a convenience for casting to a `u8` pointer and
894 /// using [`offset_from_unsigned`][NonNull::offset_from_unsigned] on it.
895 /// See that method for documentation and safety requirements.
896 ///
897 /// For non-`Sized` pointees this operation considers only the data pointers,
898 /// ignoring the metadata.
899 #[inline(always)]
900 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
901 #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
902 #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
903 pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: NonNull<U>) -> usize {
904 // SAFETY: the caller must uphold the safety contract for `byte_offset_from_unsigned`.
905 unsafe { self.as_ptr().byte_offset_from_unsigned(origin.as_ptr()) }
906 }
907
908 /// Reads the value from `self` without moving it. This leaves the
909 /// memory in `self` unchanged.
910 ///
911 /// See [`ptr::read`] for safety concerns and examples.
912 ///
913 /// [`ptr::read`]: crate::ptr::read()
914 #[inline]
915 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
916 #[stable(feature = "non_null_convenience", since = "1.80.0")]
917 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
918 pub const unsafe fn read(self) -> T
919 where
920 T: Sized,
921 {
922 // SAFETY: the caller must uphold the safety contract for `read`.
923 unsafe { ptr::read(self.as_ptr()) }
924 }
925
926 /// Performs a volatile read of the value from `self` without moving it. This
927 /// leaves the memory in `self` unchanged.
928 ///
929 /// Volatile operations are intended to act on I/O memory, and are guaranteed
930 /// to not be elided or reordered by the compiler across other volatile
931 /// operations.
932 ///
933 /// See [`ptr::read_volatile`] for safety concerns and examples.
934 ///
935 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
936 #[inline]
937 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
938 #[stable(feature = "non_null_convenience", since = "1.80.0")]
939 pub unsafe fn read_volatile(self) -> T
940 where
941 T: Sized,
942 {
943 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
944 unsafe { ptr::read_volatile(self.as_ptr()) }
945 }
946
947 /// Reads the value from `self` without moving it. This leaves the
948 /// memory in `self` unchanged.
949 ///
950 /// Unlike `read`, the pointer may be unaligned.
951 ///
952 /// See [`ptr::read_unaligned`] for safety concerns and examples.
953 ///
954 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
955 #[inline]
956 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
957 #[stable(feature = "non_null_convenience", since = "1.80.0")]
958 #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
959 pub const unsafe fn read_unaligned(self) -> T
960 where
961 T: Sized,
962 {
963 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
964 unsafe { ptr::read_unaligned(self.as_ptr()) }
965 }
966
967 /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
968 /// and destination may overlap.
969 ///
970 /// NOTE: this has the *same* argument order as [`ptr::copy`].
971 ///
972 /// See [`ptr::copy`] for safety concerns and examples.
973 ///
974 /// [`ptr::copy`]: crate::ptr::copy()
975 #[inline(always)]
976 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
977 #[stable(feature = "non_null_convenience", since = "1.80.0")]
978 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
979 pub const unsafe fn copy_to(self, dest: NonNull<T>, count: usize)
980 where
981 T: Sized,
982 {
983 // SAFETY: the caller must uphold the safety contract for `copy`.
984 unsafe { ptr::copy(self.as_ptr(), dest.as_ptr(), count) }
985 }
986
987 /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
988 /// and destination may *not* overlap.
989 ///
990 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
991 ///
992 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
993 ///
994 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
995 #[inline(always)]
996 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
997 #[stable(feature = "non_null_convenience", since = "1.80.0")]
998 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
999 pub const unsafe fn copy_to_nonoverlapping(self, dest: NonNull<T>, count: usize)
1000 where
1001 T: Sized,
1002 {
1003 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1004 unsafe { ptr::copy_nonoverlapping(self.as_ptr(), dest.as_ptr(), count) }
1005 }
1006
1007 /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
1008 /// and destination may overlap.
1009 ///
1010 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1011 ///
1012 /// See [`ptr::copy`] for safety concerns and examples.
1013 ///
1014 /// [`ptr::copy`]: crate::ptr::copy()
1015 #[inline(always)]
1016 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1017 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1018 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1019 pub const unsafe fn copy_from(self, src: NonNull<T>, count: usize)
1020 where
1021 T: Sized,
1022 {
1023 // SAFETY: the caller must uphold the safety contract for `copy`.
1024 unsafe { ptr::copy(src.as_ptr(), self.as_ptr(), count) }
1025 }
1026
1027 /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
1028 /// and destination may *not* overlap.
1029 ///
1030 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1031 ///
1032 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1033 ///
1034 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1035 #[inline(always)]
1036 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1037 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1038 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1039 pub const unsafe fn copy_from_nonoverlapping(self, src: NonNull<T>, count: usize)
1040 where
1041 T: Sized,
1042 {
1043 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1044 unsafe { ptr::copy_nonoverlapping(src.as_ptr(), self.as_ptr(), count) }
1045 }
1046
1047 /// Executes the destructor (if any) of the pointed-to value.
1048 ///
1049 /// See [`ptr::drop_in_place`] for safety concerns and examples.
1050 ///
1051 /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1052 #[inline(always)]
1053 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1054 #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
1055 pub const unsafe fn drop_in_place(mut self)
1056 where
1057 T: [const] Destruct,
1058 {
1059 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1060 unsafe { ptr::drop_glue(self.as_mut()) }
1061 }
1062
1063 /// Overwrites a memory location with the given value without reading or
1064 /// dropping the old value.
1065 ///
1066 /// See [`ptr::write`] for safety concerns and examples.
1067 ///
1068 /// [`ptr::write`]: crate::ptr::write()
1069 #[inline(always)]
1070 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1071 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1072 #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1073 pub const unsafe fn write(self, val: T)
1074 where
1075 T: Sized,
1076 {
1077 // SAFETY: the caller must uphold the safety contract for `write`.
1078 unsafe { ptr::write(self.as_ptr(), val) }
1079 }
1080
1081 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1082 /// bytes of memory starting at `self` to `val`.
1083 ///
1084 /// See [`ptr::write_bytes`] for safety concerns and examples.
1085 ///
1086 /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1087 #[inline(always)]
1088 #[doc(alias = "memset")]
1089 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1090 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1091 #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1092 pub const unsafe fn write_bytes(self, val: u8, count: usize)
1093 where
1094 T: Sized,
1095 {
1096 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1097 unsafe { ptr::write_bytes(self.as_ptr(), val, count) }
1098 }
1099
1100 /// Performs a volatile write of a memory location with the given value without
1101 /// reading or dropping the old value.
1102 ///
1103 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1104 /// to not be elided or reordered by the compiler across other volatile
1105 /// operations.
1106 ///
1107 /// See [`ptr::write_volatile`] for safety concerns and examples.
1108 ///
1109 /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1110 #[inline(always)]
1111 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1112 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1113 pub unsafe fn write_volatile(self, val: T)
1114 where
1115 T: Sized,
1116 {
1117 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1118 unsafe { ptr::write_volatile(self.as_ptr(), val) }
1119 }
1120
1121 /// Overwrites a memory location with the given value without reading or
1122 /// dropping the old value.
1123 ///
1124 /// Unlike `write`, the pointer may be unaligned.
1125 ///
1126 /// See [`ptr::write_unaligned`] for safety concerns and examples.
1127 ///
1128 /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1129 #[inline(always)]
1130 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1131 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1132 #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1133 pub const unsafe fn write_unaligned(self, val: T)
1134 where
1135 T: Sized,
1136 {
1137 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1138 unsafe { ptr::write_unaligned(self.as_ptr(), val) }
1139 }
1140
1141 /// Replaces the value at `self` with `src`, returning the old
1142 /// value, without dropping either.
1143 ///
1144 /// See [`ptr::replace`] for safety concerns and examples.
1145 ///
1146 /// [`ptr::replace`]: crate::ptr::replace()
1147 #[inline(always)]
1148 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1149 #[rustc_const_stable(feature = "const_inherent_ptr_replace", since = "1.88.0")]
1150 pub const unsafe fn replace(self, src: T) -> T
1151 where
1152 T: Sized,
1153 {
1154 // SAFETY: the caller must uphold the safety contract for `replace`.
1155 unsafe { ptr::replace(self.as_ptr(), src) }
1156 }
1157
1158 /// Swaps the values at two mutable locations of the same type, without
1159 /// deinitializing either. They may overlap, unlike `mem::swap` which is
1160 /// otherwise equivalent.
1161 ///
1162 /// See [`ptr::swap`] for safety concerns and examples.
1163 ///
1164 /// [`ptr::swap`]: crate::ptr::swap()
1165 #[inline(always)]
1166 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1167 #[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
1168 pub const unsafe fn swap(self, with: NonNull<T>)
1169 where
1170 T: Sized,
1171 {
1172 // SAFETY: the caller must uphold the safety contract for `swap`.
1173 unsafe { ptr::swap(self.as_ptr(), with.as_ptr()) }
1174 }
1175
1176 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1177 /// `align`.
1178 ///
1179 /// If it is not possible to align the pointer, the implementation returns
1180 /// `usize::MAX`.
1181 ///
1182 /// The offset is expressed in number of `T` elements, and not bytes.
1183 ///
1184 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1185 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1186 /// the returned offset is correct in all terms other than alignment.
1187 ///
1188 /// When this is called during compile-time evaluation (which is unstable), the implementation
1189 /// may return `usize::MAX` in cases where that can never happen at runtime. This is because the
1190 /// actual alignment of pointers is not known yet during compile-time, so an offset with
1191 /// guaranteed alignment can sometimes not be computed. For example, a buffer declared as `[u8;
1192 /// N]` might be allocated at an odd or an even address, but at compile-time this is not yet
1193 /// known, so the execution has to be correct for either choice. It is therefore impossible to
1194 /// find an offset that is guaranteed to be 2-aligned. (This behavior is subject to change, as usual
1195 /// for unstable APIs.)
1196 ///
1197 /// # Panics
1198 ///
1199 /// The function panics if `align` is not a power-of-two.
1200 ///
1201 /// # Examples
1202 ///
1203 /// Accessing adjacent `u8` as `u16`
1204 ///
1205 /// ```
1206 /// use std::ptr::NonNull;
1207 ///
1208 /// # unsafe {
1209 /// let x = [5_u8, 6, 7, 8, 9];
1210 /// let ptr = NonNull::new(x.as_ptr() as *mut u8).unwrap();
1211 /// let offset = ptr.align_offset(align_of::<u16>());
1212 ///
1213 /// if offset < x.len() - 1 {
1214 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1215 /// assert!(u16_ptr.read() == u16::from_ne_bytes([5, 6]) || u16_ptr.read() == u16::from_ne_bytes([6, 7]));
1216 /// } else {
1217 /// // while the pointer can be aligned via `offset`, it would point
1218 /// // outside the allocation
1219 /// }
1220 /// # }
1221 /// ```
1222 #[inline]
1223 #[must_use]
1224 #[stable(feature = "non_null_convenience", since = "1.80.0")]
1225 pub fn align_offset(self, align: usize) -> usize
1226 where
1227 T: Sized,
1228 {
1229 if !align.is_power_of_two() {
1230 panic!("align_offset: align is not a power-of-two");
1231 }
1232
1233 {
1234 // SAFETY: `align` has been checked to be a power of 2 above.
1235 unsafe { ptr::align_offset(self.as_ptr(), align) }
1236 }
1237 }
1238
1239 /// Returns whether the pointer is properly aligned for `T`.
1240 ///
1241 /// # Examples
1242 ///
1243 /// ```
1244 /// use std::ptr::NonNull;
1245 ///
1246 /// // On some platforms, the alignment of i32 is less than 4.
1247 /// #[repr(align(4))]
1248 /// struct AlignedI32(i32);
1249 ///
1250 /// let data = AlignedI32(42);
1251 /// let ptr = NonNull::<AlignedI32>::from(&data);
1252 ///
1253 /// assert!(ptr.is_aligned());
1254 /// assert!(!NonNull::new(ptr.as_ptr().wrapping_byte_add(1)).unwrap().is_aligned());
1255 /// ```
1256 #[inline]
1257 #[must_use]
1258 #[stable(feature = "pointer_is_aligned", since = "1.79.0")]
1259 pub fn is_aligned(self) -> bool
1260 where
1261 T: Sized,
1262 {
1263 self.as_ptr().is_aligned()
1264 }
1265
1266 /// Returns whether the pointer is aligned to `align`.
1267 ///
1268 /// For non-`Sized` pointees this operation considers only the data pointer,
1269 /// ignoring the metadata.
1270 ///
1271 /// # Panics
1272 ///
1273 /// The function panics if `align` is not a power-of-two (this includes 0).
1274 ///
1275 /// # Examples
1276 ///
1277 /// ```
1278 /// #![feature(pointer_is_aligned_to)]
1279 ///
1280 /// // On some platforms, the alignment of i32 is less than 4.
1281 /// #[repr(align(4))]
1282 /// struct AlignedI32(i32);
1283 ///
1284 /// let data = AlignedI32(42);
1285 /// let ptr = &data as *const AlignedI32;
1286 ///
1287 /// assert!(ptr.is_aligned_to(1));
1288 /// assert!(ptr.is_aligned_to(2));
1289 /// assert!(ptr.is_aligned_to(4));
1290 ///
1291 /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1292 /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1293 ///
1294 /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1295 /// ```
1296 #[inline]
1297 #[must_use]
1298 #[unstable(feature = "pointer_is_aligned_to", issue = "96284")]
1299 pub fn is_aligned_to(self, align: usize) -> bool {
1300 self.as_ptr().is_aligned_to(align)
1301 }
1302}
1303
1304impl<T> NonNull<T> {
1305 /// Casts from a type to its maybe-uninitialized version.
1306 #[must_use]
1307 #[inline(always)]
1308 #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1309 pub const fn cast_uninit(self) -> NonNull<MaybeUninit<T>> {
1310 self.cast()
1311 }
1312
1313 /// Creates a non-null raw slice from a thin pointer and a length.
1314 ///
1315 /// The `len` argument is the number of **elements**, not the number of bytes.
1316 ///
1317 /// This function is safe, but dereferencing the return value is unsafe.
1318 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
1319 ///
1320 /// # Examples
1321 ///
1322 /// ```rust
1323 /// #![feature(ptr_cast_slice)]
1324 /// use std::ptr::NonNull;
1325 ///
1326 /// // create a slice pointer when starting out with a pointer to the first element
1327 /// let mut x = [5, 6, 7];
1328 /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
1329 /// let slice = nonnull_pointer.cast_slice(3);
1330 /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
1331 /// ```
1332 ///
1333 /// (Note that this example artificially demonstrates a use of this method,
1334 /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
1335 #[inline]
1336 #[must_use]
1337 #[unstable(feature = "ptr_cast_slice", issue = "149103")]
1338 pub const fn cast_slice(self, len: usize) -> NonNull<[T]> {
1339 NonNull::slice_from_raw_parts(self, len)
1340 }
1341}
1342impl<T> NonNull<MaybeUninit<T>> {
1343 /// Casts from a maybe-uninitialized type to its initialized version.
1344 ///
1345 /// This is always safe, since UB can only occur if the pointer is read
1346 /// before being initialized.
1347 #[must_use]
1348 #[inline(always)]
1349 #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1350 pub const fn cast_init(self) -> NonNull<T> {
1351 self.cast()
1352 }
1353}
1354
1355impl<T> NonNull<[T]> {
1356 /// Creates a non-null raw slice from a thin pointer and a length.
1357 ///
1358 /// The `len` argument is the number of **elements**, not the number of bytes.
1359 ///
1360 /// This function is safe, but dereferencing the return value is unsafe.
1361 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
1362 ///
1363 /// # Examples
1364 ///
1365 /// ```rust
1366 /// use std::ptr::NonNull;
1367 ///
1368 /// // create a slice pointer when starting out with a pointer to the first element
1369 /// let mut x = [5, 6, 7];
1370 /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
1371 /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
1372 /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
1373 /// ```
1374 ///
1375 /// (Note that this example artificially demonstrates a use of this method,
1376 /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
1377 #[stable(feature = "nonnull_slice_from_raw_parts", since = "1.70.0")]
1378 #[rustc_const_stable(feature = "const_slice_from_raw_parts_mut", since = "1.83.0")]
1379 #[must_use]
1380 #[inline]
1381 pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
1382 // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
1383 unsafe { Self::new_unchecked(data.as_ptr().cast_slice(len)) }
1384 }
1385
1386 /// Returns the length of a non-null raw slice.
1387 ///
1388 /// The returned value is the number of **elements**, not the number of bytes.
1389 ///
1390 /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
1391 /// because the pointer does not have a valid address.
1392 ///
1393 /// # Examples
1394 ///
1395 /// ```rust
1396 /// use std::ptr::NonNull;
1397 ///
1398 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1399 /// assert_eq!(slice.len(), 3);
1400 /// ```
1401 #[stable(feature = "slice_ptr_len_nonnull", since = "1.63.0")]
1402 #[rustc_const_stable(feature = "const_slice_ptr_len_nonnull", since = "1.63.0")]
1403 #[must_use]
1404 #[inline]
1405 pub const fn len(self) -> usize {
1406 self.as_ptr().len()
1407 }
1408
1409 /// Returns `true` if the non-null raw slice has a length of 0.
1410 ///
1411 /// # Examples
1412 ///
1413 /// ```rust
1414 /// use std::ptr::NonNull;
1415 ///
1416 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1417 /// assert!(!slice.is_empty());
1418 /// ```
1419 #[stable(feature = "slice_ptr_is_empty_nonnull", since = "1.79.0")]
1420 #[rustc_const_stable(feature = "const_slice_ptr_is_empty_nonnull", since = "1.79.0")]
1421 #[must_use]
1422 #[inline]
1423 pub const fn is_empty(self) -> bool {
1424 self.len() == 0
1425 }
1426
1427 /// Returns a non-null pointer to the slice's buffer.
1428 ///
1429 /// # Examples
1430 ///
1431 /// ```rust
1432 /// #![feature(slice_ptr_get)]
1433 /// use std::ptr::NonNull;
1434 ///
1435 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1436 /// assert_eq!(slice.as_non_null_ptr(), NonNull::<i8>::dangling());
1437 /// ```
1438 #[inline]
1439 #[must_use]
1440 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1441 pub const fn as_non_null_ptr(self) -> NonNull<T> {
1442 self.cast()
1443 }
1444
1445 /// Returns a raw pointer to the slice's buffer.
1446 ///
1447 /// # Examples
1448 ///
1449 /// ```rust
1450 /// #![feature(slice_ptr_get)]
1451 /// use std::ptr::NonNull;
1452 ///
1453 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1454 /// assert_eq!(slice.as_mut_ptr(), NonNull::<i8>::dangling().as_ptr());
1455 /// ```
1456 #[inline]
1457 #[must_use]
1458 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1459 #[rustc_never_returns_null_ptr]
1460 pub const fn as_mut_ptr(self) -> *mut T {
1461 self.as_non_null_ptr().as_ptr()
1462 }
1463
1464 /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to
1465 /// [`as_ref`], this does not require that the value has to be initialized.
1466 ///
1467 /// For the mutable counterpart see [`as_uninit_slice_mut`].
1468 ///
1469 /// [`as_ref`]: NonNull::as_ref
1470 /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
1471 ///
1472 /// # Safety
1473 ///
1474 /// When calling this method, you have to ensure that all of the following is true:
1475 ///
1476 /// * The pointer must be [valid] for reads for `ptr.len() * size_of::<T>()` many bytes,
1477 /// and it must be properly aligned. This means in particular:
1478 ///
1479 /// * The entire memory range of this slice must be contained within a single allocation!
1480 /// Slices can never span across multiple allocations.
1481 ///
1482 /// * The pointer must be aligned even for zero-length slices. One
1483 /// reason for this is that enum layout optimizations may rely on references
1484 /// (including slices of any length) being aligned and non-null to distinguish
1485 /// them from other data. You can obtain a pointer that is usable as `data`
1486 /// for zero-length slices using [`NonNull::dangling()`].
1487 ///
1488 /// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1489 /// See the safety documentation of [`pointer::offset`].
1490 ///
1491 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1492 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1493 /// In particular, while this reference exists, the memory the pointer points to must
1494 /// not get mutated (except inside `UnsafeCell`).
1495 ///
1496 /// This applies even if the result of this method is unused!
1497 ///
1498 /// See also [`slice::from_raw_parts`].
1499 ///
1500 /// [valid]: crate::ptr#safety
1501 #[inline]
1502 #[must_use]
1503 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1504 pub const unsafe fn as_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>] {
1505 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1506 unsafe { slice::from_raw_parts(self.cast().as_ptr(), self.len()) }
1507 }
1508
1509 /// Returns a unique reference to a slice of possibly uninitialized values. In contrast to
1510 /// [`as_mut`], this does not require that the value has to be initialized.
1511 ///
1512 /// For the shared counterpart see [`as_uninit_slice`].
1513 ///
1514 /// [`as_mut`]: NonNull::as_mut
1515 /// [`as_uninit_slice`]: NonNull::as_uninit_slice
1516 ///
1517 /// # Safety
1518 ///
1519 /// When calling this method, you have to ensure that all of the following is true:
1520 ///
1521 /// * The pointer must be [valid] for reads and writes for `ptr.len() * size_of::<T>()`
1522 /// many bytes, and it must be properly aligned. This means in particular:
1523 ///
1524 /// * The entire memory range of this slice must be contained within a single allocation!
1525 /// Slices can never span across multiple allocations.
1526 ///
1527 /// * The pointer must be aligned even for zero-length slices. One
1528 /// reason for this is that enum layout optimizations may rely on references
1529 /// (including slices of any length) being aligned and non-null to distinguish
1530 /// them from other data. You can obtain a pointer that is usable as `data`
1531 /// for zero-length slices using [`NonNull::dangling()`].
1532 ///
1533 /// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1534 /// See the safety documentation of [`pointer::offset`].
1535 ///
1536 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1537 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1538 /// In particular, while this reference exists, the memory the pointer points to must
1539 /// not get accessed (read or written) through any other pointer.
1540 ///
1541 /// This applies even if the result of this method is unused!
1542 ///
1543 /// See also [`slice::from_raw_parts_mut`].
1544 ///
1545 /// [valid]: crate::ptr#safety
1546 ///
1547 /// # Examples
1548 ///
1549 /// ```rust
1550 /// #![feature(allocator_api, ptr_as_uninit)]
1551 ///
1552 /// use std::alloc::{Allocator, Layout, Global};
1553 /// use std::mem::MaybeUninit;
1554 /// use std::ptr::NonNull;
1555 ///
1556 /// let memory: NonNull<[u8]> = Global.allocate(Layout::new::<[u8; 32]>())?;
1557 /// // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes.
1558 /// // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized.
1559 /// # #[allow(unused_variables)]
1560 /// let slice: &mut [MaybeUninit<u8>] = unsafe { memory.as_uninit_slice_mut() };
1561 /// # // Prevent leaks for Miri.
1562 /// # unsafe { Global.deallocate(memory.cast(), Layout::new::<[u8; 32]>()); }
1563 /// # Ok::<_, std::alloc::AllocError>(())
1564 /// ```
1565 #[inline]
1566 #[must_use]
1567 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1568 pub const unsafe fn as_uninit_slice_mut<'a>(self) -> &'a mut [MaybeUninit<T>] {
1569 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
1570 unsafe { slice::from_raw_parts_mut(self.cast().as_ptr(), self.len()) }
1571 }
1572
1573 /// Returns a raw pointer to an element or subslice, without doing bounds
1574 /// checking.
1575 ///
1576 /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
1577 /// is *[undefined behavior]* even if the resulting pointer is not used.
1578 ///
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}