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