core/ptr/
const_ptr.rs

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