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