Skip to main content

core/ptr/
const_ptr.rs

1use super::*;
2use crate::cmp::Ordering::{Equal, Greater, Less};
3use crate::intrinsics::const_eval_select;
4use crate::mem::{self, SizedTypeProperties};
5use crate::slice::{self, SliceIndex};
6
7impl<T: PointeeSized> *const T {
8    #[doc = include_str!("docs/is_null.md")]
9    ///
10    /// # Examples
11    ///
12    /// ```
13    /// let s: &str = "Follow the rabbit";
14    /// let ptr: *const u8 = s.as_ptr();
15    /// assert!(!ptr.is_null());
16    /// ```
17    #[stable(feature = "rust1", since = "1.0.0")]
18    #[rustc_const_stable(feature = "const_ptr_is_null", since = "1.84.0")]
19    #[rustc_diagnostic_item = "ptr_const_is_null"]
20    #[inline]
21    #[rustc_allow_const_fn_unstable(const_eval_select)]
22    pub const fn is_null(self) -> bool {
23        // Compare via a cast to a thin pointer, so fat pointers are only
24        // considering their "data" part for null-ness.
25        let ptr = self as *const u8;
26        const_eval_select!(
27            @capture { ptr: *const u8 } -> bool:
28            // This use of `const_raw_ptr_comparison` has been explicitly blessed by t-lang.
29            if const #[rustc_allow_const_fn_unstable(const_raw_ptr_comparison)] {
30                match (ptr).guaranteed_eq(null_mut()) {
31                    Some(res) => res,
32                    // To remain maximally conservative, we stop execution when we don't
33                    // know whether the pointer is null or not.
34                    // We can *not* return `false` here, that would be unsound in `NonNull::new`!
35                    None => panic!("null-ness of this pointer cannot be determined in const context"),
36                }
37            } else {
38                ptr.addr() == 0
39            }
40        )
41    }
42
43    /// Casts to a pointer of another type.
44    #[stable(feature = "ptr_cast", since = "1.38.0")]
45    #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
46    #[rustc_diagnostic_item = "const_ptr_cast"]
47    #[inline(always)]
48    pub const fn cast<U>(self) -> *const U {
49        self as _
50    }
51
52    /// Try to cast to a pointer of another type by checking alignment.
53    ///
54    /// If the pointer is properly aligned to the target type, it will be
55    /// cast to the target type. Otherwise, `None` is returned.
56    ///
57    /// # Examples
58    ///
59    /// ```rust
60    /// let x = 0u64;
61    ///
62    /// let aligned: *const u64 = &x;
63    /// let unaligned = unsafe { aligned.byte_add(1) };
64    ///
65    /// assert!(aligned.try_cast_aligned::<u32>().is_some());
66    /// assert!(unaligned.try_cast_aligned::<u32>().is_none());
67    /// ```
68    #[stable(feature = "pointer_try_cast_aligned", since = "CURRENT_RUSTC_VERSION")]
69    #[must_use = "this returns the result of the operation, \
70                  without modifying the original"]
71    #[inline]
72    pub fn try_cast_aligned<U>(self) -> Option<*const U> {
73        if self.is_aligned_to(align_of::<U>()) { Some(self.cast()) } else { None }
74    }
75
76    /// Uses the address value in a new pointer of another type.
77    ///
78    /// This operation will ignore the address part of its `meta` operand and discard existing
79    /// metadata of `self`. For pointers to a sized types (thin pointers), this has the same effect
80    /// as a simple cast. For pointers to an unsized type (fat pointers) this recombines the address
81    /// with new metadata such as slice lengths or `dyn`-vtable.
82    ///
83    /// The resulting pointer will have provenance of `self`. This operation is semantically the
84    /// same as creating a new pointer with the data pointer value of `self` but the metadata of
85    /// `meta`, being fat or thin depending on the `meta` operand.
86    ///
87    /// # Examples
88    ///
89    /// This function is primarily useful for enabling pointer arithmetic on potentially fat
90    /// pointers. The pointer is cast to a sized pointee to utilize offset operations and then
91    /// recombined with its own original metadata.
92    ///
93    /// ```
94    /// #![feature(set_ptr_value)]
95    /// # use core::fmt::Debug;
96    /// let arr: [i32; 3] = [1, 2, 3];
97    /// let mut ptr = arr.as_ptr() as *const dyn Debug;
98    /// let thin = ptr as *const u8;
99    /// unsafe {
100    ///     ptr = thin.add(8).with_metadata_of(ptr);
101    ///     # assert_eq!(*(ptr as *const i32), 3);
102    ///     println!("{:?}", &*ptr); // will print "3"
103    /// }
104    /// ```
105    ///
106    /// # *Incorrect* usage
107    ///
108    /// The provenance from pointers is *not* combined. The result must only be used to refer to the
109    /// address allowed by `self`.
110    ///
111    /// ```rust,no_run
112    /// #![feature(set_ptr_value)]
113    /// let x = 0u32;
114    /// let y = 1u32;
115    ///
116    /// let x = (&x) as *const u32;
117    /// let y = (&y) as *const u32;
118    ///
119    /// let offset = (x as usize - y as usize) / 4;
120    /// let bad = x.wrapping_add(offset).with_metadata_of(y);
121    ///
122    /// // This dereference is UB. The pointer only has provenance for `x` but points to `y`.
123    /// println!("{:?}", unsafe { &*bad });
124    /// ```
125    #[unstable(feature = "set_ptr_value", issue = "75091")]
126    #[must_use = "returns a new pointer rather than modifying its argument"]
127    #[inline]
128    pub const fn with_metadata_of<U>(self, meta: *const U) -> *const U
129    where
130        U: PointeeSized,
131    {
132        from_raw_parts::<U>(self as *const (), metadata(meta))
133    }
134
135    /// Changes constness without changing the type.
136    ///
137    /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
138    /// refactored.
139    #[stable(feature = "ptr_const_cast", since = "1.65.0")]
140    #[rustc_const_stable(feature = "ptr_const_cast", since = "1.65.0")]
141    #[rustc_diagnostic_item = "ptr_cast_mut"]
142    #[inline(always)]
143    pub const fn cast_mut(self) -> *mut T {
144        self as _
145    }
146
147    #[doc = include_str!("./docs/addr.md")]
148    #[must_use]
149    #[inline(always)]
150    #[expect(clippy::transmutes_expressible_as_ptr_casts, reason = "implements pointer cast")]
151    #[stable(feature = "strict_provenance", since = "1.84.0")]
152    pub fn addr(self) -> usize {
153        // A pointer-to-integer transmute currently has exactly the right semantics: it returns the
154        // address without exposing the provenance. Note that this is *not* a stable guarantee about
155        // transmute semantics, it relies on sysroot crates having special status.
156        // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
157        // provenance).
158        unsafe { mem::transmute(self.cast::<()>()) }
159    }
160
161    /// Exposes the ["provenance"][crate::ptr#provenance] part of the pointer for future use in
162    /// [`with_exposed_provenance`] and returns the "address" portion.
163    ///
164    /// This is equivalent to `self as usize`, which semantically discards provenance information.
165    /// Furthermore, this (like the `as` cast) has the implicit side-effect of marking the
166    /// provenance as 'exposed', so on platforms that support it you can later call
167    /// [`with_exposed_provenance`] to reconstitute the original pointer including its provenance.
168    ///
169    /// Due to its inherent ambiguity, [`with_exposed_provenance`] may not be supported by tools
170    /// that help you to stay conformant with the Rust memory model. It is recommended to use
171    /// [Strict Provenance][crate::ptr#strict-provenance] APIs such as [`with_addr`][pointer::with_addr]
172    /// wherever possible, in which case [`addr`][pointer::addr] should be used instead of `expose_provenance`.
173    ///
174    /// On most platforms this will produce a value with the same bytes as the original pointer,
175    /// because all the bytes are dedicated to describing the address. Platforms which need to store
176    /// additional information in the pointer may not support this operation, since the 'expose'
177    /// side-effect which is required for [`with_exposed_provenance`] to work is typically not
178    /// available.
179    ///
180    /// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
181    ///
182    /// [`with_exposed_provenance`]: with_exposed_provenance
183    #[inline(always)]
184    #[stable(feature = "exposed_provenance", since = "1.84.0")]
185    #[expect(implicit_provenance_casts, reason = "this *is* the replacement")]
186    pub fn expose_provenance(self) -> usize {
187        self.cast::<()>() as usize
188    }
189
190    /// Creates a new pointer with the given address and the [provenance][crate::ptr#provenance] of
191    /// `self`.
192    ///
193    /// This is similar to a `addr as *const T` cast, but copies
194    /// the *provenance* of `self` to the new pointer.
195    /// This avoids the inherent ambiguity of the unary cast.
196    ///
197    /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
198    /// `self` to the given address, and therefore has all the same capabilities and restrictions.
199    ///
200    /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
201    #[must_use]
202    #[inline]
203    #[stable(feature = "strict_provenance", since = "1.84.0")]
204    pub fn with_addr(self, addr: usize) -> Self {
205        // This should probably be an intrinsic to avoid doing any sort of arithmetic, but
206        // meanwhile, we can implement it with `wrapping_offset`, which preserves the pointer's
207        // provenance.
208        let self_addr = self.addr() as isize;
209        let dest_addr = addr as isize;
210        let offset = dest_addr.wrapping_sub(self_addr);
211        self.wrapping_byte_offset(offset)
212    }
213
214    /// Creates a new pointer by mapping `self`'s address to a new one, preserving the
215    /// [provenance][crate::ptr#provenance] of `self`.
216    ///
217    /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
218    ///
219    /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
220    #[must_use]
221    #[inline]
222    #[stable(feature = "strict_provenance", since = "1.84.0")]
223    pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self {
224        self.with_addr(f(self.addr()))
225    }
226
227    /// Decompose a (possibly wide) pointer into its data pointer and metadata components.
228    ///
229    /// The pointer can be later reconstructed with [`from_raw_parts`].
230    #[unstable(feature = "ptr_metadata", issue = "81513")]
231    #[inline]
232    pub const fn to_raw_parts(self) -> (*const (), <T as super::Pointee>::Metadata) {
233        (self.cast(), metadata(self))
234    }
235
236    #[doc = include_str!("./docs/as_ref.md")]
237    ///
238    /// ```
239    /// let ptr: *const u8 = &10u8 as *const u8;
240    ///
241    /// unsafe {
242    ///     let val_back = ptr.as_ref_unchecked();
243    ///     assert_eq!(val_back, &10);
244    /// }
245    /// ```
246    ///
247    /// # Examples
248    ///
249    /// ```
250    /// let ptr: *const u8 = &10u8 as *const u8;
251    ///
252    /// unsafe {
253    ///     if let Some(val_back) = ptr.as_ref() {
254    ///         assert_eq!(val_back, &10);
255    ///     }
256    /// }
257    /// ```
258    ///
259    ///
260    /// [`is_null`]: #method.is_null
261    /// [`as_uninit_ref`]: #method.as_uninit_ref
262    /// [`as_ref_unchecked`]: #method.as_ref_unchecked
263    #[stable(feature = "ptr_as_ref", since = "1.9.0")]
264    #[rustc_const_stable(feature = "const_ptr_is_null", since = "1.84.0")]
265    #[inline]
266    pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
267        // SAFETY: the caller must guarantee that `self` is valid
268        // for a reference if it isn't null.
269        if self.is_null() { None } else { unsafe { Some(&*self) } }
270    }
271
272    /// Returns a shared reference to the value behind the pointer.
273    /// If the pointer may be null or the value may be uninitialized, [`as_uninit_ref`] must be used instead.
274    /// If the pointer may be null, but the value is known to have been initialized, [`as_ref`] must be used instead.
275    ///
276    /// [`as_ref`]: #method.as_ref
277    /// [`as_uninit_ref`]: #method.as_uninit_ref
278    ///
279    /// # Safety
280    ///
281    /// When calling this method, you have to ensure that
282    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
283    ///
284    /// # Examples
285    ///
286    /// ```
287    /// let ptr: *const u8 = &10u8 as *const u8;
288    ///
289    /// unsafe {
290    ///     assert_eq!(ptr.as_ref_unchecked(), &10);
291    /// }
292    /// ```
293    #[stable(feature = "ptr_as_ref_unchecked", since = "1.95.0")]
294    #[rustc_const_stable(feature = "ptr_as_ref_unchecked", since = "1.95.0")]
295    #[inline]
296    #[must_use]
297    pub const unsafe fn as_ref_unchecked<'a>(self) -> &'a T {
298        // SAFETY: the caller must guarantee that `self` is valid for a reference
299        unsafe { &*self }
300    }
301
302    #[doc = include_str!("./docs/as_uninit_ref.md")]
303    ///
304    /// [`is_null`]: #method.is_null
305    /// [`as_ref`]: #method.as_ref
306    ///
307    /// # Examples
308    ///
309    /// ```
310    /// #![feature(ptr_as_uninit)]
311    ///
312    /// let ptr: *const u8 = &10u8 as *const u8;
313    ///
314    /// unsafe {
315    ///     if let Some(val_back) = ptr.as_uninit_ref() {
316    ///         assert_eq!(val_back.assume_init(), 10);
317    ///     }
318    /// }
319    /// ```
320    #[inline]
321    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
322    pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
323    where
324        T: Sized,
325    {
326        // SAFETY: the caller must guarantee that `self` meets all the
327        // requirements for a reference.
328        if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
329    }
330
331    #[doc = include_str!("./docs/offset.md")]
332    ///
333    /// Consider using [`wrapping_offset`](#method.wrapping_offset) instead if these constraints are
334    /// difficult to satisfy. The only advantage of this method is that it
335    /// enables more aggressive compiler optimizations.
336    ///
337    /// # Examples
338    ///
339    /// ```
340    /// let s: &str = "123";
341    /// let ptr: *const u8 = s.as_ptr();
342    ///
343    /// unsafe {
344    ///     assert_eq!(*ptr.offset(1) as char, '2');
345    ///     assert_eq!(*ptr.offset(2) as char, '3');
346    /// }
347    /// ```
348    #[stable(feature = "rust1", since = "1.0.0")]
349    #[must_use = "returns a new pointer rather than modifying its argument"]
350    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
351    #[inline(always)]
352    #[track_caller]
353    pub const unsafe fn offset(self, count: isize) -> *const T
354    where
355        T: Sized,
356    {
357        #[inline]
358        #[rustc_allow_const_fn_unstable(const_eval_select)]
359        const fn runtime_offset_nowrap(this: *const (), count: isize, size: usize) -> bool {
360            // We can use const_eval_select here because this is only for UB checks.
361            const_eval_select!(
362                @capture { this: *const (), count: isize, size: usize } -> bool:
363                if const {
364                    true
365                } else {
366                    // `size` is the size of a Rust type, so we know that
367                    // `size <= isize::MAX` and thus `as` cast here is not lossy.
368                    let Some(byte_offset) = count.checked_mul(size as isize) else {
369                        return false;
370                    };
371                    let (_, overflow) = this.addr().overflowing_add_signed(byte_offset);
372                    !overflow
373                }
374            )
375        }
376
377        ub_checks::assert_unsafe_precondition!(
378            check_language_ub,
379            "ptr::offset requires the address calculation to not overflow",
380            (
381                this: *const () = self as *const (),
382                count: isize = count,
383                size: usize = size_of::<T>(),
384            ) => runtime_offset_nowrap(this, count, size)
385        );
386
387        // SAFETY: the caller must uphold the safety contract for `offset`.
388        unsafe { intrinsics::offset(self, count) }
389    }
390
391    /// Adds a signed offset in bytes to a pointer.
392    ///
393    /// `count` is in units of **bytes**.
394    ///
395    /// This is purely a convenience for casting to a `u8` pointer and
396    /// using [offset][pointer::offset] on it. See that method for documentation
397    /// and safety requirements.
398    ///
399    /// For non-`Sized` pointees this operation changes only the data pointer,
400    /// leaving the metadata untouched.
401    #[must_use]
402    #[inline(always)]
403    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
404    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
405    #[track_caller]
406    pub const unsafe fn byte_offset(self, count: isize) -> Self {
407        // SAFETY: the caller must uphold the safety contract for `offset`.
408        unsafe { self.cast::<u8>().offset(count).with_metadata_of(self) }
409    }
410
411    /// Adds a signed offset to a pointer using wrapping arithmetic.
412    ///
413    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
414    /// offset of `3 * size_of::<T>()` bytes.
415    ///
416    /// # Safety
417    ///
418    /// This operation itself is always safe, but using the resulting pointer is not.
419    ///
420    /// The resulting pointer "remembers" the [allocation] that `self` points to
421    /// (this is called "[Provenance](ptr/index.html#provenance)").
422    /// The pointer must not be used to read or write other allocations.
423    ///
424    /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
425    /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
426    /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
427    /// `x` and `y` point into the same allocation.
428    ///
429    /// Compared to [`offset`], this method basically delays the requirement of staying within the
430    /// same allocation: [`offset`] is immediate Undefined Behavior when crossing object
431    /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
432    /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
433    /// can be optimized better and is thus preferable in performance-sensitive code.
434    ///
435    /// The delayed check only considers the value of the pointer that was dereferenced, not the
436    /// intermediate values used during the computation of the final result. For example,
437    /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
438    /// words, leaving the allocation and then re-entering it later is permitted.
439    ///
440    /// [`offset`]: #method.offset
441    /// [allocation]: crate::ptr#allocation
442    ///
443    /// # Examples
444    ///
445    /// ```
446    /// # use std::fmt::Write;
447    /// // Iterate using a raw pointer in increments of two elements
448    /// let data = [1u8, 2, 3, 4, 5];
449    /// let mut ptr: *const u8 = data.as_ptr();
450    /// let step = 2;
451    /// let end_rounded_up = ptr.wrapping_offset(6);
452    ///
453    /// let mut out = String::new();
454    /// while ptr != end_rounded_up {
455    ///     unsafe {
456    ///         write!(&mut out, "{}, ", *ptr)?;
457    ///     }
458    ///     ptr = ptr.wrapping_offset(step);
459    /// }
460    /// assert_eq!(out.as_str(), "1, 3, 5, ");
461    /// # std::fmt::Result::Ok(())
462    /// ```
463    #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
464    #[must_use = "returns a new pointer rather than modifying its argument"]
465    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
466    #[inline(always)]
467    pub const fn wrapping_offset(self, count: isize) -> *const T
468    where
469        T: Sized,
470    {
471        // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
472        unsafe { intrinsics::arith_offset(self, count) }
473    }
474
475    /// Adds a signed offset in bytes to a pointer using wrapping arithmetic.
476    ///
477    /// `count` is in units of **bytes**.
478    ///
479    /// This is purely a convenience for casting to a `u8` pointer and
480    /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
481    /// for documentation.
482    ///
483    /// For non-`Sized` pointees this operation changes only the data pointer,
484    /// leaving the metadata untouched.
485    #[must_use]
486    #[inline(always)]
487    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
488    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
489    pub const fn wrapping_byte_offset(self, count: isize) -> Self {
490        self.cast::<u8>().wrapping_offset(count).with_metadata_of(self)
491    }
492
493    /// Masks out bits of the pointer according to a mask.
494    ///
495    /// This is convenience for `ptr.map_addr(|a| a & mask)`.
496    ///
497    /// For non-`Sized` pointees this operation changes only the data pointer,
498    /// leaving the metadata untouched.
499    ///
500    /// ## Examples
501    ///
502    /// ```
503    /// #![feature(ptr_mask)]
504    /// let v = 17_u32;
505    /// let ptr: *const u32 = &v;
506    ///
507    /// // `u32` is 4 bytes aligned,
508    /// // which means that lower 2 bits are always 0.
509    /// let tag_mask = 0b11;
510    /// let ptr_mask = !tag_mask;
511    ///
512    /// // We can store something in these lower bits
513    /// let tagged_ptr = ptr.map_addr(|a| a | 0b10);
514    ///
515    /// // Get the "tag" back
516    /// let tag = tagged_ptr.addr() & tag_mask;
517    /// assert_eq!(tag, 0b10);
518    ///
519    /// // Note that `tagged_ptr` is unaligned, it's UB to read from it.
520    /// // To get original pointer `mask` can be used:
521    /// let masked_ptr = tagged_ptr.mask(ptr_mask);
522    /// assert_eq!(unsafe { *masked_ptr }, 17);
523    /// ```
524    #[unstable(feature = "ptr_mask", issue = "98290")]
525    #[must_use = "returns a new pointer rather than modifying its argument"]
526    #[inline(always)]
527    pub fn mask(self, mask: usize) -> *const T {
528        intrinsics::ptr_mask(self.cast::<()>(), mask).with_metadata_of(self)
529    }
530
531    /// Calculates the distance between two pointers within the same allocation. The returned value is in
532    /// units of T: the distance in bytes divided by `size_of::<T>()`.
533    ///
534    /// This is equivalent to `(self as isize - origin as isize) / (size_of::<T>() as isize)`,
535    /// except that it has a lot more opportunities for UB, in exchange for the compiler
536    /// better understanding what you are doing.
537    ///
538    /// The primary motivation of this method is for computing the `len` of an array/slice
539    /// of `T` that you are currently representing as a "start" and "end" pointer
540    /// (and "end" is "one past the end" of the array).
541    /// In that case, `end.offset_from(start)` gets you the length of the array.
542    ///
543    /// All of the following safety requirements are trivially satisfied for this usecase.
544    ///
545    /// [`offset`]: #method.offset
546    ///
547    /// # Safety
548    ///
549    /// If any of the following conditions are violated, the result is Undefined Behavior:
550    ///
551    /// * `self` and `origin` must either
552    ///
553    ///   * point to the same address, or
554    ///   * both be [derived from][crate::ptr#provenance] a pointer to the same [allocation], and the memory range between
555    ///     the two pointers must be in bounds of that object. (See below for an example.)
556    ///
557    /// * The distance between the pointers, in bytes, must be an exact multiple
558    ///   of the size of `T`.
559    ///
560    /// As a consequence, the absolute distance between the pointers, in bytes, computed on
561    /// mathematical integers (without "wrapping around"), cannot overflow an `isize`. This is
562    /// implied by the in-bounds requirement, and the fact that no allocation can be larger
563    /// than `isize::MAX` bytes.
564    ///
565    /// The requirement for pointers to be derived from the same allocation is primarily
566    /// needed for `const`-compatibility: the distance between pointers into *different* allocated
567    /// objects is not known at compile-time. However, the requirement also exists at
568    /// runtime and may be exploited by optimizations. If you wish to compute the difference between
569    /// pointers that are not guaranteed to be from the same allocation, use
570    /// `(self.addr() as isize - origin.addr() as isize) / size_of::<T>()`.
571    ///
572    /// [`add`]: #method.add
573    /// [allocation]: crate::ptr#allocation
574    ///
575    /// # Panics
576    ///
577    /// This function panics if `T` is a Zero-Sized Type ("ZST").
578    ///
579    /// # Examples
580    ///
581    /// Basic usage:
582    ///
583    /// ```
584    /// let a = [0; 5];
585    /// let ptr1: *const i32 = &a[1];
586    /// let ptr2: *const i32 = &a[3];
587    /// unsafe {
588    ///     assert_eq!(ptr2.offset_from(ptr1), 2);
589    ///     assert_eq!(ptr1.offset_from(ptr2), -2);
590    ///     assert_eq!(ptr1.offset(2), ptr2);
591    ///     assert_eq!(ptr2.offset(-2), ptr1);
592    /// }
593    /// ```
594    ///
595    /// *Incorrect* usage:
596    ///
597    /// ```rust,no_run
598    /// let ptr1 = Box::into_raw(Box::new(0u8)) as *const u8;
599    /// let ptr2 = Box::into_raw(Box::new(1u8)) as *const u8;
600    /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
601    /// // Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.
602    /// let ptr2_other = (ptr1 as *const u8).wrapping_offset(diff).wrapping_offset(1);
603    /// assert_eq!(ptr2 as usize, ptr2_other as usize);
604    /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
605    /// // computing their offset is undefined behavior, even though
606    /// // they point to addresses that are in-bounds of the same object!
607    /// unsafe {
608    ///     let one = ptr2_other.offset_from(ptr2); // Undefined Behavior! ⚠️
609    /// }
610    /// ```
611    #[stable(feature = "ptr_offset_from", since = "1.47.0")]
612    #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
613    #[inline(always)]
614    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
615    pub const unsafe fn offset_from(self, origin: *const T) -> isize
616    where
617        T: Sized,
618    {
619        let pointee_size = size_of::<T>();
620        assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
621        // SAFETY: the caller must uphold the safety contract for `ptr_offset_from`.
622        unsafe { intrinsics::ptr_offset_from(self, origin) }
623    }
624
625    /// Calculates the distance between two pointers within the same allocation. The returned value is in
626    /// units of **bytes**.
627    ///
628    /// This is purely a convenience for casting to a `u8` pointer and
629    /// using [`offset_from`][pointer::offset_from] on it. See that method for
630    /// documentation and safety requirements.
631    ///
632    /// For non-`Sized` pointees this operation considers only the data pointers,
633    /// ignoring the metadata.
634    #[inline(always)]
635    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
636    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
637    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
638    pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: *const U) -> isize {
639        // SAFETY: the caller must uphold the safety contract for `offset_from`.
640        unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
641    }
642
643    /// Calculates the distance between two pointers within the same allocation, *where it's known that
644    /// `self` is equal to or greater than `origin`*. The returned value is in
645    /// units of T: the distance in bytes is divided by `size_of::<T>()`.
646    ///
647    /// This computes the same value that [`offset_from`](#method.offset_from)
648    /// would compute, but with the added precondition that the offset is
649    /// guaranteed to be non-negative.  This method is equivalent to
650    /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`,
651    /// but it provides slightly more information to the optimizer, which can
652    /// sometimes allow it to optimize slightly better with some backends.
653    ///
654    /// This method can be thought of as recovering the `count` that was passed
655    /// to [`add`](#method.add) (or, with the parameters in the other order,
656    /// to [`sub`](#method.sub)).  The following are all equivalent, assuming
657    /// that their safety preconditions are met:
658    /// ```rust
659    /// # unsafe fn blah(ptr: *const i32, origin: *const i32, count: usize) -> bool { unsafe {
660    /// ptr.offset_from_unsigned(origin) == count
661    /// # &&
662    /// origin.add(count) == ptr
663    /// # &&
664    /// ptr.sub(count) == origin
665    /// # } }
666    /// ```
667    ///
668    /// # Safety
669    ///
670    /// - The distance between the pointers must be non-negative (`self >= origin`)
671    ///
672    /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
673    ///   apply to this method as well; see it for the full details.
674    ///
675    /// Importantly, despite the return type of this method being able to represent
676    /// a larger offset, it's still *not permitted* to pass pointers which differ
677    /// by more than `isize::MAX` *bytes*.  As such, the result of this method will
678    /// always be less than or equal to `isize::MAX as usize`.
679    ///
680    /// # Panics
681    ///
682    /// This function panics if `T` is a Zero-Sized Type ("ZST").
683    ///
684    /// # Examples
685    ///
686    /// ```
687    /// let a = [0; 5];
688    /// let ptr1: *const i32 = &a[1];
689    /// let ptr2: *const i32 = &a[3];
690    /// unsafe {
691    ///     assert_eq!(ptr2.offset_from_unsigned(ptr1), 2);
692    ///     assert_eq!(ptr1.add(2), ptr2);
693    ///     assert_eq!(ptr2.sub(2), ptr1);
694    ///     assert_eq!(ptr2.offset_from_unsigned(ptr2), 0);
695    /// }
696    ///
697    /// // This would be incorrect, as the pointers are not correctly ordered:
698    /// // ptr1.offset_from_unsigned(ptr2)
699    /// ```
700    #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
701    #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
702    #[inline]
703    #[track_caller]
704    pub const unsafe fn offset_from_unsigned(self, origin: *const T) -> usize
705    where
706        T: Sized,
707    {
708        #[rustc_allow_const_fn_unstable(const_eval_select)]
709        const fn runtime_ptr_ge(this: *const (), origin: *const ()) -> bool {
710            const_eval_select!(
711                @capture { this: *const (), origin: *const () } -> bool:
712                if const {
713                    true
714                } else {
715                    this >= origin
716                }
717            )
718        }
719
720        ub_checks::assert_unsafe_precondition!(
721            check_language_ub,
722            "ptr::offset_from_unsigned requires `self >= origin`",
723            (
724                this: *const () = self as *const (),
725                origin: *const () = origin as *const (),
726            ) => runtime_ptr_ge(this, origin)
727        );
728
729        let pointee_size = size_of::<T>();
730        assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
731        // SAFETY: the caller must uphold the safety contract for `ptr_offset_from_unsigned`.
732        unsafe { intrinsics::ptr_offset_from_unsigned(self, origin) }
733    }
734
735    /// Calculates the distance between two pointers within the same allocation, *where it's known that
736    /// `self` is equal to or greater than `origin`*. The returned value is in
737    /// units of **bytes**.
738    ///
739    /// This is purely a convenience for casting to a `u8` pointer and
740    /// using [`offset_from_unsigned`][pointer::offset_from_unsigned] on it.
741    /// See that method for documentation and safety requirements.
742    ///
743    /// For non-`Sized` pointees this operation considers only the data pointers,
744    /// ignoring the metadata.
745    #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
746    #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
747    #[inline]
748    #[track_caller]
749    pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: *const U) -> usize {
750        // SAFETY: the caller must uphold the safety contract for `offset_from_unsigned`.
751        unsafe { self.cast::<u8>().offset_from_unsigned(origin.cast::<u8>()) }
752    }
753
754    /// Returns whether two pointers are guaranteed to be equal.
755    ///
756    /// At runtime this function behaves like `Some(self == other)`.
757    /// However, in some contexts (e.g., compile-time evaluation),
758    /// it is not always possible to determine equality of two pointers, so this function may
759    /// spuriously return `None` for pointers that later actually turn out to have its equality known.
760    /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
761    ///
762    /// The return value may change from `Some` to `None` and vice versa depending on the compiler
763    /// version and unsafe code must not
764    /// rely on the result of this function for soundness. It is suggested to only use this function
765    /// for performance optimizations where spurious `None` return values by this function do not
766    /// affect the outcome, but just the performance.
767    /// The consequences of using this method to make runtime and compile-time code behave
768    /// differently have not been explored. This method should not be used to introduce such
769    /// differences, and it should also not be stabilized before we have a better understanding
770    /// of this issue.
771    #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
772    #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
773    #[inline]
774    pub const fn guaranteed_eq(self, other: *const T) -> Option<bool>
775    where
776        T: Sized,
777    {
778        match intrinsics::ptr_guaranteed_cmp(self, other) {
779            2 => None,
780            other => Some(other == 1),
781        }
782    }
783
784    /// Returns whether two pointers are guaranteed to be inequal.
785    ///
786    /// At runtime this function behaves like `Some(self != other)`.
787    /// However, in some contexts (e.g., compile-time evaluation),
788    /// it is not always possible to determine inequality of two pointers, so this function may
789    /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
790    /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
791    ///
792    /// The return value may change from `Some` to `None` and vice versa depending on the compiler
793    /// version and unsafe code must not
794    /// rely on the result of this function for soundness. It is suggested to only use this function
795    /// for performance optimizations where spurious `None` return values by this function do not
796    /// affect the outcome, but just the performance.
797    /// The consequences of using this method to make runtime and compile-time code behave
798    /// differently have not been explored. This method should not be used to introduce such
799    /// differences, and it should also not be stabilized before we have a better understanding
800    /// of this issue.
801    #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
802    #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
803    #[inline]
804    pub const fn guaranteed_ne(self, other: *const T) -> Option<bool>
805    where
806        T: Sized,
807    {
808        match self.guaranteed_eq(other) {
809            None => None,
810            Some(eq) => Some(!eq),
811        }
812    }
813
814    #[doc = include_str!("./docs/add.md")]
815    ///
816    /// Consider using [`wrapping_add`](#method.wrapping_add) instead if these constraints are
817    /// difficult to satisfy. The only advantage of this method is that it
818    /// enables more aggressive compiler optimizations.
819    ///
820    /// # Examples
821    ///
822    /// ```
823    /// let s: &str = "123";
824    /// let ptr: *const u8 = s.as_ptr();
825    ///
826    /// unsafe {
827    ///     assert_eq!(*ptr.add(1), b'2');
828    ///     assert_eq!(*ptr.add(2), b'3');
829    /// }
830    /// ```
831    #[stable(feature = "pointer_methods", since = "1.26.0")]
832    #[must_use = "returns a new pointer rather than modifying its argument"]
833    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
834    #[inline(always)]
835    #[track_caller]
836    pub const unsafe fn add(self, count: usize) -> Self
837    where
838        T: Sized,
839    {
840        #[cfg(debug_assertions)]
841        #[inline]
842        #[rustc_allow_const_fn_unstable(const_eval_select)]
843        const fn runtime_add_nowrap(this: *const (), count: usize, size: usize) -> bool {
844            const_eval_select!(
845                @capture { this: *const (), count: usize, size: usize } -> bool:
846                if const {
847                    true
848                } else {
849                    let Some(byte_offset) = count.checked_mul(size) else {
850                        return false;
851                    };
852                    let (_, overflow) = this.addr().overflowing_add(byte_offset);
853                    byte_offset <= (isize::MAX as usize) && !overflow
854                }
855            )
856        }
857
858        #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
859        ub_checks::assert_unsafe_precondition!(
860            check_language_ub,
861            "ptr::add requires that the address calculation does not overflow",
862            (
863                this: *const () = self as *const (),
864                count: usize = count,
865                size: usize = size_of::<T>(),
866            ) => runtime_add_nowrap(this, count, size)
867        );
868
869        // SAFETY: the caller must uphold the safety contract for `offset`.
870        unsafe { intrinsics::offset(self, count) }
871    }
872
873    /// Adds an unsigned offset in bytes to a pointer.
874    ///
875    /// `count` is in units of bytes.
876    ///
877    /// This is purely a convenience for casting to a `u8` pointer and
878    /// using [add][pointer::add] on it. See that method for documentation
879    /// and safety requirements.
880    ///
881    /// For non-`Sized` pointees this operation changes only the data pointer,
882    /// leaving the metadata untouched.
883    #[must_use]
884    #[inline(always)]
885    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
886    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
887    #[track_caller]
888    pub const unsafe fn byte_add(self, count: usize) -> Self {
889        // SAFETY: the caller must uphold the safety contract for `add`.
890        unsafe { self.cast::<u8>().add(count).with_metadata_of(self) }
891    }
892
893    #[doc = include_str!("./docs/sub.md")]
894    ///
895    /// Consider using [`wrapping_sub`](#method.wrapping_sub) instead if these constraints are
896    /// difficult to satisfy. The only advantage of this method is that it
897    /// enables more aggressive compiler optimizations.
898    ///
899    /// # Examples
900    ///
901    /// ```
902    /// let s: &str = "123";
903    ///
904    /// unsafe {
905    ///     let end: *const u8 = s.as_ptr().add(3);
906    ///     assert_eq!(*end.sub(1), b'3');
907    ///     assert_eq!(*end.sub(2), b'2');
908    /// }
909    /// ```
910    #[stable(feature = "pointer_methods", since = "1.26.0")]
911    #[must_use = "returns a new pointer rather than modifying its argument"]
912    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
913    #[inline(always)]
914    #[track_caller]
915    pub const unsafe fn sub(self, count: usize) -> Self
916    where
917        T: Sized,
918    {
919        #[cfg(debug_assertions)]
920        #[inline]
921        #[rustc_allow_const_fn_unstable(const_eval_select)]
922        const fn runtime_sub_nowrap(this: *const (), count: usize, size: usize) -> bool {
923            const_eval_select!(
924                @capture { this: *const (), count: usize, size: usize } -> bool:
925                if const {
926                    true
927                } else {
928                    let Some(byte_offset) = count.checked_mul(size) else {
929                        return false;
930                    };
931                    byte_offset <= (isize::MAX as usize) && this.addr() >= byte_offset
932                }
933            )
934        }
935
936        #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
937        ub_checks::assert_unsafe_precondition!(
938            check_language_ub,
939            "ptr::sub requires that the address calculation does not overflow",
940            (
941                this: *const () = self as *const (),
942                count: usize = count,
943                size: usize = size_of::<T>(),
944            ) => runtime_sub_nowrap(this, count, size)
945        );
946
947        if T::IS_ZST {
948            // Pointer arithmetic does nothing when the pointee is a ZST.
949            self
950        } else {
951            // SAFETY: the caller must uphold the safety contract for `offset`.
952            // Because the pointee is *not* a ZST, that means that `count` is
953            // at most `isize::MAX`, and thus the negation cannot overflow.
954            unsafe { intrinsics::offset(self, intrinsics::unchecked_sub(0, count as isize)) }
955        }
956    }
957
958    /// Subtracts an unsigned offset in bytes from a pointer.
959    ///
960    /// `count` is in units of bytes.
961    ///
962    /// This is purely a convenience for casting to a `u8` pointer and
963    /// using [sub][pointer::sub] on it. See that method for documentation
964    /// and safety requirements.
965    ///
966    /// For non-`Sized` pointees this operation changes only the data pointer,
967    /// leaving the metadata untouched.
968    #[must_use]
969    #[inline(always)]
970    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
971    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
972    #[track_caller]
973    pub const unsafe fn byte_sub(self, count: usize) -> Self {
974        // SAFETY: the caller must uphold the safety contract for `sub`.
975        unsafe { self.cast::<u8>().sub(count).with_metadata_of(self) }
976    }
977
978    /// Adds an unsigned offset to a pointer using wrapping arithmetic.
979    ///
980    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
981    /// offset of `3 * size_of::<T>()` bytes.
982    ///
983    /// # Safety
984    ///
985    /// This operation itself is always safe, but using the resulting pointer is not.
986    ///
987    /// The resulting pointer "remembers" the [allocation] that `self` points to; it must not
988    /// be used to read or write other allocations.
989    ///
990    /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
991    /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
992    /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
993    /// `x` and `y` point into the same allocation.
994    ///
995    /// Compared to [`add`], this method basically delays the requirement of staying within the
996    /// same allocation: [`add`] is immediate Undefined Behavior when crossing object
997    /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
998    /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
999    /// can be optimized better and is thus preferable in performance-sensitive code.
1000    ///
1001    /// The delayed check only considers the value of the pointer that was dereferenced, not the
1002    /// intermediate values used during the computation of the final result. For example,
1003    /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1004    /// allocation and then re-entering it later is permitted.
1005    ///
1006    /// [`add`]: #method.add
1007    /// [allocation]: crate::ptr#allocation
1008    ///
1009    /// # Examples
1010    ///
1011    /// ```
1012    /// # use std::fmt::Write;
1013    /// // Iterate using a raw pointer in increments of two elements
1014    /// let data = [1u8, 2, 3, 4, 5];
1015    /// let mut ptr: *const u8 = data.as_ptr();
1016    /// let step = 2;
1017    /// let end_rounded_up = ptr.wrapping_add(6);
1018    ///
1019    /// let mut out = String::new();
1020    /// while ptr != end_rounded_up {
1021    ///     unsafe {
1022    ///         write!(&mut out, "{}, ", *ptr)?;
1023    ///     }
1024    ///     ptr = ptr.wrapping_add(step);
1025    /// }
1026    /// assert_eq!(out, "1, 3, 5, ");
1027    /// # std::fmt::Result::Ok(())
1028    /// ```
1029    #[stable(feature = "pointer_methods", since = "1.26.0")]
1030    #[must_use = "returns a new pointer rather than modifying its argument"]
1031    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1032    #[allow(clippy::ptr_offset_with_cast)]
1033    #[inline(always)]
1034    pub const fn wrapping_add(self, count: usize) -> Self
1035    where
1036        T: Sized,
1037    {
1038        self.wrapping_offset(count as isize)
1039    }
1040
1041    /// Adds an unsigned offset in bytes to a pointer using wrapping arithmetic.
1042    ///
1043    /// `count` is in units of bytes.
1044    ///
1045    /// This is purely a convenience for casting to a `u8` pointer and
1046    /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1047    ///
1048    /// For non-`Sized` pointees this operation changes only the data pointer,
1049    /// leaving the metadata untouched.
1050    #[must_use]
1051    #[inline(always)]
1052    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1053    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1054    pub const fn wrapping_byte_add(self, count: usize) -> Self {
1055        self.cast::<u8>().wrapping_add(count).with_metadata_of(self)
1056    }
1057
1058    /// Subtracts an unsigned offset from a pointer using wrapping arithmetic.
1059    ///
1060    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1061    /// offset of `3 * size_of::<T>()` bytes.
1062    ///
1063    /// # Safety
1064    ///
1065    /// This operation itself is always safe, but using the resulting pointer is not.
1066    ///
1067    /// The resulting pointer "remembers" the [allocation] that `self` points to; it must not
1068    /// be used to read or write other allocations.
1069    ///
1070    /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1071    /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1072    /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1073    /// `x` and `y` point into the same allocation.
1074    ///
1075    /// Compared to [`sub`], this method basically delays the requirement of staying within the
1076    /// same allocation: [`sub`] is immediate Undefined Behavior when crossing object
1077    /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1078    /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1079    /// can be optimized better and is thus preferable in performance-sensitive code.
1080    ///
1081    /// The delayed check only considers the value of the pointer that was dereferenced, not the
1082    /// intermediate values used during the computation of the final result. For example,
1083    /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1084    /// allocation and then re-entering it later is permitted.
1085    ///
1086    /// [`sub`]: #method.sub
1087    /// [allocation]: crate::ptr#allocation
1088    ///
1089    /// # Examples
1090    ///
1091    /// ```
1092    /// # use std::fmt::Write;
1093    /// // Iterate using a raw pointer in increments of two elements (backwards)
1094    /// let data = [1u8, 2, 3, 4, 5];
1095    /// let mut ptr: *const u8 = data.as_ptr();
1096    /// let start_rounded_down = ptr.wrapping_sub(2);
1097    /// ptr = ptr.wrapping_add(4);
1098    /// let step = 2;
1099    /// let mut out = String::new();
1100    /// while ptr != start_rounded_down {
1101    ///     unsafe {
1102    ///         write!(&mut out, "{}, ", *ptr)?;
1103    ///     }
1104    ///     ptr = ptr.wrapping_sub(step);
1105    /// }
1106    /// assert_eq!(out, "5, 3, 1, ");
1107    /// # std::fmt::Result::Ok(())
1108    /// ```
1109    #[stable(feature = "pointer_methods", since = "1.26.0")]
1110    #[must_use = "returns a new pointer rather than modifying its argument"]
1111    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1112    #[inline(always)]
1113    pub const fn wrapping_sub(self, count: usize) -> Self
1114    where
1115        T: Sized,
1116    {
1117        self.wrapping_offset((count as isize).wrapping_neg())
1118    }
1119
1120    /// Subtracts an unsigned offset in bytes from a pointer using wrapping arithmetic.
1121    ///
1122    /// `count` is in units of bytes.
1123    ///
1124    /// This is purely a convenience for casting to a `u8` pointer and
1125    /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1126    ///
1127    /// For non-`Sized` pointees this operation changes only the data pointer,
1128    /// leaving the metadata untouched.
1129    #[must_use]
1130    #[inline(always)]
1131    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1132    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1133    pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1134        self.cast::<u8>().wrapping_sub(count).with_metadata_of(self)
1135    }
1136
1137    /// Reads the value from `self` without moving it. This leaves the
1138    /// memory in `self` unchanged.
1139    ///
1140    /// See [`ptr::read`] for safety concerns and examples.
1141    ///
1142    /// [`ptr::read`]: crate::ptr::read()
1143    #[stable(feature = "pointer_methods", since = "1.26.0")]
1144    #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1145    #[inline(always)]
1146    #[track_caller]
1147    pub const unsafe fn read(self) -> T
1148    where
1149        T: Sized,
1150    {
1151        // SAFETY: the caller must uphold the safety contract for `read`.
1152        unsafe { read(self) }
1153    }
1154
1155    /// Performs a volatile read of the value from `self` without moving it. This
1156    /// leaves the memory in `self` unchanged.
1157    ///
1158    /// Volatile operations are intended to act on I/O memory, and are guaranteed
1159    /// to not be elided or reordered by the compiler across other volatile
1160    /// operations.
1161    ///
1162    /// See [`ptr::read_volatile`] for safety concerns and examples.
1163    ///
1164    /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1165    #[stable(feature = "pointer_methods", since = "1.26.0")]
1166    #[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
1167    #[inline(always)]
1168    #[track_caller]
1169    pub const unsafe fn read_volatile(self) -> T
1170    where
1171        T: Sized,
1172    {
1173        // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1174        unsafe { read_volatile(self) }
1175    }
1176
1177    /// Reads the value from `self` without moving it. This leaves the
1178    /// memory in `self` unchanged.
1179    ///
1180    /// Unlike `read`, the pointer may be unaligned.
1181    ///
1182    /// See [`ptr::read_unaligned`] for safety concerns and examples.
1183    ///
1184    /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1185    #[stable(feature = "pointer_methods", since = "1.26.0")]
1186    #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1187    #[inline(always)]
1188    #[track_caller]
1189    pub const unsafe fn read_unaligned(self) -> T
1190    where
1191        T: Sized,
1192    {
1193        // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1194        unsafe { read_unaligned(self) }
1195    }
1196
1197    /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1198    /// and destination may overlap.
1199    ///
1200    /// NOTE: this has the *same* argument order as [`ptr::copy`].
1201    ///
1202    /// See [`ptr::copy`] for safety concerns and examples.
1203    ///
1204    /// [`ptr::copy`]: crate::ptr::copy()
1205    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1206    #[stable(feature = "pointer_methods", since = "1.26.0")]
1207    #[inline(always)]
1208    #[track_caller]
1209    pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1210    where
1211        T: Sized,
1212    {
1213        // SAFETY: the caller must uphold the safety contract for `copy`.
1214        unsafe { copy(self, dest, count) }
1215    }
1216
1217    /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1218    /// and destination may *not* overlap.
1219    ///
1220    /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1221    ///
1222    /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1223    ///
1224    /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1225    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1226    #[stable(feature = "pointer_methods", since = "1.26.0")]
1227    #[inline(always)]
1228    #[track_caller]
1229    pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1230    where
1231        T: Sized,
1232    {
1233        // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1234        unsafe { copy_nonoverlapping(self, dest, count) }
1235    }
1236
1237    /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1238    /// `align`.
1239    ///
1240    /// If it is not possible to align the pointer, the implementation returns
1241    /// `usize::MAX`.
1242    ///
1243    /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1244    /// used with the `wrapping_add` method.
1245    ///
1246    /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1247    /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1248    /// the returned offset is correct in all terms other than alignment.
1249    ///
1250    /// # Panics
1251    ///
1252    /// The function panics if `align` is not a power-of-two.
1253    ///
1254    /// # Examples
1255    ///
1256    /// Accessing adjacent `u8` as `u16`
1257    ///
1258    /// ```
1259    /// # unsafe {
1260    /// let x = [5_u8, 6, 7, 8, 9];
1261    /// let ptr = x.as_ptr();
1262    /// let offset = ptr.align_offset(align_of::<u16>());
1263    ///
1264    /// if offset < x.len() - 1 {
1265    ///     let u16_ptr = ptr.add(offset).cast::<u16>();
1266    ///     assert!(*u16_ptr == u16::from_ne_bytes([5, 6]) || *u16_ptr == u16::from_ne_bytes([6, 7]));
1267    /// } else {
1268    ///     // while the pointer can be aligned via `offset`, it would point
1269    ///     // outside the allocation
1270    /// }
1271    /// # }
1272    /// ```
1273    #[must_use]
1274    #[inline]
1275    #[stable(feature = "align_offset", since = "1.36.0")]
1276    pub fn align_offset(self, align: usize) -> usize
1277    where
1278        T: Sized,
1279    {
1280        if !align.is_power_of_two() {
1281            panic!("align_offset: align is not a power-of-two");
1282        }
1283
1284        // SAFETY: `align` has been checked to be a power of 2 above
1285        let ret = unsafe { align_offset(self, align) };
1286
1287        // Inform Miri that we want to consider the resulting pointer to be suitably aligned.
1288        #[cfg(miri)]
1289        if ret != usize::MAX {
1290            intrinsics::miri_promise_symbolic_alignment(self.wrapping_add(ret).cast(), align);
1291        }
1292
1293        ret
1294    }
1295
1296    /// Returns whether the pointer is properly aligned for `T`.
1297    ///
1298    /// # Examples
1299    ///
1300    /// ```
1301    /// // On some platforms, the alignment of i32 is less than 4.
1302    /// #[repr(align(4))]
1303    /// struct AlignedI32(i32);
1304    ///
1305    /// let data = AlignedI32(42);
1306    /// let ptr = &data as *const AlignedI32;
1307    ///
1308    /// assert!(ptr.is_aligned());
1309    /// assert!(!ptr.wrapping_byte_add(1).is_aligned());
1310    /// ```
1311    #[must_use]
1312    #[inline]
1313    #[stable(feature = "pointer_is_aligned", since = "1.79.0")]
1314    pub fn is_aligned(self) -> bool
1315    where
1316        T: Sized,
1317    {
1318        self.is_aligned_to(align_of::<T>())
1319    }
1320
1321    /// Returns whether the pointer is aligned to `align`.
1322    ///
1323    /// For non-`Sized` pointees this operation considers only the data pointer,
1324    /// ignoring the metadata.
1325    ///
1326    /// # Panics
1327    ///
1328    /// The function panics if `align` is not a power-of-two (this includes 0).
1329    ///
1330    /// # Examples
1331    ///
1332    /// ```
1333    /// #![feature(pointer_is_aligned_to)]
1334    ///
1335    /// // On some platforms, the alignment of i32 is less than 4.
1336    /// #[repr(align(4))]
1337    /// struct AlignedI32(i32);
1338    ///
1339    /// let data = AlignedI32(42);
1340    /// let ptr = &data as *const AlignedI32;
1341    ///
1342    /// assert!(ptr.is_aligned_to(1));
1343    /// assert!(ptr.is_aligned_to(2));
1344    /// assert!(ptr.is_aligned_to(4));
1345    ///
1346    /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1347    /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1348    ///
1349    /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1350    /// ```
1351    #[must_use]
1352    #[inline]
1353    #[unstable(feature = "pointer_is_aligned_to", issue = "96284")]
1354    pub fn is_aligned_to(self, align: usize) -> bool {
1355        if !align.is_power_of_two() {
1356            panic!("is_aligned_to: align is not a power-of-two");
1357        }
1358
1359        self.addr() & (align - 1) == 0
1360    }
1361}
1362
1363impl<T> *const T {
1364    /// Casts from a type to its maybe-uninitialized version.
1365    #[must_use]
1366    #[inline(always)]
1367    #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1368    pub const fn cast_uninit(self) -> *const MaybeUninit<T> {
1369        self as _
1370    }
1371
1372    /// Forms a raw slice from a pointer and a length.
1373    ///
1374    /// The `len` argument is the number of **elements**, not the number of bytes.
1375    ///
1376    /// This function is safe, but actually using the return value is unsafe.
1377    /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
1378    ///
1379    /// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
1380    ///
1381    /// # Examples
1382    ///
1383    /// ```rust
1384    /// #![feature(ptr_cast_slice)]
1385    ///
1386    /// // create a slice pointer when starting out with a pointer to the first element
1387    /// let x = [5, 6, 7];
1388    /// let raw_slice = x.as_ptr().cast_slice(3);
1389    /// assert_eq!(unsafe { &*raw_slice }[2], 7);
1390    /// ```
1391    ///
1392    /// You must ensure that the pointer is valid and not null before dereferencing
1393    /// the raw slice. A slice reference must never have a null pointer, even if it's empty.
1394    ///
1395    /// ```rust,should_panic
1396    /// #![feature(ptr_cast_slice)]
1397    /// use std::ptr;
1398    /// let danger: *const [u8] = ptr::null::<u8>().cast_slice(0);
1399    /// unsafe {
1400    ///     danger.as_ref().expect("references must not be null");
1401    /// }
1402    /// ```
1403    #[inline]
1404    #[unstable(feature = "ptr_cast_slice", issue = "149103")]
1405    pub const fn cast_slice(self, len: usize) -> *const [T] {
1406        slice_from_raw_parts(self, len)
1407    }
1408}
1409impl<T> *const MaybeUninit<T> {
1410    /// Casts from a maybe-uninitialized type to its initialized version.
1411    ///
1412    /// This is always safe, since UB can only occur if the pointer is read
1413    /// before being initialized.
1414    #[must_use]
1415    #[inline(always)]
1416    #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1417    pub const fn cast_init(self) -> *const T {
1418        self as _
1419    }
1420}
1421
1422impl<T> *const [T] {
1423    /// Returns the length of a raw slice.
1424    ///
1425    /// The returned value is the number of **elements**, not the number of bytes.
1426    ///
1427    /// This function is safe, even when the raw slice cannot be cast to a slice
1428    /// reference because the pointer is null or unaligned.
1429    ///
1430    /// # Examples
1431    ///
1432    /// ```rust
1433    /// use std::ptr;
1434    ///
1435    /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1436    /// assert_eq!(slice.len(), 3);
1437    /// ```
1438    #[inline(always)]
1439    #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1440    #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1441    pub const fn len(self) -> usize {
1442        metadata(self)
1443    }
1444
1445    /// Returns `true` if the raw slice has a length of 0.
1446    ///
1447    /// # Examples
1448    ///
1449    /// ```
1450    /// use std::ptr;
1451    ///
1452    /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1453    /// assert!(!slice.is_empty());
1454    /// ```
1455    #[inline(always)]
1456    #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1457    #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1458    pub const fn is_empty(self) -> bool {
1459        self.len() == 0
1460    }
1461
1462    /// Returns a raw pointer to the slice's buffer.
1463    ///
1464    /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1465    ///
1466    /// # Examples
1467    ///
1468    /// ```rust
1469    /// #![feature(slice_ptr_get)]
1470    /// use std::ptr;
1471    ///
1472    /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1473    /// assert_eq!(slice.as_ptr(), ptr::null());
1474    /// ```
1475    #[inline(always)]
1476    #[unstable(feature = "slice_ptr_get", issue = "74265")]
1477    pub const fn as_ptr(self) -> *const T {
1478        self as *const T
1479    }
1480
1481    /// Gets a raw pointer to the underlying array.
1482    ///
1483    /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
1484    #[stable(feature = "core_slice_as_array", since = "1.93.0")]
1485    #[rustc_const_stable(feature = "core_slice_as_array", since = "1.93.0")]
1486    #[inline]
1487    #[must_use]
1488    pub const fn as_array<const N: usize>(self) -> Option<*const [T; N]> {
1489        if self.len() == N {
1490            let me = self.as_ptr() as *const [T; N];
1491            Some(me)
1492        } else {
1493            None
1494        }
1495    }
1496
1497    /// Returns a raw pointer to an element or subslice, without doing bounds
1498    /// checking.
1499    ///
1500    /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
1501    /// is *[undefined behavior]* even if the resulting pointer is not used.
1502    ///
1503    /// [out-of-bounds index]: #method.add
1504    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1505    ///
1506    /// # Examples
1507    ///
1508    /// ```
1509    /// #![feature(slice_ptr_get)]
1510    ///
1511    /// let x = &[1, 2, 4] as *const [i32];
1512    ///
1513    /// unsafe {
1514    ///     assert_eq!(x.get_unchecked(1), x.as_ptr().add(1));
1515    /// }
1516    /// ```
1517    #[unstable(feature = "slice_ptr_get", issue = "74265")]
1518    #[rustc_const_unstable(feature = "const_index", issue = "143775")]
1519    #[inline(always)]
1520    pub const unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output
1521    where
1522        I: [const] SliceIndex<[T]>,
1523    {
1524        // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1525        unsafe { index.get_unchecked(self) }
1526    }
1527
1528    #[doc = include_str!("docs/as_uninit_slice.md")]
1529    #[inline]
1530    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1531    pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1532        if self.is_null() {
1533            None
1534        } else {
1535            // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1536            Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1537        }
1538    }
1539}
1540
1541impl<T> *const T {
1542    /// Casts from a pointer-to-`T` to a pointer-to-`[T; N]`.
1543    #[inline]
1544    #[unstable(feature = "ptr_cast_array", issue = "144514")]
1545    pub const fn cast_array<const N: usize>(self) -> *const [T; N] {
1546        self.cast()
1547    }
1548}
1549
1550impl<T, const N: usize> *const [T; N] {
1551    /// Returns a raw pointer to the array's buffer.
1552    ///
1553    /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1554    ///
1555    /// # Examples
1556    ///
1557    /// ```rust
1558    /// #![feature(array_ptr_get)]
1559    /// use std::ptr;
1560    ///
1561    /// let arr: *const [i8; 3] = ptr::null();
1562    /// assert_eq!(arr.as_ptr(), ptr::null());
1563    /// ```
1564    #[inline(always)]
1565    #[unstable(feature = "array_ptr_get", issue = "119834")]
1566    pub const fn as_ptr(self) -> *const T {
1567        self as *const T
1568    }
1569
1570    /// Returns a raw pointer to a slice containing the entire array.
1571    ///
1572    /// # Examples
1573    ///
1574    /// ```
1575    /// #![feature(array_ptr_get)]
1576    ///
1577    /// let arr: *const [i32; 3] = &[1, 2, 4] as *const [i32; 3];
1578    /// let slice: *const [i32] = arr.as_slice();
1579    /// assert_eq!(slice.len(), 3);
1580    /// ```
1581    #[inline]
1582    #[unstable(feature = "array_ptr_get", issue = "119834")]
1583    pub const fn as_slice(self) -> *const [T] {
1584        self
1585    }
1586}
1587
1588/// Pointer equality is by address, as produced by the [`<*const T>::addr`](pointer::addr) method.
1589#[stable(feature = "rust1", since = "1.0.0")]
1590#[diagnostic::on_const(
1591    message = "pointers cannot be reliably compared during const eval",
1592    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1593)]
1594impl<T: PointeeSized> PartialEq for *const T {
1595    #[inline(always)]
1596    #[allow(ambiguous_wide_pointer_comparisons)]
1597    fn eq(&self, other: &*const T) -> bool {
1598        *self == *other
1599    }
1600}
1601
1602/// Pointer equality is an equivalence relation.
1603#[stable(feature = "rust1", since = "1.0.0")]
1604#[diagnostic::on_const(
1605    message = "pointers cannot be reliably compared during const eval",
1606    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1607)]
1608impl<T: PointeeSized> Eq for *const T {}
1609
1610/// Pointer comparison is by address, as produced by the [`<*const T>::addr`](pointer::addr) method.
1611#[stable(feature = "rust1", since = "1.0.0")]
1612#[diagnostic::on_const(
1613    message = "pointers cannot be reliably compared during const eval",
1614    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1615)]
1616impl<T: PointeeSized> Ord for *const T {
1617    #[inline]
1618    #[allow(ambiguous_wide_pointer_comparisons)]
1619    fn cmp(&self, other: &*const T) -> Ordering {
1620        if self < other {
1621            Less
1622        } else if self == other {
1623            Equal
1624        } else {
1625            Greater
1626        }
1627    }
1628}
1629
1630/// Pointer comparison is by address, as produced by the [`<*const T>::addr`](pointer::addr) method.
1631#[stable(feature = "rust1", since = "1.0.0")]
1632#[diagnostic::on_const(
1633    message = "pointers cannot be reliably compared during const eval",
1634    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1635)]
1636impl<T: PointeeSized> PartialOrd for *const T {
1637    #[inline(always)]
1638    #[allow(ambiguous_wide_pointer_comparisons)]
1639    fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
1640        Some(self.cmp(other))
1641    }
1642
1643    #[inline(always)]
1644    #[allow(ambiguous_wide_pointer_comparisons)]
1645    fn lt(&self, other: &*const T) -> bool {
1646        *self < *other
1647    }
1648
1649    #[inline(always)]
1650    #[allow(ambiguous_wide_pointer_comparisons)]
1651    fn le(&self, other: &*const T) -> bool {
1652        *self <= *other
1653    }
1654
1655    #[inline(always)]
1656    #[allow(ambiguous_wide_pointer_comparisons)]
1657    fn gt(&self, other: &*const T) -> bool {
1658        *self > *other
1659    }
1660
1661    #[inline(always)]
1662    #[allow(ambiguous_wide_pointer_comparisons)]
1663    fn ge(&self, other: &*const T) -> bool {
1664        *self >= *other
1665    }
1666}
1667
1668#[stable(feature = "raw_ptr_default", since = "1.88.0")]
1669impl<T: ?Sized + Thin> Default for *const T {
1670    /// Returns the default value of [`null()`][crate::ptr::null].
1671    fn default() -> Self {
1672        crate::ptr::null()
1673    }
1674}