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