Skip to main content

core/ptr/
mut_ptr.rs

1use super::*;
2use crate::cmp::Ordering::{Equal, Greater, Less};
3use crate::intrinsics::const_eval_select;
4use crate::marker::{Destruct, PointeeSized};
5use crate::mem::{self, SizedTypeProperties};
6use crate::slice::{self, SliceIndex};
7
8impl<T: PointeeSized> *mut T {
9    #[doc = include_str!("docs/is_null.md")]
10    ///
11    /// # Examples
12    ///
13    /// ```
14    /// let mut s = [1, 2, 3];
15    /// let ptr: *mut u32 = s.as_mut_ptr();
16    /// assert!(!ptr.is_null());
17    /// ```
18    #[stable(feature = "rust1", since = "1.0.0")]
19    #[rustc_const_stable(feature = "const_ptr_is_null", since = "1.84.0")]
20    #[rustc_diagnostic_item = "ptr_is_null"]
21    #[inline]
22    #[ferrocene::prevalidated]
23    pub const fn is_null(self) -> bool {
24        self.cast_const().is_null()
25    }
26
27    /// Casts to a pointer of another type.
28    #[stable(feature = "ptr_cast", since = "1.38.0")]
29    #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
30    #[rustc_diagnostic_item = "ptr_cast"]
31    #[inline(always)]
32    #[ferrocene::prevalidated]
33    pub const fn cast<U>(self) -> *mut U {
34        self as _
35    }
36
37    /// Try to cast to a pointer of another type by checking alignment.
38    ///
39    /// If the pointer is properly aligned to the target type, it will be
40    /// cast to the target type. Otherwise, `None` is returned.
41    ///
42    /// # Examples
43    ///
44    /// ```rust
45    /// #![feature(pointer_try_cast_aligned)]
46    ///
47    /// let mut x = 0u64;
48    ///
49    /// let aligned: *mut u64 = &mut x;
50    /// let unaligned = unsafe { aligned.byte_add(1) };
51    ///
52    /// assert!(aligned.try_cast_aligned::<u32>().is_some());
53    /// assert!(unaligned.try_cast_aligned::<u32>().is_none());
54    /// ```
55    #[unstable(feature = "pointer_try_cast_aligned", issue = "141221")]
56    #[must_use = "this returns the result of the operation, \
57                  without modifying the original"]
58    #[inline]
59    pub fn try_cast_aligned<U>(self) -> Option<*mut U> {
60        if self.is_aligned_to(align_of::<U>()) { Some(self.cast()) } else { None }
61    }
62
63    /// Uses the address value in a new pointer of another type.
64    ///
65    /// This operation will ignore the address part of its `meta` operand and discard existing
66    /// metadata of `self`. For pointers to a sized types (thin pointers), this has the same effect
67    /// as a simple cast. For pointers to an unsized type (fat pointers) this recombines the address
68    /// with new metadata such as slice lengths or `dyn`-vtable.
69    ///
70    /// The resulting pointer will have provenance of `self`. This operation is semantically the
71    /// same as creating a new pointer with the data pointer value of `self` but the metadata of
72    /// `meta`, being fat or thin depending on the `meta` operand.
73    ///
74    /// # Examples
75    ///
76    /// This function is primarily useful for enabling pointer arithmetic on potentially fat
77    /// pointers. The pointer is cast to a sized pointee to utilize offset operations and then
78    /// recombined with its own original metadata.
79    ///
80    /// ```
81    /// #![feature(set_ptr_value)]
82    /// # use core::fmt::Debug;
83    /// let mut arr: [i32; 3] = [1, 2, 3];
84    /// let mut ptr = arr.as_mut_ptr() as *mut dyn Debug;
85    /// let thin = ptr as *mut u8;
86    /// unsafe {
87    ///     ptr = thin.add(8).with_metadata_of(ptr);
88    ///     # assert_eq!(*(ptr as *mut i32), 3);
89    ///     println!("{:?}", &*ptr); // will print "3"
90    /// }
91    /// ```
92    ///
93    /// # *Incorrect* usage
94    ///
95    /// The provenance from pointers is *not* combined. The result must only be used to refer to the
96    /// address allowed by `self`.
97    ///
98    /// ```rust,no_run
99    /// #![feature(set_ptr_value)]
100    /// let mut x = 0u32;
101    /// let mut y = 1u32;
102    ///
103    /// let x = (&mut x) as *mut u32;
104    /// let y = (&mut y) as *mut u32;
105    ///
106    /// let offset = (x as usize - y as usize) / 4;
107    /// let bad = x.wrapping_add(offset).with_metadata_of(y);
108    ///
109    /// // This dereference is UB. The pointer only has provenance for `x` but points to `y`.
110    /// println!("{:?}", unsafe { &*bad });
111    /// ```
112    #[unstable(feature = "set_ptr_value", issue = "75091")]
113    #[must_use = "returns a new pointer rather than modifying its argument"]
114    #[inline]
115    pub const fn with_metadata_of<U>(self, meta: *const U) -> *mut U
116    where
117        U: PointeeSized,
118    {
119        from_raw_parts_mut::<U>(self as *mut (), metadata(meta))
120    }
121
122    /// Changes constness without changing the type.
123    ///
124    /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
125    /// refactored.
126    ///
127    /// While not strictly required (`*mut T` coerces to `*const T`), this is provided for symmetry
128    /// with [`cast_mut`] on `*const T` and may have documentation value if used instead of implicit
129    /// coercion.
130    ///
131    /// [`cast_mut`]: pointer::cast_mut
132    #[stable(feature = "ptr_const_cast", since = "1.65.0")]
133    #[rustc_const_stable(feature = "ptr_const_cast", since = "1.65.0")]
134    #[rustc_diagnostic_item = "ptr_cast_const"]
135    #[inline(always)]
136    #[ferrocene::prevalidated]
137    pub const fn cast_const(self) -> *const T {
138        self as _
139    }
140
141    #[doc = include_str!("./docs/addr.md")]
142    ///
143    /// [without_provenance]: without_provenance_mut
144    #[must_use]
145    #[inline(always)]
146    #[expect(clippy::transmutes_expressible_as_ptr_casts, reason = "implements pointer cast")]
147    #[stable(feature = "strict_provenance", since = "1.84.0")]
148    #[ferrocene::prevalidated]
149    pub fn addr(self) -> usize {
150        // A pointer-to-integer transmute currently has exactly the right semantics: it returns the
151        // address without exposing the provenance. Note that this is *not* a stable guarantee about
152        // transmute semantics, it relies on sysroot crates having special status.
153        // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
154        // provenance).
155        unsafe { mem::transmute(self.cast::<()>()) }
156    }
157
158    /// Exposes the ["provenance"][crate::ptr#provenance] part of the pointer for future use in
159    /// [`with_exposed_provenance_mut`] and returns the "address" portion.
160    ///
161    /// This is equivalent to `self as usize`, which semantically discards provenance information.
162    /// Furthermore, this (like the `as` cast) has the implicit side-effect of marking the
163    /// provenance as 'exposed', so on platforms that support it you can later call
164    /// [`with_exposed_provenance_mut`] to reconstitute the original pointer including its provenance.
165    ///
166    /// Due to its inherent ambiguity, [`with_exposed_provenance_mut`] may not be supported by tools
167    /// that help you to stay conformant with the Rust memory model. It is recommended to use
168    /// [Strict Provenance][crate::ptr#strict-provenance] APIs such as [`with_addr`][pointer::with_addr]
169    /// wherever possible, in which case [`addr`][pointer::addr] should be used instead of `expose_provenance`.
170    ///
171    /// On most platforms this will produce a value with the same bytes as the original pointer,
172    /// because all the bytes are dedicated to describing the address. Platforms which need to store
173    /// additional information in the pointer may not support this operation, since the 'expose'
174    /// side-effect which is required for [`with_exposed_provenance_mut`] to work is typically not
175    /// available.
176    ///
177    /// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
178    ///
179    /// [`with_exposed_provenance_mut`]: with_exposed_provenance_mut
180    #[inline(always)]
181    #[stable(feature = "exposed_provenance", since = "1.84.0")]
182    #[expect(implicit_provenance_casts, reason = "this *is* the replacement")]
183    pub fn expose_provenance(self) -> usize {
184        self.cast::<()>() as usize
185    }
186
187    /// Creates a new pointer with the given address and the [provenance][crate::ptr#provenance] of
188    /// `self`.
189    ///
190    /// This is similar to a `addr as *mut T` cast, but copies
191    /// the *provenance* of `self` to the new pointer.
192    /// This avoids the inherent ambiguity of the unary cast.
193    ///
194    /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
195    /// `self` to the given address, and therefore has all the same capabilities and restrictions.
196    ///
197    /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
198    #[must_use]
199    #[inline]
200    #[stable(feature = "strict_provenance", since = "1.84.0")]
201    pub fn with_addr(self, addr: usize) -> Self {
202        // This should probably be an intrinsic to avoid doing any sort of arithmetic, but
203        // meanwhile, we can implement it with `wrapping_offset`, which preserves the pointer's
204        // provenance.
205        let self_addr = self.addr() as isize;
206        let dest_addr = addr as isize;
207        let offset = dest_addr.wrapping_sub(self_addr);
208        self.wrapping_byte_offset(offset)
209    }
210
211    /// Creates a new pointer by mapping `self`'s address to a new one, preserving the original
212    /// pointer's [provenance][crate::ptr#provenance].
213    ///
214    /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
215    ///
216    /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
217    #[must_use]
218    #[inline]
219    #[stable(feature = "strict_provenance", since = "1.84.0")]
220    pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self {
221        self.with_addr(f(self.addr()))
222    }
223
224    /// Decompose a (possibly wide) pointer into its data pointer and metadata components.
225    ///
226    /// The pointer can be later reconstructed with [`from_raw_parts_mut`].
227    #[unstable(feature = "ptr_metadata", issue = "81513")]
228    #[inline]
229    #[ferrocene::prevalidated]
230    pub const fn to_raw_parts(self) -> (*mut (), <T as super::Pointee>::Metadata) {
231        (self.cast(), super::metadata(self))
232    }
233
234    #[doc = include_str!("./docs/as_ref.md")]
235    ///
236    /// ```
237    /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
238    ///
239    /// unsafe {
240    ///     let val_back = ptr.as_ref_unchecked();
241    ///     println!("We got back the value: {val_back}!");
242    /// }
243    /// ```
244    ///
245    /// # Examples
246    ///
247    /// ```
248    /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
249    ///
250    /// unsafe {
251    ///     if let Some(val_back) = ptr.as_ref() {
252    ///         println!("We got back the value: {val_back}!");
253    ///     }
254    /// }
255    /// ```
256    ///
257    /// # See Also
258    ///
259    /// For the mutable counterpart see [`as_mut`].
260    ///
261    /// [`is_null`]: #method.is_null-1
262    /// [`as_uninit_ref`]: #method.as_uninit_ref-1
263    /// [`as_ref_unchecked`]: #method.as_ref_unchecked-1
264    /// [`as_mut`]: #method.as_mut
265    #[stable(feature = "ptr_as_ref", since = "1.9.0")]
266    #[rustc_const_stable(feature = "const_ptr_is_null", since = "1.84.0")]
267    #[inline]
268    pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
269        // SAFETY: the caller must guarantee that `self` is valid for a
270        // reference if it isn't null.
271        if self.is_null() { None } else { unsafe { Some(&*self) } }
272    }
273
274    /// Returns a shared reference to the value behind the pointer.
275    /// If the pointer may be null or the value may be uninitialized, [`as_uninit_ref`] must be used instead.
276    /// If the pointer may be null, but the value is known to have been initialized, [`as_ref`] must be used instead.
277    ///
278    /// For the mutable counterpart see [`as_mut_unchecked`].
279    ///
280    /// [`as_ref`]: #method.as_ref
281    /// [`as_uninit_ref`]: #method.as_uninit_ref
282    /// [`as_mut_unchecked`]: #method.as_mut_unchecked
283    ///
284    /// # Safety
285    ///
286    /// When calling this method, you have to ensure that the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
287    ///
288    /// # Examples
289    ///
290    /// ```
291    /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
292    ///
293    /// unsafe {
294    ///     println!("We got back the value: {}!", ptr.as_ref_unchecked());
295    /// }
296    /// ```
297    #[stable(feature = "ptr_as_ref_unchecked", since = "1.95.0")]
298    #[rustc_const_stable(feature = "ptr_as_ref_unchecked", since = "1.95.0")]
299    #[inline]
300    #[must_use]
301    pub const unsafe fn as_ref_unchecked<'a>(self) -> &'a T {
302        // SAFETY: the caller must guarantee that `self` is valid for a reference
303        unsafe { &*self }
304    }
305
306    #[doc = include_str!("./docs/as_uninit_ref.md")]
307    ///
308    /// [`is_null`]: #method.is_null-1
309    /// [`as_ref`]: pointer#method.as_ref-1
310    ///
311    /// # See Also
312    /// For the mutable counterpart see [`as_uninit_mut`].
313    ///
314    /// [`as_uninit_mut`]: #method.as_uninit_mut
315    ///
316    /// # Examples
317    ///
318    /// ```
319    /// #![feature(ptr_as_uninit)]
320    ///
321    /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
322    ///
323    /// unsafe {
324    ///     if let Some(val_back) = ptr.as_uninit_ref() {
325    ///         println!("We got back the value: {}!", val_back.assume_init());
326    ///     }
327    /// }
328    /// ```
329    #[inline]
330    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
331    pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
332    where
333        T: Sized,
334    {
335        // SAFETY: the caller must guarantee that `self` meets all the
336        // requirements for a reference.
337        if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
338    }
339
340    #[doc = include_str!("./docs/offset.md")]
341    ///
342    /// Consider using [`wrapping_offset`](#method.wrapping_offset) instead if these constraints are
343    /// difficult to satisfy. The only advantage of this method is that it
344    /// enables more aggressive compiler optimizations.
345    ///
346    /// # Examples
347    ///
348    /// ```
349    /// let mut s = [1, 2, 3];
350    /// let ptr: *mut u32 = s.as_mut_ptr();
351    ///
352    /// unsafe {
353    ///     assert_eq!(2, *ptr.offset(1));
354    ///     assert_eq!(3, *ptr.offset(2));
355    /// }
356    /// ```
357    #[stable(feature = "rust1", since = "1.0.0")]
358    #[must_use = "returns a new pointer rather than modifying its argument"]
359    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
360    #[inline(always)]
361    #[track_caller]
362    #[ferrocene::prevalidated]
363    pub const unsafe fn offset(self, count: isize) -> *mut T
364    where
365        T: Sized,
366    {
367        #[inline]
368        #[rustc_allow_const_fn_unstable(const_eval_select)]
369        #[ferrocene::prevalidated]
370        const fn runtime_offset_nowrap(this: *const (), count: isize, size: usize) -> bool {
371            // We can use const_eval_select here because this is only for UB checks.
372            const_eval_select!(
373                @capture { this: *const (), count: isize, size: usize } -> bool:
374                if const {
375                    true
376                } else {
377                    // `size` is the size of a Rust type, so we know that
378                    // `size <= isize::MAX` and thus `as` cast here is not lossy.
379                    let Some(byte_offset) = count.checked_mul(size as isize) else {
380                        return false;
381                    };
382                    let (_, overflow) = this.addr().overflowing_add_signed(byte_offset);
383                    !overflow
384                }
385            )
386        }
387
388        ub_checks::assert_unsafe_precondition!(
389            check_language_ub,
390            "ptr::offset requires the address calculation to not overflow",
391            (
392                this: *const () = self as *const (),
393                count: isize = count,
394                size: usize = size_of::<T>(),
395            ) => runtime_offset_nowrap(this, count, size)
396        );
397
398        // SAFETY: the caller must uphold the safety contract for `offset`.
399        // The obtained pointer is valid for writes since the caller must
400        // guarantee that it points to the same allocation as `self`.
401        unsafe { intrinsics::offset(self, count) }
402    }
403
404    /// Adds a signed offset in bytes to a pointer.
405    ///
406    /// `count` is in units of **bytes**.
407    ///
408    /// This is purely a convenience for casting to a `u8` pointer and
409    /// using [offset][pointer::offset] on it. See that method for documentation
410    /// and safety requirements.
411    ///
412    /// For non-`Sized` pointees this operation changes only the data pointer,
413    /// leaving the metadata untouched.
414    #[must_use]
415    #[inline(always)]
416    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
417    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
418    #[track_caller]
419    pub const unsafe fn byte_offset(self, count: isize) -> Self {
420        // SAFETY: the caller must uphold the safety contract for `offset`.
421        unsafe { self.cast::<u8>().offset(count).with_metadata_of(self) }
422    }
423
424    /// Adds a signed offset to a pointer using wrapping arithmetic.
425    ///
426    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
427    /// offset of `3 * size_of::<T>()` bytes.
428    ///
429    /// # Safety
430    ///
431    /// This operation itself is always safe, but using the resulting pointer is not.
432    ///
433    /// The resulting pointer "remembers" the [allocation] that `self` points to
434    /// (this is called "[Provenance](ptr/index.html#provenance)").
435    /// The pointer must not be used to read or write other allocations.
436    ///
437    /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
438    /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
439    /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
440    /// `x` and `y` point into the same allocation.
441    ///
442    /// Compared to [`offset`], this method basically delays the requirement of staying within the
443    /// same allocation: [`offset`] is immediate Undefined Behavior when crossing object
444    /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
445    /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
446    /// can be optimized better and is thus preferable in performance-sensitive code.
447    ///
448    /// The delayed check only considers the value of the pointer that was dereferenced, not the
449    /// intermediate values used during the computation of the final result. For example,
450    /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
451    /// words, leaving the allocation and then re-entering it later is permitted.
452    ///
453    /// [`offset`]: #method.offset
454    /// [allocation]: crate::ptr#allocation
455    ///
456    /// # Examples
457    ///
458    /// ```
459    /// // Iterate using a raw pointer in increments of two elements
460    /// let mut data = [1u8, 2, 3, 4, 5];
461    /// let mut ptr: *mut u8 = data.as_mut_ptr();
462    /// let step = 2;
463    /// let end_rounded_up = ptr.wrapping_offset(6);
464    ///
465    /// while ptr != end_rounded_up {
466    ///     unsafe {
467    ///         *ptr = 0;
468    ///     }
469    ///     ptr = ptr.wrapping_offset(step);
470    /// }
471    /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
472    /// ```
473    #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
474    #[must_use = "returns a new pointer rather than modifying its argument"]
475    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
476    #[inline(always)]
477    #[ferrocene::prevalidated]
478    pub const fn wrapping_offset(self, count: isize) -> *mut T
479    where
480        T: Sized,
481    {
482        // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
483        unsafe { intrinsics::arith_offset(self, count) as *mut T }
484    }
485
486    /// Adds a signed offset in bytes to a pointer using wrapping arithmetic.
487    ///
488    /// `count` is in units of **bytes**.
489    ///
490    /// This is purely a convenience for casting to a `u8` pointer and
491    /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
492    /// for documentation.
493    ///
494    /// For non-`Sized` pointees this operation changes only the data pointer,
495    /// leaving the metadata untouched.
496    #[must_use]
497    #[inline(always)]
498    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
499    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
500    pub const fn wrapping_byte_offset(self, count: isize) -> Self {
501        self.cast::<u8>().wrapping_offset(count).with_metadata_of(self)
502    }
503
504    /// Masks out bits of the pointer according to a mask.
505    ///
506    /// This is convenience for `ptr.map_addr(|a| a & mask)`.
507    ///
508    /// For non-`Sized` pointees this operation changes only the data pointer,
509    /// leaving the metadata untouched.
510    ///
511    /// ## Examples
512    ///
513    /// ```
514    /// #![feature(ptr_mask)]
515    /// let mut v = 17_u32;
516    /// let ptr: *mut u32 = &mut v;
517    ///
518    /// // `u32` is 4 bytes aligned,
519    /// // which means that lower 2 bits are always 0.
520    /// let tag_mask = 0b11;
521    /// let ptr_mask = !tag_mask;
522    ///
523    /// // We can store something in these lower bits
524    /// let tagged_ptr = ptr.map_addr(|a| a | 0b10);
525    ///
526    /// // Get the "tag" back
527    /// let tag = tagged_ptr.addr() & tag_mask;
528    /// assert_eq!(tag, 0b10);
529    ///
530    /// // Note that `tagged_ptr` is unaligned, it's UB to read from/write to it.
531    /// // To get original pointer `mask` can be used:
532    /// let masked_ptr = tagged_ptr.mask(ptr_mask);
533    /// assert_eq!(unsafe { *masked_ptr }, 17);
534    ///
535    /// unsafe { *masked_ptr = 0 };
536    /// assert_eq!(v, 0);
537    /// ```
538    #[unstable(feature = "ptr_mask", issue = "98290")]
539    #[must_use = "returns a new pointer rather than modifying its argument"]
540    #[inline(always)]
541    pub fn mask(self, mask: usize) -> *mut T {
542        intrinsics::ptr_mask(self.cast::<()>(), mask).cast_mut().with_metadata_of(self)
543    }
544
545    /// Returns `None` if the pointer is null, or else returns a unique reference to
546    /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
547    /// must be used instead. If the value is known to be non-null, [`as_mut_unchecked`]
548    /// can be used instead.
549    ///
550    /// For the shared counterpart see [`as_ref`].
551    ///
552    /// [`as_uninit_mut`]: #method.as_uninit_mut
553    /// [`as_mut_unchecked`]: #method.as_mut_unchecked
554    /// [`as_ref`]: pointer#method.as_ref-1
555    ///
556    /// # Safety
557    ///
558    /// When calling this method, you have to ensure that *either*
559    /// the pointer is null *or*
560    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
561    ///
562    /// # Panics during const evaluation
563    ///
564    /// This method will panic during const evaluation if the pointer cannot be
565    /// determined to be null or not. See [`is_null`] for more information.
566    ///
567    /// [`is_null`]: #method.is_null-1
568    ///
569    /// # Examples
570    ///
571    /// ```
572    /// let mut s = [1, 2, 3];
573    /// let ptr: *mut u32 = s.as_mut_ptr();
574    /// let first_value = unsafe { ptr.as_mut().unwrap() };
575    /// *first_value = 4;
576    /// # assert_eq!(s, [4, 2, 3]);
577    /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
578    /// ```
579    ///
580    /// # Null-unchecked version
581    ///
582    /// If you are sure the pointer can never be null, you can use `as_mut_unchecked` which returns
583    /// `&mut T` instead of `Option<&mut T>`.
584    ///
585    /// ```
586    /// let mut s = [1, 2, 3];
587    /// let ptr: *mut u32 = s.as_mut_ptr();
588    /// let first_value = unsafe { ptr.as_mut_unchecked() };
589    /// *first_value = 4;
590    /// # assert_eq!(s, [4, 2, 3]);
591    /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
592    /// ```
593    #[stable(feature = "ptr_as_ref", since = "1.9.0")]
594    #[rustc_const_stable(feature = "const_ptr_is_null", since = "1.84.0")]
595    #[inline]
596    #[ferrocene::prevalidated]
597    pub const unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
598        // SAFETY: the caller must guarantee that `self` is be valid for
599        // a mutable reference if it isn't null.
600        if self.is_null() { None } else { unsafe { Some(&mut *self) } }
601    }
602
603    /// Returns a unique reference to the value behind the pointer.
604    /// If the pointer may be null or the value may be uninitialized, [`as_uninit_mut`] must be used instead.
605    /// If the pointer may be null, but the value is known to have been initialized, [`as_mut`] must be used instead.
606    ///
607    /// For the shared counterpart see [`as_ref_unchecked`].
608    ///
609    /// [`as_mut`]: #method.as_mut
610    /// [`as_uninit_mut`]: #method.as_uninit_mut
611    /// [`as_ref_unchecked`]: #method.as_ref_unchecked
612    ///
613    /// # Safety
614    ///
615    /// When calling this method, you have to ensure that
616    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
617    ///
618    /// # Examples
619    ///
620    /// ```
621    /// let mut s = [1, 2, 3];
622    /// let ptr: *mut u32 = s.as_mut_ptr();
623    /// let first_value = unsafe { ptr.as_mut_unchecked() };
624    /// *first_value = 4;
625    /// # assert_eq!(s, [4, 2, 3]);
626    /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
627    /// ```
628    #[stable(feature = "ptr_as_ref_unchecked", since = "1.95.0")]
629    #[rustc_const_stable(feature = "ptr_as_ref_unchecked", since = "1.95.0")]
630    #[inline]
631    #[must_use]
632    pub const unsafe fn as_mut_unchecked<'a>(self) -> &'a mut T {
633        // SAFETY: the caller must guarantee that `self` is valid for a reference
634        unsafe { &mut *self }
635    }
636
637    /// Returns `None` if the pointer is null, or else returns a unique reference to
638    /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
639    /// that the value has to be initialized.
640    ///
641    /// For the shared counterpart see [`as_uninit_ref`].
642    ///
643    /// [`as_mut`]: #method.as_mut
644    /// [`as_uninit_ref`]: pointer#method.as_uninit_ref-1
645    ///
646    /// # Safety
647    ///
648    /// When calling this method, you have to ensure that *either* the pointer is null *or*
649    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
650    /// Note that because the created reference is to `MaybeUninit<T>`, the
651    /// source pointer can point to uninitialized memory.
652    ///
653    /// # Panics during const evaluation
654    ///
655    /// This method will panic during const evaluation if the pointer cannot be
656    /// determined to be null or not. See [`is_null`] for more information.
657    ///
658    /// [`is_null`]: #method.is_null-1
659    #[inline]
660    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
661    pub const unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
662    where
663        T: Sized,
664    {
665        // SAFETY: the caller must guarantee that `self` meets all the
666        // requirements for a reference.
667        if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
668    }
669
670    /// Returns whether two pointers are guaranteed to be equal.
671    ///
672    /// At runtime this function behaves like `Some(self == other)`.
673    /// However, in some contexts (e.g., compile-time evaluation),
674    /// it is not always possible to determine equality of two pointers, so this function may
675    /// spuriously return `None` for pointers that later actually turn out to have its equality known.
676    /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
677    ///
678    /// The return value may change from `Some` to `None` and vice versa depending on the compiler
679    /// version and unsafe code must not
680    /// rely on the result of this function for soundness. It is suggested to only use this function
681    /// for performance optimizations where spurious `None` return values by this function do not
682    /// affect the outcome, but just the performance.
683    /// The consequences of using this method to make runtime and compile-time code behave
684    /// differently have not been explored. This method should not be used to introduce such
685    /// differences, and it should also not be stabilized before we have a better understanding
686    /// of this issue.
687    #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
688    #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
689    #[inline]
690    pub const fn guaranteed_eq(self, other: *mut T) -> Option<bool>
691    where
692        T: Sized,
693    {
694        (self as *const T).guaranteed_eq(other as _)
695    }
696
697    /// Returns whether two pointers are guaranteed to be inequal.
698    ///
699    /// At runtime this function behaves like `Some(self != other)`.
700    /// However, in some contexts (e.g., compile-time evaluation),
701    /// it is not always possible to determine inequality of two pointers, so this function may
702    /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
703    /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
704    ///
705    /// The return value may change from `Some` to `None` and vice versa depending on the compiler
706    /// version and unsafe code must not
707    /// rely on the result of this function for soundness. It is suggested to only use this function
708    /// for performance optimizations where spurious `None` return values by this function do not
709    /// affect the outcome, but just the performance.
710    /// The consequences of using this method to make runtime and compile-time code behave
711    /// differently have not been explored. This method should not be used to introduce such
712    /// differences, and it should also not be stabilized before we have a better understanding
713    /// of this issue.
714    #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
715    #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
716    #[inline]
717    pub const fn guaranteed_ne(self, other: *mut T) -> Option<bool>
718    where
719        T: Sized,
720    {
721        (self as *const T).guaranteed_ne(other as _)
722    }
723
724    /// Calculates the distance between two pointers within the same allocation. The returned value is in
725    /// units of T: the distance in bytes divided by `size_of::<T>()`.
726    ///
727    /// This is equivalent to `(self as isize - origin as isize) / (size_of::<T>() as isize)`,
728    /// except that it has a lot more opportunities for UB, in exchange for the compiler
729    /// better understanding what you are doing.
730    ///
731    /// The primary motivation of this method is for computing the `len` of an array/slice
732    /// of `T` that you are currently representing as a "start" and "end" pointer
733    /// (and "end" is "one past the end" of the array).
734    /// In that case, `end.offset_from(start)` gets you the length of the array.
735    ///
736    /// All of the following safety requirements are trivially satisfied for this usecase.
737    ///
738    /// [`offset`]: pointer#method.offset-1
739    ///
740    /// # Safety
741    ///
742    /// If any of the following conditions are violated, the result is Undefined Behavior:
743    ///
744    /// * `self` and `origin` must either
745    ///
746    ///   * point to the same address, or
747    ///   * both be [derived from][crate::ptr#provenance] a pointer to the same [allocation], and the memory range between
748    ///     the two pointers must be in bounds of that object. (See below for an example.)
749    ///
750    /// * The distance between the pointers, in bytes, must be an exact multiple
751    ///   of the size of `T`.
752    ///
753    /// As a consequence, the absolute distance between the pointers, in bytes, computed on
754    /// mathematical integers (without "wrapping around"), cannot overflow an `isize`. This is
755    /// implied by the in-bounds requirement, and the fact that no allocation can be larger
756    /// than `isize::MAX` bytes.
757    ///
758    /// The requirement for pointers to be derived from the same allocation is primarily
759    /// needed for `const`-compatibility: the distance between pointers into *different* allocated
760    /// objects is not known at compile-time. However, the requirement also exists at
761    /// runtime and may be exploited by optimizations. If you wish to compute the difference between
762    /// pointers that are not guaranteed to be from the same allocation, use
763    /// `(self.addr() as isize - origin.addr() as isize) / size_of::<T>()`.
764    ///
765    /// [`add`]: #method.add
766    /// [allocation]: crate::ptr#allocation
767    ///
768    /// # Panics
769    ///
770    /// This function panics if `T` is a Zero-Sized Type ("ZST").
771    ///
772    /// # Examples
773    ///
774    /// Basic usage:
775    ///
776    /// ```
777    /// let mut a = [0; 5];
778    /// let ptr1: *mut i32 = &mut a[1];
779    /// let ptr2: *mut i32 = &mut a[3];
780    /// unsafe {
781    ///     assert_eq!(ptr2.offset_from(ptr1), 2);
782    ///     assert_eq!(ptr1.offset_from(ptr2), -2);
783    ///     assert_eq!(ptr1.offset(2), ptr2);
784    ///     assert_eq!(ptr2.offset(-2), ptr1);
785    /// }
786    /// ```
787    ///
788    /// *Incorrect* usage:
789    ///
790    /// ```rust,no_run
791    /// let ptr1 = Box::into_raw(Box::new(0u8));
792    /// let ptr2 = Box::into_raw(Box::new(1u8));
793    /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
794    /// // Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.
795    /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff).wrapping_offset(1);
796    /// assert_eq!(ptr2 as usize, ptr2_other as usize);
797    /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
798    /// // computing their offset is undefined behavior, even though
799    /// // they point to addresses that are in-bounds of the same object!
800    /// unsafe {
801    ///     let one = ptr2_other.offset_from(ptr2); // Undefined Behavior! ⚠️
802    /// }
803    /// ```
804    #[stable(feature = "ptr_offset_from", since = "1.47.0")]
805    #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
806    #[inline(always)]
807    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
808    pub const unsafe fn offset_from(self, origin: *const T) -> isize
809    where
810        T: Sized,
811    {
812        // SAFETY: the caller must uphold the safety contract for `offset_from`.
813        unsafe { (self as *const T).offset_from(origin) }
814    }
815
816    /// Calculates the distance between two pointers within the same allocation. The returned value is in
817    /// units of **bytes**.
818    ///
819    /// This is purely a convenience for casting to a `u8` pointer and
820    /// using [`offset_from`][pointer::offset_from] on it. See that method for
821    /// documentation and safety requirements.
822    ///
823    /// For non-`Sized` pointees this operation considers only the data pointers,
824    /// ignoring the metadata.
825    #[inline(always)]
826    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
827    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
828    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
829    pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: *const U) -> isize {
830        // SAFETY: the caller must uphold the safety contract for `offset_from`.
831        unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
832    }
833
834    /// Calculates the distance between two pointers within the same allocation, *where it's known that
835    /// `self` is equal to or greater than `origin`*. The returned value is in
836    /// units of T: the distance in bytes is divided by `size_of::<T>()`.
837    ///
838    /// This computes the same value that [`offset_from`](#method.offset_from)
839    /// would compute, but with the added precondition that the offset is
840    /// guaranteed to be non-negative.  This method is equivalent to
841    /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`,
842    /// but it provides slightly more information to the optimizer, which can
843    /// sometimes allow it to optimize slightly better with some backends.
844    ///
845    /// This method can be thought of as recovering the `count` that was passed
846    /// to [`add`](#method.add) (or, with the parameters in the other order,
847    /// to [`sub`](#method.sub)).  The following are all equivalent, assuming
848    /// that their safety preconditions are met:
849    /// ```rust
850    /// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool { unsafe {
851    /// ptr.offset_from_unsigned(origin) == count
852    /// # &&
853    /// origin.add(count) == ptr
854    /// # &&
855    /// ptr.sub(count) == origin
856    /// # } }
857    /// ```
858    ///
859    /// # Safety
860    ///
861    /// - The distance between the pointers must be non-negative (`self >= origin`)
862    ///
863    /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
864    ///   apply to this method as well; see it for the full details.
865    ///
866    /// Importantly, despite the return type of this method being able to represent
867    /// a larger offset, it's still *not permitted* to pass pointers which differ
868    /// by more than `isize::MAX` *bytes*.  As such, the result of this method will
869    /// always be less than or equal to `isize::MAX as usize`.
870    ///
871    /// # Panics
872    ///
873    /// This function panics if `T` is a Zero-Sized Type ("ZST").
874    ///
875    /// # Examples
876    ///
877    /// ```
878    /// let mut a = [0; 5];
879    /// let p: *mut i32 = a.as_mut_ptr();
880    /// unsafe {
881    ///     let ptr1: *mut i32 = p.add(1);
882    ///     let ptr2: *mut i32 = p.add(3);
883    ///
884    ///     assert_eq!(ptr2.offset_from_unsigned(ptr1), 2);
885    ///     assert_eq!(ptr1.add(2), ptr2);
886    ///     assert_eq!(ptr2.sub(2), ptr1);
887    ///     assert_eq!(ptr2.offset_from_unsigned(ptr2), 0);
888    /// }
889    ///
890    /// // This would be incorrect, as the pointers are not correctly ordered:
891    /// // ptr1.offset_from(ptr2)
892    /// ```
893    #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
894    #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
895    #[inline]
896    #[track_caller]
897    #[ferrocene::prevalidated]
898    pub const unsafe fn offset_from_unsigned(self, origin: *const T) -> usize
899    where
900        T: Sized,
901    {
902        // SAFETY: the caller must uphold the safety contract for `offset_from_unsigned`.
903        unsafe { (self as *const T).offset_from_unsigned(origin) }
904    }
905
906    /// Calculates the distance between two pointers within the same allocation, *where it's known that
907    /// `self` is equal to or greater than `origin`*. The returned value is in
908    /// units of **bytes**.
909    ///
910    /// This is purely a convenience for casting to a `u8` pointer and
911    /// using [`offset_from_unsigned`][pointer::offset_from_unsigned] on it.
912    /// See that method for documentation and safety requirements.
913    ///
914    /// For non-`Sized` pointees this operation considers only the data pointers,
915    /// ignoring the metadata.
916    #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
917    #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
918    #[inline]
919    #[track_caller]
920    pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: *mut U) -> usize {
921        // SAFETY: the caller must uphold the safety contract for `byte_offset_from_unsigned`.
922        unsafe { (self as *const T).byte_offset_from_unsigned(origin) }
923    }
924
925    #[doc = include_str!("./docs/add.md")]
926    ///
927    /// Consider using [`wrapping_add`](#method.wrapping_add) instead if these constraints are
928    /// difficult to satisfy. The only advantage of this method is that it
929    /// enables more aggressive compiler optimizations.
930    ///
931    /// # Examples
932    ///
933    /// ```
934    /// let mut s: String = "123".to_string();
935    /// let ptr: *mut u8 = s.as_mut_ptr();
936    ///
937    /// unsafe {
938    ///     assert_eq!('2', *ptr.add(1) as char);
939    ///     assert_eq!('3', *ptr.add(2) as char);
940    /// }
941    /// ```
942    #[stable(feature = "pointer_methods", since = "1.26.0")]
943    #[must_use = "returns a new pointer rather than modifying its argument"]
944    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
945    #[inline(always)]
946    #[track_caller]
947    #[ferrocene::prevalidated]
948    pub const unsafe fn add(self, count: usize) -> Self
949    where
950        T: Sized,
951    {
952        #[cfg(debug_assertions)]
953        #[inline]
954        #[rustc_allow_const_fn_unstable(const_eval_select)]
955        #[ferrocene::prevalidated]
956        const fn runtime_add_nowrap(this: *const (), count: usize, size: usize) -> bool {
957            const_eval_select!(
958                @capture { this: *const (), count: usize, size: usize } -> bool:
959                if const {
960                    true
961                } else {
962                    let Some(byte_offset) = count.checked_mul(size) else {
963                        return false;
964                    };
965                    let (_, overflow) = this.addr().overflowing_add(byte_offset);
966                    byte_offset <= (isize::MAX as usize) && !overflow
967                }
968            )
969        }
970
971        #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
972        ub_checks::assert_unsafe_precondition!(
973            check_language_ub,
974            "ptr::add requires that the address calculation does not overflow",
975            (
976                this: *const () = self as *const (),
977                count: usize = count,
978                size: usize = size_of::<T>(),
979            ) => runtime_add_nowrap(this, count, size)
980        );
981
982        // SAFETY: the caller must uphold the safety contract for `offset`.
983        unsafe { intrinsics::offset(self, count) }
984    }
985
986    /// Adds an unsigned offset in bytes to a pointer.
987    ///
988    /// `count` is in units of bytes.
989    ///
990    /// This is purely a convenience for casting to a `u8` pointer and
991    /// using [add][pointer::add] on it. See that method for documentation
992    /// and safety requirements.
993    ///
994    /// For non-`Sized` pointees this operation changes only the data pointer,
995    /// leaving the metadata untouched.
996    #[must_use]
997    #[inline(always)]
998    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
999    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1000    #[track_caller]
1001    pub const unsafe fn byte_add(self, count: usize) -> Self {
1002        // SAFETY: the caller must uphold the safety contract for `add`.
1003        unsafe { self.cast::<u8>().add(count).with_metadata_of(self) }
1004    }
1005
1006    #[doc = include_str!("./docs/sub.md")]
1007    ///
1008    /// Consider using [`wrapping_sub`](#method.wrapping_sub) instead if these constraints are
1009    /// difficult to satisfy. The only advantage of this method is that it
1010    /// enables more aggressive compiler optimizations.
1011    ///
1012    /// # Examples
1013    ///
1014    /// ```
1015    /// let s: &str = "123";
1016    ///
1017    /// unsafe {
1018    ///     let end: *const u8 = s.as_ptr().add(3);
1019    ///     assert_eq!('3', *end.sub(1) as char);
1020    ///     assert_eq!('2', *end.sub(2) as char);
1021    /// }
1022    /// ```
1023    #[stable(feature = "pointer_methods", since = "1.26.0")]
1024    #[must_use = "returns a new pointer rather than modifying its argument"]
1025    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1026    #[inline(always)]
1027    #[track_caller]
1028    #[ferrocene::prevalidated]
1029    pub const unsafe fn sub(self, count: usize) -> Self
1030    where
1031        T: Sized,
1032    {
1033        #[cfg(debug_assertions)]
1034        #[inline]
1035        #[rustc_allow_const_fn_unstable(const_eval_select)]
1036        #[ferrocene::prevalidated]
1037        const fn runtime_sub_nowrap(this: *const (), count: usize, size: usize) -> bool {
1038            const_eval_select!(
1039                @capture { this: *const (), count: usize, size: usize } -> bool:
1040                if const {
1041                    true
1042                } else {
1043                    let Some(byte_offset) = count.checked_mul(size) else {
1044                        return false;
1045                    };
1046                    byte_offset <= (isize::MAX as usize) && this.addr() >= byte_offset
1047                }
1048            )
1049        }
1050
1051        #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
1052        ub_checks::assert_unsafe_precondition!(
1053            check_language_ub,
1054            "ptr::sub requires that the address calculation does not overflow",
1055            (
1056                this: *const () = self as *const (),
1057                count: usize = count,
1058                size: usize = size_of::<T>(),
1059            ) => runtime_sub_nowrap(this, count, size)
1060        );
1061
1062        if T::IS_ZST {
1063            // Pointer arithmetic does nothing when the pointee is a ZST.
1064            self
1065        } else {
1066            // SAFETY: the caller must uphold the safety contract for `offset`.
1067            // Because the pointee is *not* a ZST, that means that `count` is
1068            // at most `isize::MAX`, and thus the negation cannot overflow.
1069            unsafe { intrinsics::offset(self, intrinsics::unchecked_sub(0, count as isize)) }
1070        }
1071    }
1072
1073    /// Subtracts an unsigned offset in bytes from a pointer.
1074    ///
1075    /// `count` is in units of bytes.
1076    ///
1077    /// This is purely a convenience for casting to a `u8` pointer and
1078    /// using [sub][pointer::sub] on it. See that method for documentation
1079    /// and safety requirements.
1080    ///
1081    /// For non-`Sized` pointees this operation changes only the data pointer,
1082    /// leaving the metadata untouched.
1083    #[must_use]
1084    #[inline(always)]
1085    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1086    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1087    #[track_caller]
1088    pub const unsafe fn byte_sub(self, count: usize) -> Self {
1089        // SAFETY: the caller must uphold the safety contract for `sub`.
1090        unsafe { self.cast::<u8>().sub(count).with_metadata_of(self) }
1091    }
1092
1093    /// Adds an unsigned offset to a pointer using wrapping arithmetic.
1094    ///
1095    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1096    /// offset of `3 * size_of::<T>()` bytes.
1097    ///
1098    /// # Safety
1099    ///
1100    /// This operation itself is always safe, but using the resulting pointer is not.
1101    ///
1102    /// The resulting pointer "remembers" the [allocation] that `self` points to; it must not
1103    /// be used to read or write other allocations.
1104    ///
1105    /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1106    /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1107    /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1108    /// `x` and `y` point into the same allocation.
1109    ///
1110    /// Compared to [`add`], this method basically delays the requirement of staying within the
1111    /// same allocation: [`add`] is immediate Undefined Behavior when crossing object
1112    /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1113    /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1114    /// can be optimized better and is thus preferable in performance-sensitive code.
1115    ///
1116    /// The delayed check only considers the value of the pointer that was dereferenced, not the
1117    /// intermediate values used during the computation of the final result. For example,
1118    /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1119    /// allocation and then re-entering it later is permitted.
1120    ///
1121    /// [`add`]: #method.add
1122    /// [allocation]: crate::ptr#allocation
1123    ///
1124    /// # Examples
1125    ///
1126    /// ```
1127    /// // Iterate using a raw pointer in increments of two elements
1128    /// let data = [1u8, 2, 3, 4, 5];
1129    /// let mut ptr: *const u8 = data.as_ptr();
1130    /// let step = 2;
1131    /// let end_rounded_up = ptr.wrapping_add(6);
1132    ///
1133    /// // This loop prints "1, 3, 5, "
1134    /// while ptr != end_rounded_up {
1135    ///     unsafe {
1136    ///         print!("{}, ", *ptr);
1137    ///     }
1138    ///     ptr = ptr.wrapping_add(step);
1139    /// }
1140    /// ```
1141    #[stable(feature = "pointer_methods", since = "1.26.0")]
1142    #[must_use = "returns a new pointer rather than modifying its argument"]
1143    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1144    #[allow(clippy::ptr_offset_with_cast)]
1145    #[inline(always)]
1146    #[ferrocene::prevalidated]
1147    pub const fn wrapping_add(self, count: usize) -> Self
1148    where
1149        T: Sized,
1150    {
1151        self.wrapping_offset(count as isize)
1152    }
1153
1154    /// Adds an unsigned offset in bytes to a pointer using wrapping arithmetic.
1155    ///
1156    /// `count` is in units of bytes.
1157    ///
1158    /// This is purely a convenience for casting to a `u8` pointer and
1159    /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1160    ///
1161    /// For non-`Sized` pointees this operation changes only the data pointer,
1162    /// leaving the metadata untouched.
1163    #[must_use]
1164    #[inline(always)]
1165    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1166    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1167    pub const fn wrapping_byte_add(self, count: usize) -> Self {
1168        self.cast::<u8>().wrapping_add(count).with_metadata_of(self)
1169    }
1170
1171    /// Subtracts an unsigned offset from a pointer using wrapping arithmetic.
1172    ///
1173    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1174    /// offset of `3 * size_of::<T>()` bytes.
1175    ///
1176    /// # Safety
1177    ///
1178    /// This operation itself is always safe, but using the resulting pointer is not.
1179    ///
1180    /// The resulting pointer "remembers" the [allocation] that `self` points to; it must not
1181    /// be used to read or write other allocations.
1182    ///
1183    /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1184    /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1185    /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1186    /// `x` and `y` point into the same allocation.
1187    ///
1188    /// Compared to [`sub`], this method basically delays the requirement of staying within the
1189    /// same allocation: [`sub`] is immediate Undefined Behavior when crossing object
1190    /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1191    /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1192    /// can be optimized better and is thus preferable in performance-sensitive code.
1193    ///
1194    /// The delayed check only considers the value of the pointer that was dereferenced, not the
1195    /// intermediate values used during the computation of the final result. For example,
1196    /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1197    /// allocation and then re-entering it later is permitted.
1198    ///
1199    /// [`sub`]: #method.sub
1200    /// [allocation]: crate::ptr#allocation
1201    ///
1202    /// # Examples
1203    ///
1204    /// ```
1205    /// // Iterate using a raw pointer in increments of two elements (backwards)
1206    /// let data = [1u8, 2, 3, 4, 5];
1207    /// let mut ptr: *const u8 = data.as_ptr();
1208    /// let start_rounded_down = ptr.wrapping_sub(2);
1209    /// ptr = ptr.wrapping_add(4);
1210    /// let step = 2;
1211    /// // This loop prints "5, 3, 1, "
1212    /// while ptr != start_rounded_down {
1213    ///     unsafe {
1214    ///         print!("{}, ", *ptr);
1215    ///     }
1216    ///     ptr = ptr.wrapping_sub(step);
1217    /// }
1218    /// ```
1219    #[stable(feature = "pointer_methods", since = "1.26.0")]
1220    #[must_use = "returns a new pointer rather than modifying its argument"]
1221    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1222    #[inline(always)]
1223    pub const fn wrapping_sub(self, count: usize) -> Self
1224    where
1225        T: Sized,
1226    {
1227        self.wrapping_offset((count as isize).wrapping_neg())
1228    }
1229
1230    /// Subtracts an unsigned offset in bytes from a pointer using wrapping arithmetic.
1231    ///
1232    /// `count` is in units of bytes.
1233    ///
1234    /// This is purely a convenience for casting to a `u8` pointer and
1235    /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1236    ///
1237    /// For non-`Sized` pointees this operation changes only the data pointer,
1238    /// leaving the metadata untouched.
1239    #[must_use]
1240    #[inline(always)]
1241    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1242    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1243    pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1244        self.cast::<u8>().wrapping_sub(count).with_metadata_of(self)
1245    }
1246
1247    /// Reads the value from `self` without moving it. This leaves the
1248    /// memory in `self` unchanged.
1249    ///
1250    /// See [`ptr::read`] for safety concerns and examples.
1251    ///
1252    /// [`ptr::read`]: crate::ptr::read()
1253    #[stable(feature = "pointer_methods", since = "1.26.0")]
1254    #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1255    #[inline(always)]
1256    #[track_caller]
1257    #[ferrocene::prevalidated]
1258    pub const unsafe fn read(self) -> T
1259    where
1260        T: Sized,
1261    {
1262        // SAFETY: the caller must uphold the safety contract for ``.
1263        unsafe { read(self) }
1264    }
1265
1266    /// Performs a volatile read of the value from `self` without moving it. This
1267    /// leaves the memory in `self` unchanged.
1268    ///
1269    /// Volatile operations are intended to act on I/O memory, and are guaranteed
1270    /// to not be elided or reordered by the compiler across other volatile
1271    /// operations.
1272    ///
1273    /// See [`ptr::read_volatile`] for safety concerns and examples.
1274    ///
1275    /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1276    #[stable(feature = "pointer_methods", since = "1.26.0")]
1277    #[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
1278    #[inline(always)]
1279    #[track_caller]
1280    pub const unsafe fn read_volatile(self) -> T
1281    where
1282        T: Sized,
1283    {
1284        // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1285        unsafe { read_volatile(self) }
1286    }
1287
1288    /// Reads the value from `self` without moving it. This leaves the
1289    /// memory in `self` unchanged.
1290    ///
1291    /// Unlike `read`, the pointer may be unaligned.
1292    ///
1293    /// See [`ptr::read_unaligned`] for safety concerns and examples.
1294    ///
1295    /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1296    #[stable(feature = "pointer_methods", since = "1.26.0")]
1297    #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1298    #[inline(always)]
1299    #[track_caller]
1300    pub const unsafe fn read_unaligned(self) -> T
1301    where
1302        T: Sized,
1303    {
1304        // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1305        unsafe { read_unaligned(self) }
1306    }
1307
1308    /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1309    /// and destination may overlap.
1310    ///
1311    /// NOTE: this has the *same* argument order as [`ptr::copy`].
1312    ///
1313    /// See [`ptr::copy`] for safety concerns and examples.
1314    ///
1315    /// [`ptr::copy`]: crate::ptr::copy()
1316    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1317    #[stable(feature = "pointer_methods", since = "1.26.0")]
1318    #[inline(always)]
1319    #[track_caller]
1320    pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1321    where
1322        T: Sized,
1323    {
1324        // SAFETY: the caller must uphold the safety contract for `copy`.
1325        unsafe { copy(self, dest, count) }
1326    }
1327
1328    /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1329    /// and destination may *not* overlap.
1330    ///
1331    /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1332    ///
1333    /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1334    ///
1335    /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1336    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1337    #[stable(feature = "pointer_methods", since = "1.26.0")]
1338    #[inline(always)]
1339    #[track_caller]
1340    pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1341    where
1342        T: Sized,
1343    {
1344        // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1345        unsafe { copy_nonoverlapping(self, dest, count) }
1346    }
1347
1348    /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
1349    /// and destination may overlap.
1350    ///
1351    /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1352    ///
1353    /// See [`ptr::copy`] for safety concerns and examples.
1354    ///
1355    /// [`ptr::copy`]: crate::ptr::copy()
1356    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1357    #[stable(feature = "pointer_methods", since = "1.26.0")]
1358    #[inline(always)]
1359    #[track_caller]
1360    pub const unsafe fn copy_from(self, src: *const T, count: usize)
1361    where
1362        T: Sized,
1363    {
1364        // SAFETY: the caller must uphold the safety contract for `copy`.
1365        unsafe { copy(src, self, count) }
1366    }
1367
1368    /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
1369    /// and destination may *not* overlap.
1370    ///
1371    /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1372    ///
1373    /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1374    ///
1375    /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1376    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1377    #[stable(feature = "pointer_methods", since = "1.26.0")]
1378    #[inline(always)]
1379    #[track_caller]
1380    pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1381    where
1382        T: Sized,
1383    {
1384        // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1385        unsafe { copy_nonoverlapping(src, self, count) }
1386    }
1387
1388    /// Executes the destructor (if any) of the pointed-to value.
1389    ///
1390    /// See [`ptr::drop_in_place`] for safety concerns and examples.
1391    ///
1392    /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1393    #[stable(feature = "pointer_methods", since = "1.26.0")]
1394    #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
1395    #[rustc_diagnostic_item = "ptr_drop_in_place_self"]
1396    #[inline(always)]
1397    #[ferrocene::prevalidated]
1398    pub const unsafe fn drop_in_place(self)
1399    where
1400        T: [const] Destruct,
1401    {
1402        // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1403        unsafe { drop_in_place(self) }
1404    }
1405
1406    /// Overwrites a memory location with the given value without reading or
1407    /// dropping the old value.
1408    ///
1409    /// See [`ptr::write`] for safety concerns and examples.
1410    ///
1411    /// [`ptr::write`]: crate::ptr::write()
1412    #[stable(feature = "pointer_methods", since = "1.26.0")]
1413    #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1414    #[inline(always)]
1415    #[track_caller]
1416    #[ferrocene::prevalidated]
1417    pub const unsafe fn write(self, val: T)
1418    where
1419        T: Sized,
1420    {
1421        // SAFETY: the caller must uphold the safety contract for `write`.
1422        unsafe { write(self, val) }
1423    }
1424
1425    /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1426    /// bytes of memory starting at `self` to `val`.
1427    ///
1428    /// See [`ptr::write_bytes`] for safety concerns and examples.
1429    ///
1430    /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1431    #[doc(alias = "memset")]
1432    #[stable(feature = "pointer_methods", since = "1.26.0")]
1433    #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1434    #[inline(always)]
1435    #[track_caller]
1436    #[ferrocene::prevalidated]
1437    pub const unsafe fn write_bytes(self, val: u8, count: usize)
1438    where
1439        T: Sized,
1440    {
1441        // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1442        unsafe { write_bytes(self, val, count) }
1443    }
1444
1445    /// Performs a volatile write of a memory location with the given value without
1446    /// reading or dropping the old value.
1447    ///
1448    /// Volatile operations are intended to act on I/O memory, and are guaranteed
1449    /// to not be elided or reordered by the compiler across other volatile
1450    /// operations.
1451    ///
1452    /// See [`ptr::write_volatile`] for safety concerns and examples.
1453    ///
1454    /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1455    #[stable(feature = "pointer_methods", since = "1.26.0")]
1456    #[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
1457    #[inline(always)]
1458    #[track_caller]
1459    pub const unsafe fn write_volatile(self, val: T)
1460    where
1461        T: Sized,
1462    {
1463        // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1464        unsafe { write_volatile(self, val) }
1465    }
1466
1467    /// Overwrites a memory location with the given value without reading or
1468    /// dropping the old value.
1469    ///
1470    /// Unlike `write`, the pointer may be unaligned.
1471    ///
1472    /// See [`ptr::write_unaligned`] for safety concerns and examples.
1473    ///
1474    /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1475    #[stable(feature = "pointer_methods", since = "1.26.0")]
1476    #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1477    #[inline(always)]
1478    #[track_caller]
1479    pub const unsafe fn write_unaligned(self, val: T)
1480    where
1481        T: Sized,
1482    {
1483        // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1484        unsafe { write_unaligned(self, val) }
1485    }
1486
1487    /// Replaces the value at `self` with `src`, returning the old
1488    /// value, without dropping either.
1489    ///
1490    /// See [`ptr::replace`] for safety concerns and examples.
1491    ///
1492    /// [`ptr::replace`]: crate::ptr::replace()
1493    #[stable(feature = "pointer_methods", since = "1.26.0")]
1494    #[rustc_const_stable(feature = "const_inherent_ptr_replace", since = "1.88.0")]
1495    #[inline(always)]
1496    #[ferrocene::prevalidated]
1497    pub const unsafe fn replace(self, src: T) -> T
1498    where
1499        T: Sized,
1500    {
1501        // SAFETY: the caller must uphold the safety contract for `replace`.
1502        unsafe { replace(self, src) }
1503    }
1504
1505    /// Swaps the values at two mutable locations of the same type, without
1506    /// deinitializing either. They may overlap, unlike `mem::swap` which is
1507    /// otherwise equivalent.
1508    ///
1509    /// See [`ptr::swap`] for safety concerns and examples.
1510    ///
1511    /// [`ptr::swap`]: crate::ptr::swap()
1512    #[stable(feature = "pointer_methods", since = "1.26.0")]
1513    #[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
1514    #[inline(always)]
1515    pub const unsafe fn swap(self, with: *mut T)
1516    where
1517        T: Sized,
1518    {
1519        // SAFETY: the caller must uphold the safety contract for `swap`.
1520        unsafe { swap(self, with) }
1521    }
1522
1523    /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1524    /// `align`.
1525    ///
1526    /// If it is not possible to align the pointer, the implementation returns
1527    /// `usize::MAX`.
1528    ///
1529    /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1530    /// used with the `wrapping_add` method.
1531    ///
1532    /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1533    /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1534    /// the returned offset is correct in all terms other than alignment.
1535    ///
1536    /// # Panics
1537    ///
1538    /// The function panics if `align` is not a power-of-two.
1539    ///
1540    /// # Examples
1541    ///
1542    /// Accessing adjacent `u8` as `u16`
1543    ///
1544    /// ```
1545    /// # unsafe {
1546    /// let mut x = [5_u8, 6, 7, 8, 9];
1547    /// let ptr = x.as_mut_ptr();
1548    /// let offset = ptr.align_offset(align_of::<u16>());
1549    ///
1550    /// if offset < x.len() - 1 {
1551    ///     let u16_ptr = ptr.add(offset).cast::<u16>();
1552    ///     *u16_ptr = 0;
1553    ///
1554    ///     assert!(x == [0, 0, 7, 8, 9] || x == [5, 0, 0, 8, 9]);
1555    /// } else {
1556    ///     // while the pointer can be aligned via `offset`, it would point
1557    ///     // outside the allocation
1558    /// }
1559    /// # }
1560    /// ```
1561    #[must_use]
1562    #[inline]
1563    #[stable(feature = "align_offset", since = "1.36.0")]
1564    pub fn align_offset(self, align: usize) -> usize
1565    where
1566        T: Sized,
1567    {
1568        if !align.is_power_of_two() {
1569            panic!("align_offset: align is not a power-of-two");
1570        }
1571
1572        // SAFETY: `align` has been checked to be a power of 2 above
1573        let ret = unsafe { align_offset(self, align) };
1574
1575        // Inform Miri that we want to consider the resulting pointer to be suitably aligned.
1576        #[cfg(miri)]
1577        if ret != usize::MAX {
1578            intrinsics::miri_promise_symbolic_alignment(
1579                self.wrapping_add(ret).cast_const().cast(),
1580                align,
1581            );
1582        }
1583
1584        ret
1585    }
1586
1587    /// Returns whether the pointer is properly aligned for `T`.
1588    ///
1589    /// # Examples
1590    ///
1591    /// ```
1592    /// // On some platforms, the alignment of i32 is less than 4.
1593    /// #[repr(align(4))]
1594    /// struct AlignedI32(i32);
1595    ///
1596    /// let mut data = AlignedI32(42);
1597    /// let ptr = &mut data as *mut AlignedI32;
1598    ///
1599    /// assert!(ptr.is_aligned());
1600    /// assert!(!ptr.wrapping_byte_add(1).is_aligned());
1601    /// ```
1602    #[must_use]
1603    #[inline]
1604    #[stable(feature = "pointer_is_aligned", since = "1.79.0")]
1605    pub fn is_aligned(self) -> bool
1606    where
1607        T: Sized,
1608    {
1609        self.is_aligned_to(align_of::<T>())
1610    }
1611
1612    /// Returns whether the pointer is aligned to `align`.
1613    ///
1614    /// For non-`Sized` pointees this operation considers only the data pointer,
1615    /// ignoring the metadata.
1616    ///
1617    /// # Panics
1618    ///
1619    /// The function panics if `align` is not a power-of-two (this includes 0).
1620    ///
1621    /// # Examples
1622    ///
1623    /// ```
1624    /// #![feature(pointer_is_aligned_to)]
1625    ///
1626    /// // On some platforms, the alignment of i32 is less than 4.
1627    /// #[repr(align(4))]
1628    /// struct AlignedI32(i32);
1629    ///
1630    /// let mut data = AlignedI32(42);
1631    /// let ptr = &mut data as *mut AlignedI32;
1632    ///
1633    /// assert!(ptr.is_aligned_to(1));
1634    /// assert!(ptr.is_aligned_to(2));
1635    /// assert!(ptr.is_aligned_to(4));
1636    ///
1637    /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1638    /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1639    ///
1640    /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1641    /// ```
1642    #[must_use]
1643    #[inline]
1644    #[unstable(feature = "pointer_is_aligned_to", issue = "96284")]
1645    pub fn is_aligned_to(self, align: usize) -> bool {
1646        if !align.is_power_of_two() {
1647            panic!("is_aligned_to: align is not a power-of-two");
1648        }
1649
1650        self.addr() & (align - 1) == 0
1651    }
1652}
1653
1654impl<T> *mut T {
1655    /// Casts from a type to its maybe-uninitialized version.
1656    ///
1657    /// This is always safe, since UB can only occur if the pointer is read
1658    /// before being initialized.
1659    #[must_use]
1660    #[inline(always)]
1661    #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1662    pub const fn cast_uninit(self) -> *mut MaybeUninit<T> {
1663        self as _
1664    }
1665
1666    /// Forms a raw mutable slice from a pointer and a length.
1667    ///
1668    /// The `len` argument is the number of **elements**, not the number of bytes.
1669    ///
1670    /// Performs the same functionality as [`cast_slice`] on a `*const T`, except that a
1671    /// raw mutable slice is returned, as opposed to a raw immutable slice.
1672    ///
1673    /// This function is safe, but actually using the return value is unsafe.
1674    /// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements.
1675    ///
1676    /// [`slice::from_raw_parts_mut`]: crate::slice::from_raw_parts_mut
1677    /// [`cast_slice`]: pointer::cast_slice
1678    ///
1679    /// # Examples
1680    ///
1681    /// ```rust
1682    /// #![feature(ptr_cast_slice)]
1683    ///
1684    /// let x = &mut [5, 6, 7];
1685    /// let raw_mut_slice = x.as_mut_ptr().cast_slice(3);
1686    ///
1687    /// unsafe {
1688    ///     (*raw_mut_slice)[2] = 99; // assign a value at an index in the slice
1689    /// };
1690    ///
1691    /// assert_eq!(unsafe { &*raw_mut_slice }[2], 99);
1692    /// ```
1693    ///
1694    /// You must ensure that the pointer is valid and not null before dereferencing
1695    /// the raw slice. A slice reference must never have a null pointer, even if it's empty.
1696    ///
1697    /// ```rust,should_panic
1698    /// #![feature(ptr_cast_slice)]
1699    /// use std::ptr;
1700    /// let danger: *mut [u8] = ptr::null_mut::<u8>().cast_slice(0);
1701    /// unsafe {
1702    ///     danger.as_mut().expect("references must not be null");
1703    /// }
1704    /// ```
1705    #[ferrocene::prevalidated]
1706    #[inline]
1707    #[unstable(feature = "ptr_cast_slice", issue = "149103")]
1708    pub const fn cast_slice(self, len: usize) -> *mut [T] {
1709        slice_from_raw_parts_mut(self, len)
1710    }
1711}
1712
1713impl<T> *mut MaybeUninit<T> {
1714    /// Casts from a maybe-uninitialized type to its initialized version.
1715    ///
1716    /// This is always safe, since UB can only occur if the pointer is read
1717    /// before being initialized.
1718    #[must_use]
1719    #[inline(always)]
1720    #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1721    pub const fn cast_init(self) -> *mut T {
1722        self as _
1723    }
1724}
1725
1726impl<T> *mut [T] {
1727    /// Returns the length of a raw slice.
1728    ///
1729    /// The returned value is the number of **elements**, not the number of bytes.
1730    ///
1731    /// This function is safe, even when the raw slice cannot be cast to a slice
1732    /// reference because the pointer is null or unaligned.
1733    ///
1734    /// # Examples
1735    ///
1736    /// ```rust
1737    /// use std::ptr;
1738    ///
1739    /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1740    /// assert_eq!(slice.len(), 3);
1741    /// ```
1742    #[inline(always)]
1743    #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1744    #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1745    #[ferrocene::prevalidated]
1746    pub const fn len(self) -> usize {
1747        metadata(self)
1748    }
1749
1750    /// Returns `true` if the raw slice has a length of 0.
1751    ///
1752    /// # Examples
1753    ///
1754    /// ```
1755    /// use std::ptr;
1756    ///
1757    /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1758    /// assert!(!slice.is_empty());
1759    /// ```
1760    #[inline(always)]
1761    #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1762    #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1763    #[ferrocene::prevalidated]
1764    pub const fn is_empty(self) -> bool {
1765        self.len() == 0
1766    }
1767
1768    /// Gets a raw, mutable pointer to the underlying array.
1769    ///
1770    /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
1771    #[stable(feature = "core_slice_as_array", since = "1.93.0")]
1772    #[rustc_const_stable(feature = "core_slice_as_array", since = "1.93.0")]
1773    #[inline]
1774    #[must_use]
1775    #[ferrocene::prevalidated]
1776    pub const fn as_mut_array<const N: usize>(self) -> Option<*mut [T; N]> {
1777        if self.len() == N {
1778            let me = self.as_mut_ptr() as *mut [T; N];
1779            Some(me)
1780        } else {
1781            None
1782        }
1783    }
1784
1785    /// Divides one mutable raw slice into two at an index.
1786    ///
1787    /// The first will contain all indices from `[0, mid)` (excluding
1788    /// the index `mid` itself) and the second will contain all
1789    /// indices from `[mid, len)` (excluding the index `len` itself).
1790    ///
1791    /// # Panics
1792    ///
1793    /// Panics if `mid > len`.
1794    ///
1795    /// # Safety
1796    ///
1797    /// `mid` must be [in-bounds] of the underlying [allocation].
1798    /// Which means `self` must be dereferenceable and span a single allocation
1799    /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1800    /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1801    ///
1802    /// Since `len` being in-bounds is not a safety invariant of `*mut [T]` the
1803    /// safety requirements of this method are the same as for [`split_at_mut_unchecked`].
1804    /// The explicit bounds check is only as useful as `len` is correct.
1805    ///
1806    /// [`split_at_mut_unchecked`]: #method.split_at_mut_unchecked
1807    /// [in-bounds]: #method.add
1808    /// [allocation]: crate::ptr#allocation
1809    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1810    ///
1811    /// # Examples
1812    ///
1813    /// ```
1814    /// #![feature(raw_slice_split)]
1815    ///
1816    /// let mut v = [1, 0, 3, 0, 5, 6];
1817    /// let ptr = &mut v as *mut [_];
1818    /// unsafe {
1819    ///     let (left, right) = ptr.split_at_mut(2);
1820    ///     assert_eq!(&*left, [1, 0]);
1821    ///     assert_eq!(&*right, [3, 0, 5, 6]);
1822    /// }
1823    /// ```
1824    #[inline(always)]
1825    #[track_caller]
1826    #[unstable(feature = "raw_slice_split", issue = "95595")]
1827    #[ferrocene::prevalidated]
1828    pub unsafe fn split_at_mut(self, mid: usize) -> (*mut [T], *mut [T]) {
1829        assert!(mid <= self.len());
1830        // SAFETY: The assert above is only a safety-net as long as `self.len()` is correct
1831        // The actual safety requirements of this function are the same as for `split_at_mut_unchecked`
1832        unsafe { self.split_at_mut_unchecked(mid) }
1833    }
1834
1835    /// Divides one mutable raw slice into two at an index, without doing bounds checking.
1836    ///
1837    /// The first will contain all indices from `[0, mid)` (excluding
1838    /// the index `mid` itself) and the second will contain all
1839    /// indices from `[mid, len)` (excluding the index `len` itself).
1840    ///
1841    /// # Safety
1842    ///
1843    /// `mid` must be [in-bounds] of the underlying [allocation].
1844    /// Which means `self` must be dereferenceable and span a single allocation
1845    /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1846    /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1847    ///
1848    /// [in-bounds]: #method.add
1849    /// [out-of-bounds index]: #method.add
1850    /// [allocation]: crate::ptr#allocation
1851    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1852    ///
1853    /// # Examples
1854    ///
1855    /// ```
1856    /// #![feature(raw_slice_split)]
1857    ///
1858    /// let mut v = [1, 0, 3, 0, 5, 6];
1859    /// // scoped to restrict the lifetime of the borrows
1860    /// unsafe {
1861    ///     let ptr = &mut v as *mut [_];
1862    ///     let (left, right) = ptr.split_at_mut_unchecked(2);
1863    ///     assert_eq!(&*left, [1, 0]);
1864    ///     assert_eq!(&*right, [3, 0, 5, 6]);
1865    ///     (&mut *left)[1] = 2;
1866    ///     (&mut *right)[1] = 4;
1867    /// }
1868    /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1869    /// ```
1870    #[inline(always)]
1871    #[unstable(feature = "raw_slice_split", issue = "95595")]
1872    #[ferrocene::prevalidated]
1873    pub unsafe fn split_at_mut_unchecked(self, mid: usize) -> (*mut [T], *mut [T]) {
1874        let len = self.len();
1875        let ptr = self.as_mut_ptr();
1876
1877        // SAFETY: Caller must pass a valid pointer and an index that is in-bounds.
1878        let tail = unsafe { ptr.add(mid) };
1879        (
1880            crate::ptr::slice_from_raw_parts_mut(ptr, mid),
1881            crate::ptr::slice_from_raw_parts_mut(tail, len - mid),
1882        )
1883    }
1884
1885    /// Returns a raw pointer to the slice's buffer.
1886    ///
1887    /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
1888    ///
1889    /// # Examples
1890    ///
1891    /// ```rust
1892    /// #![feature(slice_ptr_get)]
1893    /// use std::ptr;
1894    ///
1895    /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1896    /// assert_eq!(slice.as_mut_ptr(), ptr::null_mut());
1897    /// ```
1898    #[inline(always)]
1899    #[unstable(feature = "slice_ptr_get", issue = "74265")]
1900    #[ferrocene::prevalidated]
1901    pub const fn as_mut_ptr(self) -> *mut T {
1902        self as *mut T
1903    }
1904
1905    /// Returns a raw pointer to an element or subslice, without doing bounds
1906    /// checking.
1907    ///
1908    /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
1909    /// is *[undefined behavior]* even if the resulting pointer is not used.
1910    ///
1911    /// [out-of-bounds index]: #method.add
1912    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1913    ///
1914    /// # Examples
1915    ///
1916    /// ```
1917    /// #![feature(slice_ptr_get)]
1918    ///
1919    /// let x = &mut [1, 2, 4] as *mut [i32];
1920    ///
1921    /// unsafe {
1922    ///     assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
1923    /// }
1924    /// ```
1925    #[unstable(feature = "slice_ptr_get", issue = "74265")]
1926    #[rustc_const_unstable(feature = "const_index", issue = "143775")]
1927    #[inline(always)]
1928    #[ferrocene::prevalidated]
1929    pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
1930    where
1931        I: [const] SliceIndex<[T]>,
1932    {
1933        // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1934        unsafe { index.get_unchecked_mut(self) }
1935    }
1936
1937    #[doc = include_str!("docs/as_uninit_slice.md")]
1938    ///
1939    /// # See Also
1940    /// For the mutable counterpart see [`as_uninit_slice_mut`](pointer::as_uninit_slice_mut).
1941    #[inline]
1942    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1943    pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1944        if self.is_null() {
1945            None
1946        } else {
1947            // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1948            Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1949        }
1950    }
1951
1952    /// Returns `None` if the pointer is null, or else returns a unique slice to
1953    /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
1954    /// that the value has to be initialized.
1955    ///
1956    /// For the shared counterpart see [`as_uninit_slice`].
1957    ///
1958    /// [`as_mut`]: #method.as_mut
1959    /// [`as_uninit_slice`]: #method.as_uninit_slice-1
1960    ///
1961    /// # Safety
1962    ///
1963    /// When calling this method, you have to ensure that *either* the pointer is null *or*
1964    /// all of the following is true:
1965    ///
1966    /// * The pointer must be [valid] for reads and writes for `ptr.len() * size_of::<T>()`
1967    ///   many bytes, and it must be properly aligned. This means in particular:
1968    ///
1969    ///     * The entire memory range of this slice must be contained within a single [allocation]!
1970    ///       Slices can never span across multiple allocations.
1971    ///
1972    ///     * The pointer must be aligned even for zero-length slices. One
1973    ///       reason for this is that enum layout optimizations may rely on references
1974    ///       (including slices of any length) being aligned and non-null to distinguish
1975    ///       them from other data. You can obtain a pointer that is usable as `data`
1976    ///       for zero-length slices using [`NonNull::dangling()`].
1977    ///
1978    /// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1979    ///   See the safety documentation of [`pointer::offset`].
1980    ///
1981    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1982    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1983    ///   In particular, while this reference exists, the memory the pointer points to must
1984    ///   not get accessed (read or written) through any other pointer.
1985    ///
1986    /// This applies even if the result of this method is unused!
1987    ///
1988    /// See also [`slice::from_raw_parts_mut`][].
1989    ///
1990    /// [valid]: crate::ptr#safety
1991    /// [allocation]: crate::ptr#allocation
1992    ///
1993    /// # Panics during const evaluation
1994    ///
1995    /// This method will panic during const evaluation if the pointer cannot be
1996    /// determined to be null or not. See [`is_null`] for more information.
1997    ///
1998    /// [`is_null`]: #method.is_null-1
1999    #[inline]
2000    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
2001    pub const unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
2002        if self.is_null() {
2003            None
2004        } else {
2005            // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
2006            Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
2007        }
2008    }
2009}
2010
2011impl<T> *mut T {
2012    /// Casts from a pointer-to-`T` to a pointer-to-`[T; N]`.
2013    #[inline]
2014    #[unstable(feature = "ptr_cast_array", issue = "144514")]
2015    #[ferrocene::prevalidated]
2016    pub const fn cast_array<const N: usize>(self) -> *mut [T; N] {
2017        self.cast()
2018    }
2019}
2020
2021impl<T, const N: usize> *mut [T; N] {
2022    /// Returns a raw pointer to the array's buffer.
2023    ///
2024    /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
2025    ///
2026    /// # Examples
2027    ///
2028    /// ```rust
2029    /// #![feature(array_ptr_get)]
2030    /// use std::ptr;
2031    ///
2032    /// let arr: *mut [i8; 3] = ptr::null_mut();
2033    /// assert_eq!(arr.as_mut_ptr(), ptr::null_mut());
2034    /// ```
2035    #[inline]
2036    #[unstable(feature = "array_ptr_get", issue = "119834")]
2037    pub const fn as_mut_ptr(self) -> *mut T {
2038        self as *mut T
2039    }
2040
2041    /// Returns a raw pointer to a mutable slice containing the entire array.
2042    ///
2043    /// # Examples
2044    ///
2045    /// ```
2046    /// #![feature(array_ptr_get)]
2047    ///
2048    /// let mut arr = [1, 2, 5];
2049    /// let ptr: *mut [i32; 3] = &mut arr;
2050    /// unsafe {
2051    ///     (&mut *ptr.as_mut_slice())[..2].copy_from_slice(&[3, 4]);
2052    /// }
2053    /// assert_eq!(arr, [3, 4, 5]);
2054    /// ```
2055    #[inline]
2056    #[unstable(feature = "array_ptr_get", issue = "119834")]
2057    pub const fn as_mut_slice(self) -> *mut [T] {
2058        self
2059    }
2060}
2061
2062/// Pointer equality is by address, as produced by the [`<*mut T>::addr`](pointer::addr) method.
2063#[stable(feature = "rust1", since = "1.0.0")]
2064#[diagnostic::on_const(
2065    message = "pointers cannot be reliably compared during const eval",
2066    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2067)]
2068impl<T: PointeeSized> PartialEq for *mut T {
2069    #[inline(always)]
2070    #[allow(ambiguous_wide_pointer_comparisons)]
2071    #[ferrocene::prevalidated]
2072    fn eq(&self, other: &*mut T) -> bool {
2073        *self == *other
2074    }
2075}
2076
2077/// Pointer equality is an equivalence relation.
2078#[stable(feature = "rust1", since = "1.0.0")]
2079#[diagnostic::on_const(
2080    message = "pointers cannot be reliably compared during const eval",
2081    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2082)]
2083impl<T: PointeeSized> Eq for *mut T {}
2084
2085/// Pointer comparison is by address, as produced by the [`<*mut T>::addr`](pointer::addr) method.
2086#[stable(feature = "rust1", since = "1.0.0")]
2087#[diagnostic::on_const(
2088    message = "pointers cannot be reliably compared during const eval",
2089    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2090)]
2091impl<T: PointeeSized> Ord for *mut T {
2092    #[inline]
2093    #[allow(ambiguous_wide_pointer_comparisons)]
2094    fn cmp(&self, other: &*mut T) -> Ordering {
2095        if self < other {
2096            Less
2097        } else if self == other {
2098            Equal
2099        } else {
2100            Greater
2101        }
2102    }
2103}
2104
2105/// Pointer comparison is by address, as produced by the [`<*mut T>::addr`](pointer::addr) method.
2106#[stable(feature = "rust1", since = "1.0.0")]
2107#[diagnostic::on_const(
2108    message = "pointers cannot be reliably compared during const eval",
2109    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2110)]
2111impl<T: PointeeSized> PartialOrd for *mut T {
2112    #[inline(always)]
2113    #[allow(ambiguous_wide_pointer_comparisons)]
2114    fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2115        Some(self.cmp(other))
2116    }
2117
2118    #[inline(always)]
2119    #[allow(ambiguous_wide_pointer_comparisons)]
2120    fn lt(&self, other: &*mut T) -> bool {
2121        *self < *other
2122    }
2123
2124    #[inline(always)]
2125    #[allow(ambiguous_wide_pointer_comparisons)]
2126    fn le(&self, other: &*mut T) -> bool {
2127        *self <= *other
2128    }
2129
2130    #[inline(always)]
2131    #[allow(ambiguous_wide_pointer_comparisons)]
2132    fn gt(&self, other: &*mut T) -> bool {
2133        *self > *other
2134    }
2135
2136    #[inline(always)]
2137    #[allow(ambiguous_wide_pointer_comparisons)]
2138    fn ge(&self, other: &*mut T) -> bool {
2139        *self >= *other
2140    }
2141}
2142
2143#[stable(feature = "raw_ptr_default", since = "1.88.0")]
2144impl<T: ?Sized + Thin> Default for *mut T {
2145    /// Returns the default value of [`null_mut()`][crate::ptr::null_mut].
2146    fn default() -> Self {
2147        crate::ptr::null_mut()
2148    }
2149}