core/ptr/
const_ptr.rs

1use super::*;
2#[cfg(not(feature = "ferrocene_certified"))]
3use crate::cmp::Ordering::{Equal, Greater, Less};
4#[cfg(not(feature = "ferrocene_certified"))]
5use crate::intrinsics::const_eval_select;
6#[cfg(not(feature = "ferrocene_certified"))]
7use crate::mem::{self, SizedTypeProperties};
8#[cfg(not(feature = "ferrocene_certified"))]
9use crate::slice::{self, SliceIndex};
10// Ferrocene addition: imports used by certified subset
11#[cfg(feature = "ferrocene_certified")]
12use crate::{intrinsics::const_eval_select, 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    #[cfg(not(feature = "ferrocene_certified"))]
725    pub const unsafe fn offset_from_unsigned(self, origin: *const T) -> usize
726    where
727        T: Sized,
728    {
729        #[rustc_allow_const_fn_unstable(const_eval_select)]
730        const fn runtime_ptr_ge(this: *const (), origin: *const ()) -> bool {
731            const_eval_select!(
732                @capture { this: *const (), origin: *const () } -> bool:
733                if const {
734                    true
735                } else {
736                    this >= origin
737                }
738            )
739        }
740
741        ub_checks::assert_unsafe_precondition!(
742            check_language_ub,
743            "ptr::offset_from_unsigned requires `self >= origin`",
744            (
745                this: *const () = self as *const (),
746                origin: *const () = origin as *const (),
747            ) => runtime_ptr_ge(this, origin)
748        );
749
750        let pointee_size = size_of::<T>();
751        assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
752        // SAFETY: the caller must uphold the safety contract for `ptr_offset_from_unsigned`.
753        unsafe { intrinsics::ptr_offset_from_unsigned(self, origin) }
754    }
755
756    /// Calculates the distance between two pointers within the same allocation, *where it's known that
757    /// `self` is equal to or greater than `origin`*. The returned value is in
758    /// units of **bytes**.
759    ///
760    /// This is purely a convenience for casting to a `u8` pointer and
761    /// using [`offset_from_unsigned`][pointer::offset_from_unsigned] on it.
762    /// See that method for documentation and safety requirements.
763    ///
764    /// For non-`Sized` pointees this operation considers only the data pointers,
765    /// ignoring the metadata.
766    #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
767    #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
768    #[inline]
769    #[track_caller]
770    #[cfg(not(feature = "ferrocene_certified"))]
771    pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: *const U) -> usize {
772        // SAFETY: the caller must uphold the safety contract for `offset_from_unsigned`.
773        unsafe { self.cast::<u8>().offset_from_unsigned(origin.cast::<u8>()) }
774    }
775
776    /// Returns whether two pointers are guaranteed to be equal.
777    ///
778    /// At runtime this function behaves like `Some(self == other)`.
779    /// However, in some contexts (e.g., compile-time evaluation),
780    /// it is not always possible to determine equality of two pointers, so this function may
781    /// spuriously return `None` for pointers that later actually turn out to have its equality known.
782    /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
783    ///
784    /// The return value may change from `Some` to `None` and vice versa depending on the compiler
785    /// version and unsafe code must not
786    /// rely on the result of this function for soundness. It is suggested to only use this function
787    /// for performance optimizations where spurious `None` return values by this function do not
788    /// affect the outcome, but just the performance.
789    /// The consequences of using this method to make runtime and compile-time code behave
790    /// differently have not been explored. This method should not be used to introduce such
791    /// differences, and it should also not be stabilized before we have a better understanding
792    /// of this issue.
793    #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
794    #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
795    #[inline]
796    pub const fn guaranteed_eq(self, other: *const T) -> Option<bool>
797    where
798        T: Sized,
799    {
800        match intrinsics::ptr_guaranteed_cmp(self, other) {
801            // Ferrocene annotation: This cannot be reached in runtime code so it cannot be covered.
802            2 => None,
803            other => Some(other == 1),
804        }
805    }
806
807    /// Returns whether two pointers are guaranteed to be inequal.
808    ///
809    /// At runtime this function behaves like `Some(self != other)`.
810    /// However, in some contexts (e.g., compile-time evaluation),
811    /// it is not always possible to determine inequality of two pointers, so this function may
812    /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
813    /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
814    ///
815    /// The return value may change from `Some` to `None` and vice versa depending on the compiler
816    /// version and unsafe code must not
817    /// rely on the result of this function for soundness. It is suggested to only use this function
818    /// for performance optimizations where spurious `None` return values by this function do not
819    /// affect the outcome, but just the performance.
820    /// The consequences of using this method to make runtime and compile-time code behave
821    /// differently have not been explored. This method should not be used to introduce such
822    /// differences, and it should also not be stabilized before we have a better understanding
823    /// of this issue.
824    #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
825    #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
826    #[inline]
827    #[cfg(not(feature = "ferrocene_certified"))]
828    pub const fn guaranteed_ne(self, other: *const T) -> Option<bool>
829    where
830        T: Sized,
831    {
832        match self.guaranteed_eq(other) {
833            None => None,
834            Some(eq) => Some(!eq),
835        }
836    }
837
838    #[doc = include_str!("./docs/add.md")]
839    ///
840    /// # Examples
841    ///
842    /// ```
843    /// let s: &str = "123";
844    /// let ptr: *const u8 = s.as_ptr();
845    ///
846    /// unsafe {
847    ///     assert_eq!(*ptr.add(1), b'2');
848    ///     assert_eq!(*ptr.add(2), b'3');
849    /// }
850    /// ```
851    #[stable(feature = "pointer_methods", since = "1.26.0")]
852    #[must_use = "returns a new pointer rather than modifying its argument"]
853    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
854    #[inline(always)]
855    #[track_caller]
856    #[cfg(not(feature = "ferrocene_certified"))]
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    #[cfg(not(feature = "ferrocene_certified"))]
1202    pub const unsafe fn read(self) -> T
1203    where
1204        T: Sized,
1205    {
1206        // SAFETY: the caller must uphold the safety contract for `read`.
1207        unsafe { read(self) }
1208    }
1209
1210    /// Performs a volatile read of the value from `self` without moving it. This
1211    /// leaves the memory in `self` unchanged.
1212    ///
1213    /// Volatile operations are intended to act on I/O memory, and are guaranteed
1214    /// to not be elided or reordered by the compiler across other volatile
1215    /// operations.
1216    ///
1217    /// See [`ptr::read_volatile`] for safety concerns and examples.
1218    ///
1219    /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1220    #[stable(feature = "pointer_methods", since = "1.26.0")]
1221    #[inline]
1222    #[track_caller]
1223    #[cfg(not(feature = "ferrocene_certified"))]
1224    pub unsafe fn read_volatile(self) -> T
1225    where
1226        T: Sized,
1227    {
1228        // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1229        unsafe { read_volatile(self) }
1230    }
1231
1232    /// Reads the value from `self` without moving it. This leaves the
1233    /// memory in `self` unchanged.
1234    ///
1235    /// Unlike `read`, the pointer may be unaligned.
1236    ///
1237    /// See [`ptr::read_unaligned`] for safety concerns and examples.
1238    ///
1239    /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1240    #[stable(feature = "pointer_methods", since = "1.26.0")]
1241    #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1242    #[inline]
1243    #[track_caller]
1244    #[cfg(not(feature = "ferrocene_certified"))]
1245    pub const unsafe fn read_unaligned(self) -> T
1246    where
1247        T: Sized,
1248    {
1249        // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1250        unsafe { read_unaligned(self) }
1251    }
1252
1253    /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1254    /// and destination may overlap.
1255    ///
1256    /// NOTE: this has the *same* argument order as [`ptr::copy`].
1257    ///
1258    /// See [`ptr::copy`] for safety concerns and examples.
1259    ///
1260    /// [`ptr::copy`]: crate::ptr::copy()
1261    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1262    #[stable(feature = "pointer_methods", since = "1.26.0")]
1263    #[inline]
1264    #[track_caller]
1265    #[cfg(not(feature = "ferrocene_certified"))]
1266    pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1267    where
1268        T: Sized,
1269    {
1270        // SAFETY: the caller must uphold the safety contract for `copy`.
1271        unsafe { copy(self, dest, count) }
1272    }
1273
1274    /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1275    /// and destination may *not* overlap.
1276    ///
1277    /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1278    ///
1279    /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1280    ///
1281    /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1282    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1283    #[stable(feature = "pointer_methods", since = "1.26.0")]
1284    #[inline]
1285    #[track_caller]
1286    #[cfg(not(feature = "ferrocene_certified"))]
1287    pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1288    where
1289        T: Sized,
1290    {
1291        // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1292        unsafe { copy_nonoverlapping(self, dest, count) }
1293    }
1294
1295    /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1296    /// `align`.
1297    ///
1298    /// If it is not possible to align the pointer, the implementation returns
1299    /// `usize::MAX`.
1300    ///
1301    /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1302    /// used with the `wrapping_add` method.
1303    ///
1304    /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1305    /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1306    /// the returned offset is correct in all terms other than alignment.
1307    ///
1308    /// # Panics
1309    ///
1310    /// The function panics if `align` is not a power-of-two.
1311    ///
1312    /// # Examples
1313    ///
1314    /// Accessing adjacent `u8` as `u16`
1315    ///
1316    /// ```
1317    /// # unsafe {
1318    /// let x = [5_u8, 6, 7, 8, 9];
1319    /// let ptr = x.as_ptr();
1320    /// let offset = ptr.align_offset(align_of::<u16>());
1321    ///
1322    /// if offset < x.len() - 1 {
1323    ///     let u16_ptr = ptr.add(offset).cast::<u16>();
1324    ///     assert!(*u16_ptr == u16::from_ne_bytes([5, 6]) || *u16_ptr == u16::from_ne_bytes([6, 7]));
1325    /// } else {
1326    ///     // while the pointer can be aligned via `offset`, it would point
1327    ///     // outside the allocation
1328    /// }
1329    /// # }
1330    /// ```
1331    #[must_use]
1332    #[inline]
1333    #[stable(feature = "align_offset", since = "1.36.0")]
1334    #[cfg(not(feature = "ferrocene_certified"))]
1335    pub fn align_offset(self, align: usize) -> usize
1336    where
1337        T: Sized,
1338    {
1339        if !align.is_power_of_two() {
1340            panic!("align_offset: align is not a power-of-two");
1341        }
1342
1343        // SAFETY: `align` has been checked to be a power of 2 above
1344        let ret = unsafe { align_offset(self, align) };
1345
1346        // Inform Miri that we want to consider the resulting pointer to be suitably aligned.
1347        #[cfg(miri)]
1348        if ret != usize::MAX {
1349            intrinsics::miri_promise_symbolic_alignment(self.wrapping_add(ret).cast(), align);
1350        }
1351
1352        ret
1353    }
1354
1355    /// Returns whether the pointer is properly aligned for `T`.
1356    ///
1357    /// # Examples
1358    ///
1359    /// ```
1360    /// // On some platforms, the alignment of i32 is less than 4.
1361    /// #[repr(align(4))]
1362    /// struct AlignedI32(i32);
1363    ///
1364    /// let data = AlignedI32(42);
1365    /// let ptr = &data as *const AlignedI32;
1366    ///
1367    /// assert!(ptr.is_aligned());
1368    /// assert!(!ptr.wrapping_byte_add(1).is_aligned());
1369    /// ```
1370    #[must_use]
1371    #[inline]
1372    #[stable(feature = "pointer_is_aligned", since = "1.79.0")]
1373    #[cfg(not(feature = "ferrocene_certified"))]
1374    pub fn is_aligned(self) -> bool
1375    where
1376        T: Sized,
1377    {
1378        self.is_aligned_to(align_of::<T>())
1379    }
1380
1381    /// Returns whether the pointer is aligned to `align`.
1382    ///
1383    /// For non-`Sized` pointees this operation considers only the data pointer,
1384    /// ignoring the metadata.
1385    ///
1386    /// # Panics
1387    ///
1388    /// The function panics if `align` is not a power-of-two (this includes 0).
1389    ///
1390    /// # Examples
1391    ///
1392    /// ```
1393    /// #![feature(pointer_is_aligned_to)]
1394    ///
1395    /// // On some platforms, the alignment of i32 is less than 4.
1396    /// #[repr(align(4))]
1397    /// struct AlignedI32(i32);
1398    ///
1399    /// let data = AlignedI32(42);
1400    /// let ptr = &data as *const AlignedI32;
1401    ///
1402    /// assert!(ptr.is_aligned_to(1));
1403    /// assert!(ptr.is_aligned_to(2));
1404    /// assert!(ptr.is_aligned_to(4));
1405    ///
1406    /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1407    /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1408    ///
1409    /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1410    /// ```
1411    #[must_use]
1412    #[inline]
1413    #[unstable(feature = "pointer_is_aligned_to", issue = "96284")]
1414    pub fn is_aligned_to(self, align: usize) -> bool {
1415        if !align.is_power_of_two() {
1416            panic!("is_aligned_to: align is not a power-of-two");
1417        }
1418
1419        self.addr() & (align - 1) == 0
1420    }
1421}
1422
1423impl<T> *const T {
1424    /// Casts from a type to its maybe-uninitialized version.
1425    #[must_use]
1426    #[inline(always)]
1427    #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1428    #[cfg(not(feature = "ferrocene_certified"))]
1429    pub const fn cast_uninit(self) -> *const MaybeUninit<T> {
1430        self as _
1431    }
1432}
1433#[cfg(not(feature = "ferrocene_certified"))]
1434impl<T> *const MaybeUninit<T> {
1435    /// Casts from a maybe-uninitialized type to its initialized version.
1436    ///
1437    /// This is always safe, since UB can only occur if the pointer is read
1438    /// before being initialized.
1439    #[must_use]
1440    #[inline(always)]
1441    #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1442    pub const fn cast_init(self) -> *const T {
1443        self as _
1444    }
1445}
1446
1447#[cfg(not(feature = "ferrocene_certified"))]
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    pub const fn len(self) -> usize {
1468        metadata(self)
1469    }
1470
1471    /// Returns `true` if the raw slice has a length of 0.
1472    ///
1473    /// # Examples
1474    ///
1475    /// ```
1476    /// use std::ptr;
1477    ///
1478    /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1479    /// assert!(!slice.is_empty());
1480    /// ```
1481    #[inline(always)]
1482    #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1483    #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1484    pub const fn is_empty(self) -> bool {
1485        self.len() == 0
1486    }
1487
1488    /// Returns a raw pointer to the slice's buffer.
1489    ///
1490    /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1491    ///
1492    /// # Examples
1493    ///
1494    /// ```rust
1495    /// #![feature(slice_ptr_get)]
1496    /// use std::ptr;
1497    ///
1498    /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1499    /// assert_eq!(slice.as_ptr(), ptr::null());
1500    /// ```
1501    #[inline]
1502    #[unstable(feature = "slice_ptr_get", issue = "74265")]
1503    pub const fn as_ptr(self) -> *const T {
1504        self as *const T
1505    }
1506
1507    /// Gets a raw pointer to the underlying array.
1508    ///
1509    /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
1510    #[unstable(feature = "slice_as_array", issue = "133508")]
1511    #[inline]
1512    #[must_use]
1513    pub const fn as_array<const N: usize>(self) -> Option<*const [T; N]> {
1514        if self.len() == N {
1515            let me = self.as_ptr() as *const [T; N];
1516            Some(me)
1517        } else {
1518            None
1519        }
1520    }
1521
1522    /// Returns a raw pointer to an element or subslice, without doing bounds
1523    /// checking.
1524    ///
1525    /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
1526    /// is *[undefined behavior]* even if the resulting pointer is not used.
1527    ///
1528    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1529    ///
1530    /// # Examples
1531    ///
1532    /// ```
1533    /// #![feature(slice_ptr_get)]
1534    ///
1535    /// let x = &[1, 2, 4] as *const [i32];
1536    ///
1537    /// unsafe {
1538    ///     assert_eq!(x.get_unchecked(1), x.as_ptr().add(1));
1539    /// }
1540    /// ```
1541    #[unstable(feature = "slice_ptr_get", issue = "74265")]
1542    #[rustc_const_unstable(feature = "const_index", issue = "143775")]
1543    #[inline]
1544    pub const unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output
1545    where
1546        I: [const] SliceIndex<[T]>,
1547    {
1548        // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1549        unsafe { index.get_unchecked(self) }
1550    }
1551
1552    #[doc = include_str!("docs/as_uninit_slice.md")]
1553    #[inline]
1554    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
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")]
1629#[cfg(not(feature = "ferrocene_certified"))]
1630impl<T: PointeeSized> Ord for *const T {
1631    #[inline]
1632    #[allow(ambiguous_wide_pointer_comparisons)]
1633    fn cmp(&self, other: &*const T) -> Ordering {
1634        if self < other {
1635            Less
1636        } else if self == other {
1637            Equal
1638        } else {
1639            Greater
1640        }
1641    }
1642}
1643
1644/// Pointer comparison is by address, as produced by the `[`<*const T>::addr`](pointer::addr)` method.
1645#[stable(feature = "rust1", since = "1.0.0")]
1646#[cfg(not(feature = "ferrocene_certified"))]
1647impl<T: PointeeSized> PartialOrd for *const T {
1648    #[inline]
1649    #[allow(ambiguous_wide_pointer_comparisons)]
1650    fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
1651        Some(self.cmp(other))
1652    }
1653
1654    #[inline]
1655    #[allow(ambiguous_wide_pointer_comparisons)]
1656    fn lt(&self, other: &*const T) -> bool {
1657        *self < *other
1658    }
1659
1660    #[inline]
1661    #[allow(ambiguous_wide_pointer_comparisons)]
1662    fn le(&self, other: &*const T) -> bool {
1663        *self <= *other
1664    }
1665
1666    #[inline]
1667    #[allow(ambiguous_wide_pointer_comparisons)]
1668    fn gt(&self, other: &*const T) -> bool {
1669        *self > *other
1670    }
1671
1672    #[inline]
1673    #[allow(ambiguous_wide_pointer_comparisons)]
1674    fn ge(&self, other: &*const T) -> bool {
1675        *self >= *other
1676    }
1677}
1678
1679#[stable(feature = "raw_ptr_default", since = "1.88.0")]
1680#[cfg(not(feature = "ferrocene_certified"))]
1681impl<T: ?Sized + Thin> Default for *const T {
1682    /// Returns the default value of [`null()`][crate::ptr::null].
1683    fn default() -> Self {
1684        crate::ptr::null()
1685    }
1686}