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