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