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