core/ptr/
mut_ptr.rs

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