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