core/ptr/
mut_ptr.rs

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