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