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