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(lossy_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 `(self as isize -
581    /// origin as isize) / size_of::<T>()`.
582    // FIXME: recommend `addr()` instead of `as usize` once that is stable.
583    ///
584    /// [`add`]: #method.add
585    /// [allocation]: crate::ptr#allocation
586    ///
587    /// # Panics
588    ///
589    /// This function panics if `T` is a Zero-Sized Type ("ZST").
590    ///
591    /// # Examples
592    ///
593    /// Basic usage:
594    ///
595    /// ```
596    /// let a = [0; 5];
597    /// let ptr1: *const i32 = &a[1];
598    /// let ptr2: *const i32 = &a[3];
599    /// unsafe {
600    ///     assert_eq!(ptr2.offset_from(ptr1), 2);
601    ///     assert_eq!(ptr1.offset_from(ptr2), -2);
602    ///     assert_eq!(ptr1.offset(2), ptr2);
603    ///     assert_eq!(ptr2.offset(-2), ptr1);
604    /// }
605    /// ```
606    ///
607    /// *Incorrect* usage:
608    ///
609    /// ```rust,no_run
610    /// let ptr1 = Box::into_raw(Box::new(0u8)) as *const u8;
611    /// let ptr2 = Box::into_raw(Box::new(1u8)) as *const u8;
612    /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
613    /// // Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.
614    /// let ptr2_other = (ptr1 as *const u8).wrapping_offset(diff).wrapping_offset(1);
615    /// assert_eq!(ptr2 as usize, ptr2_other as usize);
616    /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
617    /// // computing their offset is undefined behavior, even though
618    /// // they point to addresses that are in-bounds of the same object!
619    /// unsafe {
620    ///     let one = ptr2_other.offset_from(ptr2); // Undefined Behavior! ⚠️
621    /// }
622    /// ```
623    #[stable(feature = "ptr_offset_from", since = "1.47.0")]
624    #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
625    #[inline]
626    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
627    pub const unsafe fn offset_from(self, origin: *const T) -> isize
628    where
629        T: Sized,
630    {
631        let pointee_size = size_of::<T>();
632        assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
633        // SAFETY: the caller must uphold the safety contract for `ptr_offset_from`.
634        unsafe { intrinsics::ptr_offset_from(self, origin) }
635    }
636
637    /// Calculates the distance between two pointers within the same allocation. The returned value is in
638    /// units of **bytes**.
639    ///
640    /// This is purely a convenience for casting to a `u8` pointer and
641    /// using [`offset_from`][pointer::offset_from] on it. See that method for
642    /// documentation and safety requirements.
643    ///
644    /// For non-`Sized` pointees this operation considers only the data pointers,
645    /// ignoring the metadata.
646    #[inline(always)]
647    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
648    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
649    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
650    pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: *const U) -> isize {
651        // SAFETY: the caller must uphold the safety contract for `offset_from`.
652        unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
653    }
654
655    /// Calculates the distance between two pointers within the same allocation, *where it's known that
656    /// `self` is equal to or greater than `origin`*. The returned value is in
657    /// units of T: the distance in bytes is divided by `size_of::<T>()`.
658    ///
659    /// This computes the same value that [`offset_from`](#method.offset_from)
660    /// would compute, but with the added precondition that the offset is
661    /// guaranteed to be non-negative.  This method is equivalent to
662    /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`,
663    /// but it provides slightly more information to the optimizer, which can
664    /// sometimes allow it to optimize slightly better with some backends.
665    ///
666    /// This method can be thought of as recovering the `count` that was passed
667    /// to [`add`](#method.add) (or, with the parameters in the other order,
668    /// to [`sub`](#method.sub)).  The following are all equivalent, assuming
669    /// that their safety preconditions are met:
670    /// ```rust
671    /// # unsafe fn blah(ptr: *const i32, origin: *const i32, count: usize) -> bool { unsafe {
672    /// ptr.offset_from_unsigned(origin) == count
673    /// # &&
674    /// origin.add(count) == ptr
675    /// # &&
676    /// ptr.sub(count) == origin
677    /// # } }
678    /// ```
679    ///
680    /// # Safety
681    ///
682    /// - The distance between the pointers must be non-negative (`self >= origin`)
683    ///
684    /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
685    ///   apply to this method as well; see it for the full details.
686    ///
687    /// Importantly, despite the return type of this method being able to represent
688    /// a larger offset, it's still *not permitted* to pass pointers which differ
689    /// by more than `isize::MAX` *bytes*.  As such, the result of this method will
690    /// always be less than or equal to `isize::MAX as usize`.
691    ///
692    /// # Panics
693    ///
694    /// This function panics if `T` is a Zero-Sized Type ("ZST").
695    ///
696    /// # Examples
697    ///
698    /// ```
699    /// let a = [0; 5];
700    /// let ptr1: *const i32 = &a[1];
701    /// let ptr2: *const i32 = &a[3];
702    /// unsafe {
703    ///     assert_eq!(ptr2.offset_from_unsigned(ptr1), 2);
704    ///     assert_eq!(ptr1.add(2), ptr2);
705    ///     assert_eq!(ptr2.sub(2), ptr1);
706    ///     assert_eq!(ptr2.offset_from_unsigned(ptr2), 0);
707    /// }
708    ///
709    /// // This would be incorrect, as the pointers are not correctly ordered:
710    /// // ptr1.offset_from_unsigned(ptr2)
711    /// ```
712    #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
713    #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
714    #[inline]
715    #[track_caller]
716    #[ferrocene::prevalidated]
717    pub const unsafe fn offset_from_unsigned(self, origin: *const T) -> usize
718    where
719        T: Sized,
720    {
721        #[rustc_allow_const_fn_unstable(const_eval_select)]
722        #[ferrocene::prevalidated]
723        const fn runtime_ptr_ge(this: *const (), origin: *const ()) -> bool {
724            const_eval_select!(
725                @capture { this: *const (), origin: *const () } -> bool:
726                if const {
727                    true
728                } else {
729                    this >= origin
730                }
731            )
732        }
733
734        ub_checks::assert_unsafe_precondition!(
735            check_language_ub,
736            "ptr::offset_from_unsigned requires `self >= origin`",
737            (
738                this: *const () = self as *const (),
739                origin: *const () = origin as *const (),
740            ) => runtime_ptr_ge(this, origin)
741        );
742
743        let pointee_size = size_of::<T>();
744        assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
745        // SAFETY: the caller must uphold the safety contract for `ptr_offset_from_unsigned`.
746        unsafe { intrinsics::ptr_offset_from_unsigned(self, origin) }
747    }
748
749    /// Calculates the distance between two pointers within the same allocation, *where it's known that
750    /// `self` is equal to or greater than `origin`*. The returned value is in
751    /// units of **bytes**.
752    ///
753    /// This is purely a convenience for casting to a `u8` pointer and
754    /// using [`offset_from_unsigned`][pointer::offset_from_unsigned] on it.
755    /// See that method for documentation and safety requirements.
756    ///
757    /// For non-`Sized` pointees this operation considers only the data pointers,
758    /// ignoring the metadata.
759    #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
760    #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
761    #[inline]
762    #[track_caller]
763    pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: *const U) -> usize {
764        // SAFETY: the caller must uphold the safety contract for `offset_from_unsigned`.
765        unsafe { self.cast::<u8>().offset_from_unsigned(origin.cast::<u8>()) }
766    }
767
768    /// Returns whether two pointers are guaranteed to be equal.
769    ///
770    /// At runtime this function behaves like `Some(self == other)`.
771    /// However, in some contexts (e.g., compile-time evaluation),
772    /// it is not always possible to determine equality of two pointers, so this function may
773    /// spuriously return `None` for pointers that later actually turn out to have its equality known.
774    /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
775    ///
776    /// The return value may change from `Some` to `None` and vice versa depending on the compiler
777    /// version and unsafe code must not
778    /// rely on the result of this function for soundness. It is suggested to only use this function
779    /// for performance optimizations where spurious `None` return values by this function do not
780    /// affect the outcome, but just the performance.
781    /// The consequences of using this method to make runtime and compile-time code behave
782    /// differently have not been explored. This method should not be used to introduce such
783    /// differences, and it should also not be stabilized before we have a better understanding
784    /// of this issue.
785    #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
786    #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
787    #[inline]
788    #[ferrocene::prevalidated]
789    pub const fn guaranteed_eq(self, other: *const T) -> Option<bool>
790    where
791        T: Sized,
792    {
793        match intrinsics::ptr_guaranteed_cmp(self, other) {
794            #[ferrocene::annotation(
795                "This cannot be reached in runtime code so it cannot be covered."
796            )]
797            2 => None,
798            other => Some(other == 1),
799        }
800    }
801
802    /// Returns whether two pointers are guaranteed to be inequal.
803    ///
804    /// At runtime this function behaves like `Some(self != other)`.
805    /// However, in some contexts (e.g., compile-time evaluation),
806    /// it is not always possible to determine inequality of two pointers, so this function may
807    /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
808    /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
809    ///
810    /// The return value may change from `Some` to `None` and vice versa depending on the compiler
811    /// version and unsafe code must not
812    /// rely on the result of this function for soundness. It is suggested to only use this function
813    /// for performance optimizations where spurious `None` return values by this function do not
814    /// affect the outcome, but just the performance.
815    /// The consequences of using this method to make runtime and compile-time code behave
816    /// differently have not been explored. This method should not be used to introduce such
817    /// differences, and it should also not be stabilized before we have a better understanding
818    /// of this issue.
819    #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
820    #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
821    #[inline]
822    pub const fn guaranteed_ne(self, other: *const T) -> Option<bool>
823    where
824        T: Sized,
825    {
826        match self.guaranteed_eq(other) {
827            None => None,
828            Some(eq) => Some(!eq),
829        }
830    }
831
832    #[doc = include_str!("./docs/add.md")]
833    ///
834    /// Consider using [`wrapping_add`](#method.wrapping_add) instead if these constraints are
835    /// difficult to satisfy. The only advantage of this method is that it
836    /// enables more aggressive compiler optimizations.
837    ///
838    /// # Examples
839    ///
840    /// ```
841    /// let s: &str = "123";
842    /// let ptr: *const u8 = s.as_ptr();
843    ///
844    /// unsafe {
845    ///     assert_eq!(*ptr.add(1), b'2');
846    ///     assert_eq!(*ptr.add(2), b'3');
847    /// }
848    /// ```
849    #[stable(feature = "pointer_methods", since = "1.26.0")]
850    #[must_use = "returns a new pointer rather than modifying its argument"]
851    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
852    #[inline(always)]
853    #[track_caller]
854    #[ferrocene::prevalidated]
855    pub const unsafe fn add(self, count: usize) -> Self
856    where
857        T: Sized,
858    {
859        #[cfg(debug_assertions)]
860        #[inline]
861        #[rustc_allow_const_fn_unstable(const_eval_select)]
862        #[ferrocene::prevalidated]
863        const fn runtime_add_nowrap(this: *const (), count: usize, size: usize) -> bool {
864            const_eval_select!(
865                @capture { this: *const (), count: usize, size: usize } -> bool:
866                if const {
867                    true
868                } else {
869                    let Some(byte_offset) = count.checked_mul(size) else {
870                        return false;
871                    };
872                    let (_, overflow) = this.addr().overflowing_add(byte_offset);
873                    byte_offset <= (isize::MAX as usize) && !overflow
874                }
875            )
876        }
877
878        #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
879        ub_checks::assert_unsafe_precondition!(
880            check_language_ub,
881            "ptr::add requires that the address calculation does not overflow",
882            (
883                this: *const () = self as *const (),
884                count: usize = count,
885                size: usize = size_of::<T>(),
886            ) => runtime_add_nowrap(this, count, size)
887        );
888
889        // SAFETY: the caller must uphold the safety contract for `offset`.
890        unsafe { intrinsics::offset(self, count) }
891    }
892
893    /// Adds an unsigned offset in bytes to a pointer.
894    ///
895    /// `count` is in units of bytes.
896    ///
897    /// This is purely a convenience for casting to a `u8` pointer and
898    /// using [add][pointer::add] on it. See that method for documentation
899    /// and safety requirements.
900    ///
901    /// For non-`Sized` pointees this operation changes only the data pointer,
902    /// leaving the metadata untouched.
903    #[must_use]
904    #[inline(always)]
905    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
906    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
907    #[track_caller]
908    #[ferrocene::prevalidated]
909    pub const unsafe fn byte_add(self, count: usize) -> Self {
910        // SAFETY: the caller must uphold the safety contract for `add`.
911        unsafe { self.cast::<u8>().add(count).with_metadata_of(self) }
912    }
913
914    #[doc = include_str!("./docs/sub.md")]
915    ///
916    /// Consider using [`wrapping_sub`](#method.wrapping_sub) instead if these constraints are
917    /// difficult to satisfy. The only advantage of this method is that it
918    /// enables more aggressive compiler optimizations.
919    ///
920    /// # Examples
921    ///
922    /// ```
923    /// let s: &str = "123";
924    ///
925    /// unsafe {
926    ///     let end: *const u8 = s.as_ptr().add(3);
927    ///     assert_eq!(*end.sub(1), b'3');
928    ///     assert_eq!(*end.sub(2), b'2');
929    /// }
930    /// ```
931    #[stable(feature = "pointer_methods", since = "1.26.0")]
932    #[must_use = "returns a new pointer rather than modifying its argument"]
933    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
934    #[inline(always)]
935    #[track_caller]
936    pub const unsafe fn sub(self, count: usize) -> Self
937    where
938        T: Sized,
939    {
940        #[cfg(debug_assertions)]
941        #[inline]
942        #[rustc_allow_const_fn_unstable(const_eval_select)]
943        #[ferrocene::prevalidated]
944        const fn runtime_sub_nowrap(this: *const (), count: usize, size: usize) -> bool {
945            const_eval_select!(
946                @capture { this: *const (), count: usize, size: usize } -> bool:
947                if const {
948                    true
949                } else {
950                    let Some(byte_offset) = count.checked_mul(size) else {
951                        return false;
952                    };
953                    byte_offset <= (isize::MAX as usize) && this.addr() >= byte_offset
954                }
955            )
956        }
957
958        #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
959        ub_checks::assert_unsafe_precondition!(
960            check_language_ub,
961            "ptr::sub requires that the address calculation does not overflow",
962            (
963                this: *const () = self as *const (),
964                count: usize = count,
965                size: usize = size_of::<T>(),
966            ) => runtime_sub_nowrap(this, count, size)
967        );
968
969        if T::IS_ZST {
970            // Pointer arithmetic does nothing when the pointee is a ZST.
971            self
972        } else {
973            // SAFETY: the caller must uphold the safety contract for `offset`.
974            // Because the pointee is *not* a ZST, that means that `count` is
975            // at most `isize::MAX`, and thus the negation cannot overflow.
976            unsafe { intrinsics::offset(self, intrinsics::unchecked_sub(0, count as isize)) }
977        }
978    }
979
980    /// Subtracts an unsigned offset in bytes from a pointer.
981    ///
982    /// `count` is in units of bytes.
983    ///
984    /// This is purely a convenience for casting to a `u8` pointer and
985    /// using [sub][pointer::sub] on it. See that method for documentation
986    /// and safety requirements.
987    ///
988    /// For non-`Sized` pointees this operation changes only the data pointer,
989    /// leaving the metadata untouched.
990    #[must_use]
991    #[inline(always)]
992    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
993    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
994    #[track_caller]
995    pub const unsafe fn byte_sub(self, count: usize) -> Self {
996        // SAFETY: the caller must uphold the safety contract for `sub`.
997        unsafe { self.cast::<u8>().sub(count).with_metadata_of(self) }
998    }
999
1000    /// Adds an unsigned offset to a pointer using wrapping arithmetic.
1001    ///
1002    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1003    /// offset of `3 * size_of::<T>()` bytes.
1004    ///
1005    /// # Safety
1006    ///
1007    /// This operation itself is always safe, but using the resulting pointer is not.
1008    ///
1009    /// The resulting pointer "remembers" the [allocation] that `self` points to; it must not
1010    /// be used to read or write other allocations.
1011    ///
1012    /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1013    /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1014    /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1015    /// `x` and `y` point into the same allocation.
1016    ///
1017    /// Compared to [`add`], this method basically delays the requirement of staying within the
1018    /// same allocation: [`add`] is immediate Undefined Behavior when crossing object
1019    /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1020    /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1021    /// can be optimized better and is thus preferable in performance-sensitive code.
1022    ///
1023    /// The delayed check only considers the value of the pointer that was dereferenced, not the
1024    /// intermediate values used during the computation of the final result. For example,
1025    /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1026    /// allocation and then re-entering it later is permitted.
1027    ///
1028    /// [`add`]: #method.add
1029    /// [allocation]: crate::ptr#allocation
1030    ///
1031    /// # Examples
1032    ///
1033    /// ```
1034    /// # use std::fmt::Write;
1035    /// // Iterate using a raw pointer in increments of two elements
1036    /// let data = [1u8, 2, 3, 4, 5];
1037    /// let mut ptr: *const u8 = data.as_ptr();
1038    /// let step = 2;
1039    /// let end_rounded_up = ptr.wrapping_add(6);
1040    ///
1041    /// let mut out = String::new();
1042    /// while ptr != end_rounded_up {
1043    ///     unsafe {
1044    ///         write!(&mut out, "{}, ", *ptr)?;
1045    ///     }
1046    ///     ptr = ptr.wrapping_add(step);
1047    /// }
1048    /// assert_eq!(out, "1, 3, 5, ");
1049    /// # std::fmt::Result::Ok(())
1050    /// ```
1051    #[stable(feature = "pointer_methods", since = "1.26.0")]
1052    #[must_use = "returns a new pointer rather than modifying its argument"]
1053    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1054    #[inline(always)]
1055    #[ferrocene::prevalidated]
1056    pub const fn wrapping_add(self, count: usize) -> Self
1057    where
1058        T: Sized,
1059    {
1060        self.wrapping_offset(count as isize)
1061    }
1062
1063    /// Adds an unsigned offset in bytes to a pointer using wrapping arithmetic.
1064    ///
1065    /// `count` is in units of bytes.
1066    ///
1067    /// This is purely a convenience for casting to a `u8` pointer and
1068    /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1069    ///
1070    /// For non-`Sized` pointees this operation changes only the data pointer,
1071    /// leaving the metadata untouched.
1072    #[must_use]
1073    #[inline(always)]
1074    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1075    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1076    pub const fn wrapping_byte_add(self, count: usize) -> Self {
1077        self.cast::<u8>().wrapping_add(count).with_metadata_of(self)
1078    }
1079
1080    /// Subtracts an unsigned offset from a pointer using wrapping arithmetic.
1081    ///
1082    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1083    /// offset of `3 * size_of::<T>()` bytes.
1084    ///
1085    /// # Safety
1086    ///
1087    /// This operation itself is always safe, but using the resulting pointer is not.
1088    ///
1089    /// The resulting pointer "remembers" the [allocation] that `self` points to; it must not
1090    /// be used to read or write other allocations.
1091    ///
1092    /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1093    /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1094    /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1095    /// `x` and `y` point into the same allocation.
1096    ///
1097    /// Compared to [`sub`], this method basically delays the requirement of staying within the
1098    /// same allocation: [`sub`] is immediate Undefined Behavior when crossing object
1099    /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1100    /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1101    /// can be optimized better and is thus preferable in performance-sensitive code.
1102    ///
1103    /// The delayed check only considers the value of the pointer that was dereferenced, not the
1104    /// intermediate values used during the computation of the final result. For example,
1105    /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1106    /// allocation and then re-entering it later is permitted.
1107    ///
1108    /// [`sub`]: #method.sub
1109    /// [allocation]: crate::ptr#allocation
1110    ///
1111    /// # Examples
1112    ///
1113    /// ```
1114    /// # use std::fmt::Write;
1115    /// // Iterate using a raw pointer in increments of two elements (backwards)
1116    /// let data = [1u8, 2, 3, 4, 5];
1117    /// let mut ptr: *const u8 = data.as_ptr();
1118    /// let start_rounded_down = ptr.wrapping_sub(2);
1119    /// ptr = ptr.wrapping_add(4);
1120    /// let step = 2;
1121    /// let mut out = String::new();
1122    /// while ptr != start_rounded_down {
1123    ///     unsafe {
1124    ///         write!(&mut out, "{}, ", *ptr)?;
1125    ///     }
1126    ///     ptr = ptr.wrapping_sub(step);
1127    /// }
1128    /// assert_eq!(out, "5, 3, 1, ");
1129    /// # std::fmt::Result::Ok(())
1130    /// ```
1131    #[stable(feature = "pointer_methods", since = "1.26.0")]
1132    #[must_use = "returns a new pointer rather than modifying its argument"]
1133    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1134    #[inline(always)]
1135    pub const fn wrapping_sub(self, count: usize) -> Self
1136    where
1137        T: Sized,
1138    {
1139        self.wrapping_offset((count as isize).wrapping_neg())
1140    }
1141
1142    /// Subtracts an unsigned offset in bytes from a pointer using wrapping arithmetic.
1143    ///
1144    /// `count` is in units of bytes.
1145    ///
1146    /// This is purely a convenience for casting to a `u8` pointer and
1147    /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1148    ///
1149    /// For non-`Sized` pointees this operation changes only the data pointer,
1150    /// leaving the metadata untouched.
1151    #[must_use]
1152    #[inline(always)]
1153    #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1154    #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1155    pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1156        self.cast::<u8>().wrapping_sub(count).with_metadata_of(self)
1157    }
1158
1159    /// Reads the value from `self` without moving it. This leaves the
1160    /// memory in `self` unchanged.
1161    ///
1162    /// See [`ptr::read`] for safety concerns and examples.
1163    ///
1164    /// [`ptr::read`]: crate::ptr::read()
1165    #[stable(feature = "pointer_methods", since = "1.26.0")]
1166    #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1167    #[inline]
1168    #[track_caller]
1169    #[ferrocene::prevalidated]
1170    pub const unsafe fn read(self) -> T
1171    where
1172        T: Sized,
1173    {
1174        // SAFETY: the caller must uphold the safety contract for `read`.
1175        unsafe { read(self) }
1176    }
1177
1178    /// Performs a volatile read of the value from `self` without moving it. This
1179    /// leaves the memory in `self` unchanged.
1180    ///
1181    /// Volatile operations are intended to act on I/O memory, and are guaranteed
1182    /// to not be elided or reordered by the compiler across other volatile
1183    /// operations.
1184    ///
1185    /// See [`ptr::read_volatile`] for safety concerns and examples.
1186    ///
1187    /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1188    #[stable(feature = "pointer_methods", since = "1.26.0")]
1189    #[inline]
1190    #[track_caller]
1191    pub 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    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1534    ///
1535    /// # Examples
1536    ///
1537    /// ```
1538    /// #![feature(slice_ptr_get)]
1539    ///
1540    /// let x = &[1, 2, 4] as *const [i32];
1541    ///
1542    /// unsafe {
1543    ///     assert_eq!(x.get_unchecked(1), x.as_ptr().add(1));
1544    /// }
1545    /// ```
1546    #[unstable(feature = "slice_ptr_get", issue = "74265")]
1547    #[rustc_const_unstable(feature = "const_index", issue = "143775")]
1548    #[inline]
1549    pub const unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output
1550    where
1551        I: [const] SliceIndex<[T]>,
1552    {
1553        // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1554        unsafe { index.get_unchecked(self) }
1555    }
1556
1557    #[doc = include_str!("docs/as_uninit_slice.md")]
1558    #[inline]
1559    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1560    pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1561        if self.is_null() {
1562            None
1563        } else {
1564            // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1565            Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1566        }
1567    }
1568}
1569
1570impl<T> *const T {
1571    /// Casts from a pointer-to-`T` to a pointer-to-`[T; N]`.
1572    #[inline]
1573    #[unstable(feature = "ptr_cast_array", issue = "144514")]
1574    #[ferrocene::prevalidated]
1575    pub const fn cast_array<const N: usize>(self) -> *const [T; N] {
1576        self.cast()
1577    }
1578}
1579
1580impl<T, const N: usize> *const [T; N] {
1581    /// Returns a raw pointer to the array's buffer.
1582    ///
1583    /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1584    ///
1585    /// # Examples
1586    ///
1587    /// ```rust
1588    /// #![feature(array_ptr_get)]
1589    /// use std::ptr;
1590    ///
1591    /// let arr: *const [i8; 3] = ptr::null();
1592    /// assert_eq!(arr.as_ptr(), ptr::null());
1593    /// ```
1594    #[inline]
1595    #[unstable(feature = "array_ptr_get", issue = "119834")]
1596    pub const fn as_ptr(self) -> *const T {
1597        self as *const T
1598    }
1599
1600    /// Returns a raw pointer to a slice containing the entire array.
1601    ///
1602    /// # Examples
1603    ///
1604    /// ```
1605    /// #![feature(array_ptr_get)]
1606    ///
1607    /// let arr: *const [i32; 3] = &[1, 2, 4] as *const [i32; 3];
1608    /// let slice: *const [i32] = arr.as_slice();
1609    /// assert_eq!(slice.len(), 3);
1610    /// ```
1611    #[inline]
1612    #[unstable(feature = "array_ptr_get", issue = "119834")]
1613    pub const fn as_slice(self) -> *const [T] {
1614        self
1615    }
1616}
1617
1618/// Pointer equality is by address, as produced by the [`<*const T>::addr`](pointer::addr) method.
1619#[stable(feature = "rust1", since = "1.0.0")]
1620#[diagnostic::on_const(
1621    message = "pointers cannot be reliably compared during const eval",
1622    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1623)]
1624impl<T: PointeeSized> PartialEq for *const T {
1625    #[inline]
1626    #[allow(ambiguous_wide_pointer_comparisons)]
1627    #[ferrocene::prevalidated]
1628    fn eq(&self, other: &*const T) -> bool {
1629        *self == *other
1630    }
1631}
1632
1633/// Pointer equality is an equivalence relation.
1634#[stable(feature = "rust1", since = "1.0.0")]
1635#[diagnostic::on_const(
1636    message = "pointers cannot be reliably compared during const eval",
1637    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1638)]
1639impl<T: PointeeSized> Eq for *const T {}
1640
1641/// Pointer comparison is by address, as produced by the `[`<*const T>::addr`](pointer::addr)` method.
1642#[stable(feature = "rust1", since = "1.0.0")]
1643#[diagnostic::on_const(
1644    message = "pointers cannot be reliably compared during const eval",
1645    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1646)]
1647impl<T: PointeeSized> Ord for *const T {
1648    #[inline]
1649    #[allow(ambiguous_wide_pointer_comparisons)]
1650    #[ferrocene::prevalidated]
1651    fn cmp(&self, other: &*const T) -> Ordering {
1652        if self < other {
1653            Less
1654        } else if self == other {
1655            Equal
1656        } else {
1657            Greater
1658        }
1659    }
1660}
1661
1662/// Pointer comparison is by address, as produced by the `[`<*const T>::addr`](pointer::addr)` method.
1663#[stable(feature = "rust1", since = "1.0.0")]
1664#[diagnostic::on_const(
1665    message = "pointers cannot be reliably compared during const eval",
1666    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1667)]
1668impl<T: PointeeSized> PartialOrd for *const T {
1669    #[inline]
1670    #[allow(ambiguous_wide_pointer_comparisons)]
1671    #[ferrocene::prevalidated]
1672    fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
1673        Some(self.cmp(other))
1674    }
1675
1676    #[inline]
1677    #[allow(ambiguous_wide_pointer_comparisons)]
1678    #[ferrocene::prevalidated]
1679    fn lt(&self, other: &*const T) -> bool {
1680        *self < *other
1681    }
1682
1683    #[inline]
1684    #[allow(ambiguous_wide_pointer_comparisons)]
1685    #[ferrocene::prevalidated]
1686    fn le(&self, other: &*const T) -> bool {
1687        *self <= *other
1688    }
1689
1690    #[inline]
1691    #[allow(ambiguous_wide_pointer_comparisons)]
1692    #[ferrocene::prevalidated]
1693    fn gt(&self, other: &*const T) -> bool {
1694        *self > *other
1695    }
1696
1697    #[inline]
1698    #[allow(ambiguous_wide_pointer_comparisons)]
1699    #[ferrocene::prevalidated]
1700    fn ge(&self, other: &*const T) -> bool {
1701        *self >= *other
1702    }
1703}
1704
1705#[stable(feature = "raw_ptr_default", since = "1.88.0")]
1706impl<T: ?Sized + Thin> Default for *const T {
1707    /// Returns the default value of [`null()`][crate::ptr::null].
1708    fn default() -> Self {
1709        crate::ptr::null()
1710    }
1711}