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