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