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