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