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