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