core/ptr/
const_ptr.rs

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