Skip to main content

core/ptr/
const_ptr.rs

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