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