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