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