Skip to main content

core/ptr/
mut_ptr.rs

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