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