]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/mut_ptr.rs
Rollup merge of #97373 - dimpolo:cell_dispatch_from_dyn, r=dtolnay
[rust.git] / library / core / src / ptr / mut_ptr.rs
1 use super::*;
2 use crate::cmp::Ordering::{self, Equal, Greater, Less};
3 use crate::intrinsics::{self, const_eval_select};
4 use crate::slice::{self, SliceIndex};
5
6 impl<T: ?Sized> *mut T {
7     /// Returns `true` if the pointer is null.
8     ///
9     /// Note that unsized types have many possible null pointers, as only the
10     /// raw data pointer is considered, not their length, vtable, etc.
11     /// Therefore, two pointers that are null may still not compare equal to
12     /// each other.
13     ///
14     /// ## Behavior during const evaluation
15     ///
16     /// When this function is used during const evaluation, it may return `false` for pointers
17     /// that turn out to be null at runtime. Specifically, when a pointer to some memory
18     /// is offset beyond its bounds in such a way that the resulting pointer is null,
19     /// the function will still return `false`. There is no way for CTFE to know
20     /// the absolute position of that memory, so we cannot tell if the pointer is
21     /// null or not.
22     ///
23     /// # Examples
24     ///
25     /// Basic usage:
26     ///
27     /// ```
28     /// let mut s = [1, 2, 3];
29     /// let ptr: *mut u32 = s.as_mut_ptr();
30     /// assert!(!ptr.is_null());
31     /// ```
32     #[stable(feature = "rust1", since = "1.0.0")]
33     #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")]
34     #[inline]
35     pub const fn is_null(self) -> bool {
36         #[inline]
37         fn runtime_impl(ptr: *mut u8) -> bool {
38             ptr.addr() == 0
39         }
40
41         #[inline]
42         const fn const_impl(ptr: *mut u8) -> bool {
43             // Compare via a cast to a thin pointer, so fat pointers are only
44             // considering their "data" part for null-ness.
45             match (ptr).guaranteed_eq(null_mut()) {
46                 None => false,
47                 Some(res) => res,
48             }
49         }
50
51         // SAFETY: The two versions are equivalent at runtime.
52         unsafe { const_eval_select((self as *mut u8,), const_impl, runtime_impl) }
53     }
54
55     /// Casts to a pointer of another type.
56     #[stable(feature = "ptr_cast", since = "1.38.0")]
57     #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
58     #[inline(always)]
59     pub const fn cast<U>(self) -> *mut U {
60         self as _
61     }
62
63     /// Use the pointer value in a new pointer of another type.
64     ///
65     /// In case `val` is a (fat) pointer to an unsized type, this operation
66     /// will ignore the pointer part, whereas for (thin) pointers to sized
67     /// types, this has the same effect as a simple cast.
68     ///
69     /// The resulting pointer will have provenance of `self`, i.e., for a fat
70     /// pointer, this operation is semantically the same as creating a new
71     /// fat pointer with the data pointer value of `self` but the metadata of
72     /// `val`.
73     ///
74     /// # Examples
75     ///
76     /// This function is primarily useful for allowing byte-wise pointer
77     /// arithmetic on potentially fat pointers:
78     ///
79     /// ```
80     /// #![feature(set_ptr_value)]
81     /// # use core::fmt::Debug;
82     /// let mut arr: [i32; 3] = [1, 2, 3];
83     /// let mut ptr = arr.as_mut_ptr() as *mut dyn Debug;
84     /// let thin = ptr as *mut u8;
85     /// unsafe {
86     ///     ptr = thin.add(8).with_metadata_of(ptr);
87     ///     # assert_eq!(*(ptr as *mut i32), 3);
88     ///     println!("{:?}", &*ptr); // will print "3"
89     /// }
90     /// ```
91     #[unstable(feature = "set_ptr_value", issue = "75091")]
92     #[rustc_const_unstable(feature = "set_ptr_value", issue = "75091")]
93     #[must_use = "returns a new pointer rather than modifying its argument"]
94     #[inline]
95     pub const fn with_metadata_of<U>(self, meta: *const U) -> *mut U
96     where
97         U: ?Sized,
98     {
99         from_raw_parts_mut::<U>(self as *mut (), metadata(meta))
100     }
101
102     /// Changes constness without changing the type.
103     ///
104     /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
105     /// refactored.
106     ///
107     /// While not strictly required (`*mut T` coerces to `*const T`), this is provided for symmetry
108     /// with [`cast_mut`] on `*const T` and may have documentation value if used instead of implicit
109     /// coercion.
110     ///
111     /// [`cast_mut`]: #method.cast_mut
112     #[stable(feature = "ptr_const_cast", since = "1.65.0")]
113     #[rustc_const_stable(feature = "ptr_const_cast", since = "1.65.0")]
114     #[inline(always)]
115     pub const fn cast_const(self) -> *const T {
116         self as _
117     }
118
119     /// Casts a pointer to its raw bits.
120     ///
121     /// This is equivalent to `as usize`, but is more specific to enhance readability.
122     /// The inverse method is [`from_bits`](#method.from_bits-1).
123     ///
124     /// In particular, `*p as usize` and `p as usize` will both compile for
125     /// pointers to numeric types but do very different things, so using this
126     /// helps emphasize that reading the bits was intentional.
127     ///
128     /// # Examples
129     ///
130     /// ```
131     /// #![feature(ptr_to_from_bits)]
132     /// # #[cfg(not(miri))] { // doctest does not work with strict provenance
133     /// let mut array = [13, 42];
134     /// let mut it = array.iter_mut();
135     /// let p0: *mut i32 = it.next().unwrap();
136     /// assert_eq!(<*mut _>::from_bits(p0.to_bits()), p0);
137     /// let p1: *mut i32 = it.next().unwrap();
138     /// assert_eq!(p1.to_bits() - p0.to_bits(), 4);
139     /// }
140     /// ```
141     #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
142     #[deprecated(
143         since = "1.67",
144         note = "replaced by the `exposed_addr` method, or update your code \
145             to follow the strict provenance rules using its APIs"
146     )]
147     #[inline(always)]
148     pub fn to_bits(self) -> usize
149     where
150         T: Sized,
151     {
152         self as usize
153     }
154
155     /// Creates a pointer from its raw bits.
156     ///
157     /// This is equivalent to `as *mut T`, but is more specific to enhance readability.
158     /// The inverse method is [`to_bits`](#method.to_bits-1).
159     ///
160     /// # Examples
161     ///
162     /// ```
163     /// #![feature(ptr_to_from_bits)]
164     /// # #[cfg(not(miri))] { // doctest does not work with strict provenance
165     /// use std::ptr::NonNull;
166     /// let dangling: *mut u8 = NonNull::dangling().as_ptr();
167     /// assert_eq!(<*mut u8>::from_bits(1), dangling);
168     /// }
169     /// ```
170     #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
171     #[deprecated(
172         since = "1.67",
173         note = "replaced by the `ptr::from_exposed_addr_mut` function, or \
174             update your code to follow the strict provenance rules using its APIs"
175     )]
176     #[allow(fuzzy_provenance_casts)] // this is an unstable and semi-deprecated cast function
177     #[inline(always)]
178     pub fn from_bits(bits: usize) -> Self
179     where
180         T: Sized,
181     {
182         bits as Self
183     }
184
185     /// Gets the "address" portion of the pointer.
186     ///
187     /// This is similar to `self as usize`, which semantically discards *provenance* and
188     /// *address-space* information. However, unlike `self as usize`, casting the returned address
189     /// back to a pointer yields [`invalid`][], which is undefined behavior to dereference. To
190     /// properly restore the lost information and obtain a dereferenceable pointer, use
191     /// [`with_addr`][pointer::with_addr] or [`map_addr`][pointer::map_addr].
192     ///
193     /// If using those APIs is not possible because there is no way to preserve a pointer with the
194     /// required provenance, use [`expose_addr`][pointer::expose_addr] and
195     /// [`from_exposed_addr_mut`][from_exposed_addr_mut] instead. However, note that this makes
196     /// your code less portable and less amenable to tools that check for compliance with the Rust
197     /// memory model.
198     ///
199     /// On most platforms this will produce a value with the same bytes as the original
200     /// pointer, because all the bytes are dedicated to describing the address.
201     /// Platforms which need to store additional information in the pointer may
202     /// perform a change of representation to produce a value containing only the address
203     /// portion of the pointer. What that means is up to the platform to define.
204     ///
205     /// This API and its claimed semantics are part of the Strict Provenance experiment, and as such
206     /// might change in the future (including possibly weakening this so it becomes wholly
207     /// equivalent to `self as usize`). See the [module documentation][crate::ptr] for details.
208     #[must_use]
209     #[inline(always)]
210     #[unstable(feature = "strict_provenance", issue = "95228")]
211     pub fn addr(self) -> usize {
212         // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
213         // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
214         // provenance).
215         unsafe { mem::transmute(self.cast::<()>()) }
216     }
217
218     /// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future
219     /// use in [`from_exposed_addr`][].
220     ///
221     /// This is equivalent to `self as usize`, which semantically discards *provenance* and
222     /// *address-space* information. Furthermore, this (like the `as` cast) has the implicit
223     /// side-effect of marking the provenance as 'exposed', so on platforms that support it you can
224     /// later call [`from_exposed_addr_mut`][] to reconstitute the original pointer including its
225     /// provenance. (Reconstructing address space information, if required, is your responsibility.)
226     ///
227     /// Using this method means that code is *not* following Strict Provenance rules. Supporting
228     /// [`from_exposed_addr_mut`][] complicates specification and reasoning and may not be supported
229     /// by tools that help you to stay conformant with the Rust memory model, so it is recommended
230     /// to use [`addr`][pointer::addr] wherever possible.
231     ///
232     /// On most platforms this will produce a value with the same bytes as the original pointer,
233     /// because all the bytes are dedicated to describing the address. Platforms which need to store
234     /// additional information in the pointer may not support this operation, since the 'expose'
235     /// side-effect which is required for [`from_exposed_addr_mut`][] to work is typically not
236     /// available.
237     ///
238     /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
239     /// [module documentation][crate::ptr] for details.
240     ///
241     /// [`from_exposed_addr_mut`]: from_exposed_addr_mut
242     #[must_use]
243     #[inline(always)]
244     #[unstable(feature = "strict_provenance", issue = "95228")]
245     pub fn expose_addr(self) -> usize {
246         // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
247         self.cast::<()>() as usize
248     }
249
250     /// Creates a new pointer with the given address.
251     ///
252     /// This performs the same operation as an `addr as ptr` cast, but copies
253     /// the *address-space* and *provenance* of `self` to the new pointer.
254     /// This allows us to dynamically preserve and propagate this important
255     /// information in a way that is otherwise impossible with a unary cast.
256     ///
257     /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
258     /// `self` to the given address, and therefore has all the same capabilities and restrictions.
259     ///
260     /// This API and its claimed semantics are part of the Strict Provenance experiment,
261     /// see the [module documentation][crate::ptr] for details.
262     #[must_use]
263     #[inline]
264     #[unstable(feature = "strict_provenance", issue = "95228")]
265     pub fn with_addr(self, addr: usize) -> Self {
266         // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
267         //
268         // In the mean-time, this operation is defined to be "as if" it was
269         // a wrapping_offset, so we can emulate it as such. This should properly
270         // restore pointer provenance even under today's compiler.
271         let self_addr = self.addr() as isize;
272         let dest_addr = addr as isize;
273         let offset = dest_addr.wrapping_sub(self_addr);
274
275         // This is the canonical desugarring of this operation
276         self.wrapping_byte_offset(offset)
277     }
278
279     /// Creates a new pointer by mapping `self`'s address to a new one.
280     ///
281     /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
282     ///
283     /// This API and its claimed semantics are part of the Strict Provenance experiment,
284     /// see the [module documentation][crate::ptr] for details.
285     #[must_use]
286     #[inline]
287     #[unstable(feature = "strict_provenance", issue = "95228")]
288     pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self {
289         self.with_addr(f(self.addr()))
290     }
291
292     /// Decompose a (possibly wide) pointer into its address and metadata components.
293     ///
294     /// The pointer can be later reconstructed with [`from_raw_parts_mut`].
295     #[unstable(feature = "ptr_metadata", issue = "81513")]
296     #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
297     #[inline]
298     pub const fn to_raw_parts(self) -> (*mut (), <T as super::Pointee>::Metadata) {
299         (self.cast(), super::metadata(self))
300     }
301
302     /// Returns `None` if the pointer is null, or else returns a shared reference to
303     /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
304     /// must be used instead.
305     ///
306     /// For the mutable counterpart see [`as_mut`].
307     ///
308     /// [`as_uninit_ref`]: #method.as_uninit_ref-1
309     /// [`as_mut`]: #method.as_mut
310     ///
311     /// # Safety
312     ///
313     /// When calling this method, you have to ensure that *either* the pointer is null *or*
314     /// all of the following is true:
315     ///
316     /// * The pointer must be properly aligned.
317     ///
318     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
319     ///
320     /// * The pointer must point to an initialized instance of `T`.
321     ///
322     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
323     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
324     ///   In particular, while this reference exists, the memory the pointer points to must
325     ///   not get mutated (except inside `UnsafeCell`).
326     ///
327     /// This applies even if the result of this method is unused!
328     /// (The part about being initialized is not yet fully decided, but until
329     /// it is, the only safe approach is to ensure that they are indeed initialized.)
330     ///
331     /// [the module documentation]: crate::ptr#safety
332     ///
333     /// # Examples
334     ///
335     /// Basic usage:
336     ///
337     /// ```
338     /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
339     ///
340     /// unsafe {
341     ///     if let Some(val_back) = ptr.as_ref() {
342     ///         println!("We got back the value: {val_back}!");
343     ///     }
344     /// }
345     /// ```
346     ///
347     /// # Null-unchecked version
348     ///
349     /// If you are sure the pointer can never be null and are looking for some kind of
350     /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
351     /// dereference the pointer directly.
352     ///
353     /// ```
354     /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
355     ///
356     /// unsafe {
357     ///     let val_back = &*ptr;
358     ///     println!("We got back the value: {val_back}!");
359     /// }
360     /// ```
361     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
362     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
363     #[inline]
364     pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
365         // SAFETY: the caller must guarantee that `self` is valid for a
366         // reference if it isn't null.
367         if self.is_null() { None } else { unsafe { Some(&*self) } }
368     }
369
370     /// Returns `None` if the pointer is null, or else returns a shared reference to
371     /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
372     /// that the value has to be initialized.
373     ///
374     /// For the mutable counterpart see [`as_uninit_mut`].
375     ///
376     /// [`as_ref`]: #method.as_ref-1
377     /// [`as_uninit_mut`]: #method.as_uninit_mut
378     ///
379     /// # Safety
380     ///
381     /// When calling this method, you have to ensure that *either* the pointer is null *or*
382     /// all of the following is true:
383     ///
384     /// * The pointer must be properly aligned.
385     ///
386     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
387     ///
388     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
389     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
390     ///   In particular, while this reference exists, the memory the pointer points to must
391     ///   not get mutated (except inside `UnsafeCell`).
392     ///
393     /// This applies even if the result of this method is unused!
394     ///
395     /// [the module documentation]: crate::ptr#safety
396     ///
397     /// # Examples
398     ///
399     /// Basic usage:
400     ///
401     /// ```
402     /// #![feature(ptr_as_uninit)]
403     ///
404     /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
405     ///
406     /// unsafe {
407     ///     if let Some(val_back) = ptr.as_uninit_ref() {
408     ///         println!("We got back the value: {}!", val_back.assume_init());
409     ///     }
410     /// }
411     /// ```
412     #[inline]
413     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
414     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
415     pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
416     where
417         T: Sized,
418     {
419         // SAFETY: the caller must guarantee that `self` meets all the
420         // requirements for a reference.
421         if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
422     }
423
424     /// Calculates the offset from a pointer.
425     ///
426     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
427     /// offset of `3 * size_of::<T>()` bytes.
428     ///
429     /// # Safety
430     ///
431     /// If any of the following conditions are violated, the result is Undefined
432     /// Behavior:
433     ///
434     /// * Both the starting and resulting pointer must be either in bounds or one
435     ///   byte past the end of the same [allocated object].
436     ///
437     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
438     ///
439     /// * The offset being in bounds cannot rely on "wrapping around" the address
440     ///   space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
441     ///
442     /// The compiler and standard library generally tries to ensure allocations
443     /// never reach a size where an offset is a concern. For instance, `Vec`
444     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
445     /// `vec.as_ptr().add(vec.len())` is always safe.
446     ///
447     /// Most platforms fundamentally can't even construct such an allocation.
448     /// For instance, no known 64-bit platform can ever serve a request
449     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
450     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
451     /// more than `isize::MAX` bytes with things like Physical Address
452     /// Extension. As such, memory acquired directly from allocators or memory
453     /// mapped files *may* be too large to handle with this function.
454     ///
455     /// Consider using [`wrapping_offset`] instead if these constraints are
456     /// difficult to satisfy. The only advantage of this method is that it
457     /// enables more aggressive compiler optimizations.
458     ///
459     /// [`wrapping_offset`]: #method.wrapping_offset
460     /// [allocated object]: crate::ptr#allocated-object
461     ///
462     /// # Examples
463     ///
464     /// Basic usage:
465     ///
466     /// ```
467     /// let mut s = [1, 2, 3];
468     /// let ptr: *mut u32 = s.as_mut_ptr();
469     ///
470     /// unsafe {
471     ///     println!("{}", *ptr.offset(1));
472     ///     println!("{}", *ptr.offset(2));
473     /// }
474     /// ```
475     #[stable(feature = "rust1", since = "1.0.0")]
476     #[must_use = "returns a new pointer rather than modifying its argument"]
477     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
478     #[inline(always)]
479     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
480     pub const unsafe fn offset(self, count: isize) -> *mut T
481     where
482         T: Sized,
483     {
484         // SAFETY: the caller must uphold the safety contract for `offset`.
485         // The obtained pointer is valid for writes since the caller must
486         // guarantee that it points to the same allocated object as `self`.
487         unsafe { intrinsics::offset(self, count) as *mut T }
488     }
489
490     /// Calculates the offset from a pointer in bytes.
491     ///
492     /// `count` is in units of **bytes**.
493     ///
494     /// This is purely a convenience for casting to a `u8` pointer and
495     /// using [offset][pointer::offset] on it. See that method for documentation
496     /// and safety requirements.
497     ///
498     /// For non-`Sized` pointees this operation changes only the data pointer,
499     /// leaving the metadata untouched.
500     #[must_use]
501     #[inline(always)]
502     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
503     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
504     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
505     pub const unsafe fn byte_offset(self, count: isize) -> Self {
506         // SAFETY: the caller must uphold the safety contract for `offset`.
507         unsafe { self.cast::<u8>().offset(count).with_metadata_of(self) }
508     }
509
510     /// Calculates the offset from a pointer using wrapping arithmetic.
511     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
512     /// offset of `3 * size_of::<T>()` bytes.
513     ///
514     /// # Safety
515     ///
516     /// This operation itself is always safe, but using the resulting pointer is not.
517     ///
518     /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
519     /// be used to read or write other allocated objects.
520     ///
521     /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
522     /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
523     /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
524     /// `x` and `y` point into the same allocated object.
525     ///
526     /// Compared to [`offset`], this method basically delays the requirement of staying within the
527     /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
528     /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
529     /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
530     /// can be optimized better and is thus preferable in performance-sensitive code.
531     ///
532     /// The delayed check only considers the value of the pointer that was dereferenced, not the
533     /// intermediate values used during the computation of the final result. For example,
534     /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
535     /// words, leaving the allocated object and then re-entering it later is permitted.
536     ///
537     /// [`offset`]: #method.offset
538     /// [allocated object]: crate::ptr#allocated-object
539     ///
540     /// # Examples
541     ///
542     /// Basic usage:
543     ///
544     /// ```
545     /// // Iterate using a raw pointer in increments of two elements
546     /// let mut data = [1u8, 2, 3, 4, 5];
547     /// let mut ptr: *mut u8 = data.as_mut_ptr();
548     /// let step = 2;
549     /// let end_rounded_up = ptr.wrapping_offset(6);
550     ///
551     /// while ptr != end_rounded_up {
552     ///     unsafe {
553     ///         *ptr = 0;
554     ///     }
555     ///     ptr = ptr.wrapping_offset(step);
556     /// }
557     /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
558     /// ```
559     #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
560     #[must_use = "returns a new pointer rather than modifying its argument"]
561     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
562     #[inline(always)]
563     pub const fn wrapping_offset(self, count: isize) -> *mut T
564     where
565         T: Sized,
566     {
567         // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
568         unsafe { intrinsics::arith_offset(self, count) as *mut T }
569     }
570
571     /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
572     ///
573     /// `count` is in units of **bytes**.
574     ///
575     /// This is purely a convenience for casting to a `u8` pointer and
576     /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
577     /// for documentation.
578     ///
579     /// For non-`Sized` pointees this operation changes only the data pointer,
580     /// leaving the metadata untouched.
581     #[must_use]
582     #[inline(always)]
583     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
584     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
585     pub const fn wrapping_byte_offset(self, count: isize) -> Self {
586         self.cast::<u8>().wrapping_offset(count).with_metadata_of(self)
587     }
588
589     /// Masks out bits of the pointer according to a mask.
590     ///
591     /// This is convenience for `ptr.map_addr(|a| a & mask)`.
592     ///
593     /// For non-`Sized` pointees this operation changes only the data pointer,
594     /// leaving the metadata untouched.
595     ///
596     /// ## Examples
597     ///
598     /// ```
599     /// #![feature(ptr_mask, strict_provenance)]
600     /// let mut v = 17_u32;
601     /// let ptr: *mut u32 = &mut v;
602     ///
603     /// // `u32` is 4 bytes aligned,
604     /// // which means that lower 2 bits are always 0.
605     /// let tag_mask = 0b11;
606     /// let ptr_mask = !tag_mask;
607     ///
608     /// // We can store something in these lower bits
609     /// let tagged_ptr = ptr.map_addr(|a| a | 0b10);
610     ///
611     /// // Get the "tag" back
612     /// let tag = tagged_ptr.addr() & tag_mask;
613     /// assert_eq!(tag, 0b10);
614     ///
615     /// // Note that `tagged_ptr` is unaligned, it's UB to read from/write to it.
616     /// // To get original pointer `mask` can be used:
617     /// let masked_ptr = tagged_ptr.mask(ptr_mask);
618     /// assert_eq!(unsafe { *masked_ptr }, 17);
619     ///
620     /// unsafe { *masked_ptr = 0 };
621     /// assert_eq!(v, 0);
622     /// ```
623     #[unstable(feature = "ptr_mask", issue = "98290")]
624     #[must_use = "returns a new pointer rather than modifying its argument"]
625     #[inline(always)]
626     pub fn mask(self, mask: usize) -> *mut T {
627         intrinsics::ptr_mask(self.cast::<()>(), mask).cast_mut().with_metadata_of(self)
628     }
629
630     /// Returns `None` if the pointer is null, or else returns a unique reference to
631     /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
632     /// must be used instead.
633     ///
634     /// For the shared counterpart see [`as_ref`].
635     ///
636     /// [`as_uninit_mut`]: #method.as_uninit_mut
637     /// [`as_ref`]: #method.as_ref-1
638     ///
639     /// # Safety
640     ///
641     /// When calling this method, you have to ensure that *either* the pointer is null *or*
642     /// all of the following is true:
643     ///
644     /// * The pointer must be properly aligned.
645     ///
646     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
647     ///
648     /// * The pointer must point to an initialized instance of `T`.
649     ///
650     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
651     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
652     ///   In particular, while this reference exists, the memory the pointer points to must
653     ///   not get accessed (read or written) through any other pointer.
654     ///
655     /// This applies even if the result of this method is unused!
656     /// (The part about being initialized is not yet fully decided, but until
657     /// it is, the only safe approach is to ensure that they are indeed initialized.)
658     ///
659     /// [the module documentation]: crate::ptr#safety
660     ///
661     /// # Examples
662     ///
663     /// Basic usage:
664     ///
665     /// ```
666     /// let mut s = [1, 2, 3];
667     /// let ptr: *mut u32 = s.as_mut_ptr();
668     /// let first_value = unsafe { ptr.as_mut().unwrap() };
669     /// *first_value = 4;
670     /// # assert_eq!(s, [4, 2, 3]);
671     /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
672     /// ```
673     ///
674     /// # Null-unchecked version
675     ///
676     /// If you are sure the pointer can never be null and are looking for some kind of
677     /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
678     /// you can dereference the pointer directly.
679     ///
680     /// ```
681     /// let mut s = [1, 2, 3];
682     /// let ptr: *mut u32 = s.as_mut_ptr();
683     /// let first_value = unsafe { &mut *ptr };
684     /// *first_value = 4;
685     /// # assert_eq!(s, [4, 2, 3]);
686     /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
687     /// ```
688     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
689     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
690     #[inline]
691     pub const unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
692         // SAFETY: the caller must guarantee that `self` is be valid for
693         // a mutable reference if it isn't null.
694         if self.is_null() { None } else { unsafe { Some(&mut *self) } }
695     }
696
697     /// Returns `None` if the pointer is null, or else returns a unique reference to
698     /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
699     /// that the value has to be initialized.
700     ///
701     /// For the shared counterpart see [`as_uninit_ref`].
702     ///
703     /// [`as_mut`]: #method.as_mut
704     /// [`as_uninit_ref`]: #method.as_uninit_ref-1
705     ///
706     /// # Safety
707     ///
708     /// When calling this method, you have to ensure that *either* the pointer is null *or*
709     /// all of the following is true:
710     ///
711     /// * The pointer must be properly aligned.
712     ///
713     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
714     ///
715     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
716     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
717     ///   In particular, while this reference exists, the memory the pointer points to must
718     ///   not get accessed (read or written) through any other pointer.
719     ///
720     /// This applies even if the result of this method is unused!
721     ///
722     /// [the module documentation]: crate::ptr#safety
723     #[inline]
724     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
725     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
726     pub const unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
727     where
728         T: Sized,
729     {
730         // SAFETY: the caller must guarantee that `self` meets all the
731         // requirements for a reference.
732         if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
733     }
734
735     /// Returns whether two pointers are guaranteed to be equal.
736     ///
737     /// At runtime this function behaves like `Some(self == other)`.
738     /// However, in some contexts (e.g., compile-time evaluation),
739     /// it is not always possible to determine equality of two pointers, so this function may
740     /// spuriously return `None` for pointers that later actually turn out to have its equality known.
741     /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
742     ///
743     /// The return value may change from `Some` to `None` and vice versa depending on the compiler
744     /// version and unsafe code must not
745     /// rely on the result of this function for soundness. It is suggested to only use this function
746     /// for performance optimizations where spurious `None` return values by this function do not
747     /// affect the outcome, but just the performance.
748     /// The consequences of using this method to make runtime and compile-time code behave
749     /// differently have not been explored. This method should not be used to introduce such
750     /// differences, and it should also not be stabilized before we have a better understanding
751     /// of this issue.
752     #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
753     #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
754     #[inline]
755     pub const fn guaranteed_eq(self, other: *mut T) -> Option<bool>
756     where
757         T: Sized,
758     {
759         (self as *const T).guaranteed_eq(other as _)
760     }
761
762     /// Returns whether two pointers are guaranteed to be inequal.
763     ///
764     /// At runtime this function behaves like `Some(self != other)`.
765     /// However, in some contexts (e.g., compile-time evaluation),
766     /// it is not always possible to determine inequality of two pointers, so this function may
767     /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
768     /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
769     ///
770     /// The return value may change from `Some` to `None` and vice versa depending on the compiler
771     /// version and unsafe code must not
772     /// rely on the result of this function for soundness. It is suggested to only use this function
773     /// for performance optimizations where spurious `None` return values by this function do not
774     /// affect the outcome, but just the performance.
775     /// The consequences of using this method to make runtime and compile-time code behave
776     /// differently have not been explored. This method should not be used to introduce such
777     /// differences, and it should also not be stabilized before we have a better understanding
778     /// of this issue.
779     #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
780     #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
781     #[inline]
782     pub const fn guaranteed_ne(self, other: *mut T) -> Option<bool>
783     where
784         T: Sized,
785     {
786         (self as *const T).guaranteed_ne(other as _)
787     }
788
789     /// Calculates the distance between two pointers. The returned value is in
790     /// units of T: the distance in bytes divided by `mem::size_of::<T>()`.
791     ///
792     /// This function is the inverse of [`offset`].
793     ///
794     /// [`offset`]: #method.offset-1
795     ///
796     /// # Safety
797     ///
798     /// If any of the following conditions are violated, the result is Undefined
799     /// Behavior:
800     ///
801     /// * Both the starting and other pointer must be either in bounds or one
802     ///   byte past the end of the same [allocated object].
803     ///
804     /// * Both pointers must be *derived from* a pointer to the same object.
805     ///   (See below for an example.)
806     ///
807     /// * The distance between the pointers, in bytes, must be an exact multiple
808     ///   of the size of `T`.
809     ///
810     /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
811     ///
812     /// * The distance being in bounds cannot rely on "wrapping around" the address space.
813     ///
814     /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
815     /// address space, so two pointers within some value of any Rust type `T` will always satisfy
816     /// the last two conditions. The standard library also generally ensures that allocations
817     /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
818     /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
819     /// always satisfies the last two conditions.
820     ///
821     /// Most platforms fundamentally can't even construct such a large allocation.
822     /// For instance, no known 64-bit platform can ever serve a request
823     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
824     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
825     /// more than `isize::MAX` bytes with things like Physical Address
826     /// Extension. As such, memory acquired directly from allocators or memory
827     /// mapped files *may* be too large to handle with this function.
828     /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
829     /// such large allocations either.)
830     ///
831     /// [`add`]: #method.add
832     /// [allocated object]: crate::ptr#allocated-object
833     ///
834     /// # Panics
835     ///
836     /// This function panics if `T` is a Zero-Sized Type ("ZST").
837     ///
838     /// # Examples
839     ///
840     /// Basic usage:
841     ///
842     /// ```
843     /// let mut a = [0; 5];
844     /// let ptr1: *mut i32 = &mut a[1];
845     /// let ptr2: *mut i32 = &mut a[3];
846     /// unsafe {
847     ///     assert_eq!(ptr2.offset_from(ptr1), 2);
848     ///     assert_eq!(ptr1.offset_from(ptr2), -2);
849     ///     assert_eq!(ptr1.offset(2), ptr2);
850     ///     assert_eq!(ptr2.offset(-2), ptr1);
851     /// }
852     /// ```
853     ///
854     /// *Incorrect* usage:
855     ///
856     /// ```rust,no_run
857     /// let ptr1 = Box::into_raw(Box::new(0u8));
858     /// let ptr2 = Box::into_raw(Box::new(1u8));
859     /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
860     /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
861     /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff);
862     /// assert_eq!(ptr2 as usize, ptr2_other as usize);
863     /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
864     /// // computing their offset is undefined behavior, even though
865     /// // they point to the same address!
866     /// unsafe {
867     ///     let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
868     /// }
869     /// ```
870     #[stable(feature = "ptr_offset_from", since = "1.47.0")]
871     #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
872     #[inline(always)]
873     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
874     pub const unsafe fn offset_from(self, origin: *const T) -> isize
875     where
876         T: Sized,
877     {
878         // SAFETY: the caller must uphold the safety contract for `offset_from`.
879         unsafe { (self as *const T).offset_from(origin) }
880     }
881
882     /// Calculates the distance between two pointers. The returned value is in
883     /// units of **bytes**.
884     ///
885     /// This is purely a convenience for casting to a `u8` pointer and
886     /// using [offset_from][pointer::offset_from] on it. See that method for
887     /// documentation and safety requirements.
888     ///
889     /// For non-`Sized` pointees this operation considers only the data pointers,
890     /// ignoring the metadata.
891     #[inline(always)]
892     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
893     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
894     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
895     pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: *const U) -> isize {
896         // SAFETY: the caller must uphold the safety contract for `offset_from`.
897         unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
898     }
899
900     /// Calculates the distance between two pointers, *where it's known that
901     /// `self` is equal to or greater than `origin`*. The returned value is in
902     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
903     ///
904     /// This computes the same value that [`offset_from`](#method.offset_from)
905     /// would compute, but with the added precondition that the offset is
906     /// guaranteed to be non-negative.  This method is equivalent to
907     /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`,
908     /// but it provides slightly more information to the optimizer, which can
909     /// sometimes allow it to optimize slightly better with some backends.
910     ///
911     /// This method can be though of as recovering the `count` that was passed
912     /// to [`add`](#method.add) (or, with the parameters in the other order,
913     /// to [`sub`](#method.sub)).  The following are all equivalent, assuming
914     /// that their safety preconditions are met:
915     /// ```rust
916     /// # #![feature(ptr_sub_ptr)]
917     /// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool {
918     /// ptr.sub_ptr(origin) == count
919     /// # &&
920     /// origin.add(count) == ptr
921     /// # &&
922     /// ptr.sub(count) == origin
923     /// # }
924     /// ```
925     ///
926     /// # Safety
927     ///
928     /// - The distance between the pointers must be non-negative (`self >= origin`)
929     ///
930     /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
931     ///   apply to this method as well; see it for the full details.
932     ///
933     /// Importantly, despite the return type of this method being able to represent
934     /// a larger offset, it's still *not permitted* to pass pointers which differ
935     /// by more than `isize::MAX` *bytes*.  As such, the result of this method will
936     /// always be less than or equal to `isize::MAX as usize`.
937     ///
938     /// # Panics
939     ///
940     /// This function panics if `T` is a Zero-Sized Type ("ZST").
941     ///
942     /// # Examples
943     ///
944     /// ```
945     /// #![feature(ptr_sub_ptr)]
946     ///
947     /// let mut a = [0; 5];
948     /// let p: *mut i32 = a.as_mut_ptr();
949     /// unsafe {
950     ///     let ptr1: *mut i32 = p.add(1);
951     ///     let ptr2: *mut i32 = p.add(3);
952     ///
953     ///     assert_eq!(ptr2.sub_ptr(ptr1), 2);
954     ///     assert_eq!(ptr1.add(2), ptr2);
955     ///     assert_eq!(ptr2.sub(2), ptr1);
956     ///     assert_eq!(ptr2.sub_ptr(ptr2), 0);
957     /// }
958     ///
959     /// // This would be incorrect, as the pointers are not correctly ordered:
960     /// // ptr1.offset_from(ptr2)
961     #[unstable(feature = "ptr_sub_ptr", issue = "95892")]
962     #[rustc_const_unstable(feature = "const_ptr_sub_ptr", issue = "95892")]
963     #[inline]
964     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
965     pub const unsafe fn sub_ptr(self, origin: *const T) -> usize
966     where
967         T: Sized,
968     {
969         // SAFETY: the caller must uphold the safety contract for `sub_ptr`.
970         unsafe { (self as *const T).sub_ptr(origin) }
971     }
972
973     /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
974     ///
975     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
976     /// offset of `3 * size_of::<T>()` bytes.
977     ///
978     /// # Safety
979     ///
980     /// If any of the following conditions are violated, the result is Undefined
981     /// Behavior:
982     ///
983     /// * Both the starting and resulting pointer must be either in bounds or one
984     ///   byte past the end of the same [allocated object].
985     ///
986     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
987     ///
988     /// * The offset being in bounds cannot rely on "wrapping around" the address
989     ///   space. That is, the infinite-precision sum must fit in a `usize`.
990     ///
991     /// The compiler and standard library generally tries to ensure allocations
992     /// never reach a size where an offset is a concern. For instance, `Vec`
993     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
994     /// `vec.as_ptr().add(vec.len())` is always safe.
995     ///
996     /// Most platforms fundamentally can't even construct such an allocation.
997     /// For instance, no known 64-bit platform can ever serve a request
998     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
999     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1000     /// more than `isize::MAX` bytes with things like Physical Address
1001     /// Extension. As such, memory acquired directly from allocators or memory
1002     /// mapped files *may* be too large to handle with this function.
1003     ///
1004     /// Consider using [`wrapping_add`] instead if these constraints are
1005     /// difficult to satisfy. The only advantage of this method is that it
1006     /// enables more aggressive compiler optimizations.
1007     ///
1008     /// [`wrapping_add`]: #method.wrapping_add
1009     /// [allocated object]: crate::ptr#allocated-object
1010     ///
1011     /// # Examples
1012     ///
1013     /// Basic usage:
1014     ///
1015     /// ```
1016     /// let s: &str = "123";
1017     /// let ptr: *const u8 = s.as_ptr();
1018     ///
1019     /// unsafe {
1020     ///     println!("{}", *ptr.add(1) as char);
1021     ///     println!("{}", *ptr.add(2) as char);
1022     /// }
1023     /// ```
1024     #[stable(feature = "pointer_methods", since = "1.26.0")]
1025     #[must_use = "returns a new pointer rather than modifying its argument"]
1026     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1027     #[inline(always)]
1028     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1029     pub const unsafe fn add(self, count: usize) -> Self
1030     where
1031         T: Sized,
1032     {
1033         // SAFETY: the caller must uphold the safety contract for `offset`.
1034         unsafe { self.offset(count as isize) }
1035     }
1036
1037     /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
1038     ///
1039     /// `count` is in units of bytes.
1040     ///
1041     /// This is purely a convenience for casting to a `u8` pointer and
1042     /// using [add][pointer::add] on it. See that method for documentation
1043     /// and safety requirements.
1044     ///
1045     /// For non-`Sized` pointees this operation changes only the data pointer,
1046     /// leaving the metadata untouched.
1047     #[must_use]
1048     #[inline(always)]
1049     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1050     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1051     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1052     pub const unsafe fn byte_add(self, count: usize) -> Self {
1053         // SAFETY: the caller must uphold the safety contract for `add`.
1054         unsafe { self.cast::<u8>().add(count).with_metadata_of(self) }
1055     }
1056
1057     /// Calculates the offset from a pointer (convenience for
1058     /// `.offset((count as isize).wrapping_neg())`).
1059     ///
1060     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1061     /// offset of `3 * size_of::<T>()` bytes.
1062     ///
1063     /// # Safety
1064     ///
1065     /// If any of the following conditions are violated, the result is Undefined
1066     /// Behavior:
1067     ///
1068     /// * Both the starting and resulting pointer must be either in bounds or one
1069     ///   byte past the end of the same [allocated object].
1070     ///
1071     /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1072     ///
1073     /// * The offset being in bounds cannot rely on "wrapping around" the address
1074     ///   space. That is, the infinite-precision sum must fit in a usize.
1075     ///
1076     /// The compiler and standard library generally tries to ensure allocations
1077     /// never reach a size where an offset is a concern. For instance, `Vec`
1078     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1079     /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1080     ///
1081     /// Most platforms fundamentally can't even construct such an allocation.
1082     /// For instance, no known 64-bit platform can ever serve a request
1083     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1084     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1085     /// more than `isize::MAX` bytes with things like Physical Address
1086     /// Extension. As such, memory acquired directly from allocators or memory
1087     /// mapped files *may* be too large to handle with this function.
1088     ///
1089     /// Consider using [`wrapping_sub`] instead if these constraints are
1090     /// difficult to satisfy. The only advantage of this method is that it
1091     /// enables more aggressive compiler optimizations.
1092     ///
1093     /// [`wrapping_sub`]: #method.wrapping_sub
1094     /// [allocated object]: crate::ptr#allocated-object
1095     ///
1096     /// # Examples
1097     ///
1098     /// Basic usage:
1099     ///
1100     /// ```
1101     /// let s: &str = "123";
1102     ///
1103     /// unsafe {
1104     ///     let end: *const u8 = s.as_ptr().add(3);
1105     ///     println!("{}", *end.sub(1) as char);
1106     ///     println!("{}", *end.sub(2) as char);
1107     /// }
1108     /// ```
1109     #[stable(feature = "pointer_methods", since = "1.26.0")]
1110     #[must_use = "returns a new pointer rather than modifying its argument"]
1111     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1112     #[inline(always)]
1113     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1114     pub const unsafe fn sub(self, count: usize) -> Self
1115     where
1116         T: Sized,
1117     {
1118         // SAFETY: the caller must uphold the safety contract for `offset`.
1119         unsafe { self.offset((count as isize).wrapping_neg()) }
1120     }
1121
1122     /// Calculates the offset from a pointer in bytes (convenience for
1123     /// `.byte_offset((count as isize).wrapping_neg())`).
1124     ///
1125     /// `count` is in units of bytes.
1126     ///
1127     /// This is purely a convenience for casting to a `u8` pointer and
1128     /// using [sub][pointer::sub] on it. See that method for documentation
1129     /// and safety requirements.
1130     ///
1131     /// For non-`Sized` pointees this operation changes only the data pointer,
1132     /// leaving the metadata untouched.
1133     #[must_use]
1134     #[inline(always)]
1135     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1136     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1137     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1138     pub const unsafe fn byte_sub(self, count: usize) -> Self {
1139         // SAFETY: the caller must uphold the safety contract for `sub`.
1140         unsafe { self.cast::<u8>().sub(count).with_metadata_of(self) }
1141     }
1142
1143     /// Calculates the offset from a pointer using wrapping arithmetic.
1144     /// (convenience for `.wrapping_offset(count as isize)`)
1145     ///
1146     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1147     /// offset of `3 * size_of::<T>()` bytes.
1148     ///
1149     /// # Safety
1150     ///
1151     /// This operation itself is always safe, but using the resulting pointer is not.
1152     ///
1153     /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1154     /// be used to read or write other allocated objects.
1155     ///
1156     /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1157     /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1158     /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1159     /// `x` and `y` point into the same allocated object.
1160     ///
1161     /// Compared to [`add`], this method basically delays the requirement of staying within the
1162     /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
1163     /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1164     /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1165     /// can be optimized better and is thus preferable in performance-sensitive code.
1166     ///
1167     /// The delayed check only considers the value of the pointer that was dereferenced, not the
1168     /// intermediate values used during the computation of the final result. For example,
1169     /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1170     /// allocated object and then re-entering it later is permitted.
1171     ///
1172     /// [`add`]: #method.add
1173     /// [allocated object]: crate::ptr#allocated-object
1174     ///
1175     /// # Examples
1176     ///
1177     /// Basic usage:
1178     ///
1179     /// ```
1180     /// // Iterate using a raw pointer in increments of two elements
1181     /// let data = [1u8, 2, 3, 4, 5];
1182     /// let mut ptr: *const u8 = data.as_ptr();
1183     /// let step = 2;
1184     /// let end_rounded_up = ptr.wrapping_add(6);
1185     ///
1186     /// // This loop prints "1, 3, 5, "
1187     /// while ptr != end_rounded_up {
1188     ///     unsafe {
1189     ///         print!("{}, ", *ptr);
1190     ///     }
1191     ///     ptr = ptr.wrapping_add(step);
1192     /// }
1193     /// ```
1194     #[stable(feature = "pointer_methods", since = "1.26.0")]
1195     #[must_use = "returns a new pointer rather than modifying its argument"]
1196     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1197     #[inline(always)]
1198     pub const fn wrapping_add(self, count: usize) -> Self
1199     where
1200         T: Sized,
1201     {
1202         self.wrapping_offset(count as isize)
1203     }
1204
1205     /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1206     /// (convenience for `.wrapping_byte_offset(count as isize)`)
1207     ///
1208     /// `count` is in units of bytes.
1209     ///
1210     /// This is purely a convenience for casting to a `u8` pointer and
1211     /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1212     ///
1213     /// For non-`Sized` pointees this operation changes only the data pointer,
1214     /// leaving the metadata untouched.
1215     #[must_use]
1216     #[inline(always)]
1217     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1218     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1219     pub const fn wrapping_byte_add(self, count: usize) -> Self {
1220         self.cast::<u8>().wrapping_add(count).with_metadata_of(self)
1221     }
1222
1223     /// Calculates the offset from a pointer using wrapping arithmetic.
1224     /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1225     ///
1226     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1227     /// offset of `3 * size_of::<T>()` bytes.
1228     ///
1229     /// # Safety
1230     ///
1231     /// This operation itself is always safe, but using the resulting pointer is not.
1232     ///
1233     /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1234     /// be used to read or write other allocated objects.
1235     ///
1236     /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1237     /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1238     /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1239     /// `x` and `y` point into the same allocated object.
1240     ///
1241     /// Compared to [`sub`], this method basically delays the requirement of staying within the
1242     /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
1243     /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1244     /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1245     /// can be optimized better and is thus preferable in performance-sensitive code.
1246     ///
1247     /// The delayed check only considers the value of the pointer that was dereferenced, not the
1248     /// intermediate values used during the computation of the final result. For example,
1249     /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1250     /// allocated object and then re-entering it later is permitted.
1251     ///
1252     /// [`sub`]: #method.sub
1253     /// [allocated object]: crate::ptr#allocated-object
1254     ///
1255     /// # Examples
1256     ///
1257     /// Basic usage:
1258     ///
1259     /// ```
1260     /// // Iterate using a raw pointer in increments of two elements (backwards)
1261     /// let data = [1u8, 2, 3, 4, 5];
1262     /// let mut ptr: *const u8 = data.as_ptr();
1263     /// let start_rounded_down = ptr.wrapping_sub(2);
1264     /// ptr = ptr.wrapping_add(4);
1265     /// let step = 2;
1266     /// // This loop prints "5, 3, 1, "
1267     /// while ptr != start_rounded_down {
1268     ///     unsafe {
1269     ///         print!("{}, ", *ptr);
1270     ///     }
1271     ///     ptr = ptr.wrapping_sub(step);
1272     /// }
1273     /// ```
1274     #[stable(feature = "pointer_methods", since = "1.26.0")]
1275     #[must_use = "returns a new pointer rather than modifying its argument"]
1276     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1277     #[inline(always)]
1278     pub const fn wrapping_sub(self, count: usize) -> Self
1279     where
1280         T: Sized,
1281     {
1282         self.wrapping_offset((count as isize).wrapping_neg())
1283     }
1284
1285     /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1286     /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1287     ///
1288     /// `count` is in units of bytes.
1289     ///
1290     /// This is purely a convenience for casting to a `u8` pointer and
1291     /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1292     ///
1293     /// For non-`Sized` pointees this operation changes only the data pointer,
1294     /// leaving the metadata untouched.
1295     #[must_use]
1296     #[inline(always)]
1297     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1298     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1299     pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1300         self.cast::<u8>().wrapping_sub(count).with_metadata_of(self)
1301     }
1302
1303     /// Reads the value from `self` without moving it. This leaves the
1304     /// memory in `self` unchanged.
1305     ///
1306     /// See [`ptr::read`] for safety concerns and examples.
1307     ///
1308     /// [`ptr::read`]: crate::ptr::read()
1309     #[stable(feature = "pointer_methods", since = "1.26.0")]
1310     #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1311     #[inline(always)]
1312     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1313     pub const unsafe fn read(self) -> T
1314     where
1315         T: Sized,
1316     {
1317         // SAFETY: the caller must uphold the safety contract for ``.
1318         unsafe { read(self) }
1319     }
1320
1321     /// Performs a volatile read of the value from `self` without moving it. This
1322     /// leaves the memory in `self` unchanged.
1323     ///
1324     /// Volatile operations are intended to act on I/O memory, and are guaranteed
1325     /// to not be elided or reordered by the compiler across other volatile
1326     /// operations.
1327     ///
1328     /// See [`ptr::read_volatile`] for safety concerns and examples.
1329     ///
1330     /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1331     #[stable(feature = "pointer_methods", since = "1.26.0")]
1332     #[inline(always)]
1333     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1334     pub unsafe fn read_volatile(self) -> T
1335     where
1336         T: Sized,
1337     {
1338         // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1339         unsafe { read_volatile(self) }
1340     }
1341
1342     /// Reads the value from `self` without moving it. This leaves the
1343     /// memory in `self` unchanged.
1344     ///
1345     /// Unlike `read`, the pointer may be unaligned.
1346     ///
1347     /// See [`ptr::read_unaligned`] for safety concerns and examples.
1348     ///
1349     /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1350     #[stable(feature = "pointer_methods", since = "1.26.0")]
1351     #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1352     #[inline(always)]
1353     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1354     pub const unsafe fn read_unaligned(self) -> T
1355     where
1356         T: Sized,
1357     {
1358         // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1359         unsafe { read_unaligned(self) }
1360     }
1361
1362     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1363     /// and destination may overlap.
1364     ///
1365     /// NOTE: this has the *same* argument order as [`ptr::copy`].
1366     ///
1367     /// See [`ptr::copy`] for safety concerns and examples.
1368     ///
1369     /// [`ptr::copy`]: crate::ptr::copy()
1370     #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1371     #[stable(feature = "pointer_methods", since = "1.26.0")]
1372     #[inline(always)]
1373     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1374     pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1375     where
1376         T: Sized,
1377     {
1378         // SAFETY: the caller must uphold the safety contract for `copy`.
1379         unsafe { copy(self, dest, count) }
1380     }
1381
1382     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1383     /// and destination may *not* overlap.
1384     ///
1385     /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1386     ///
1387     /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1388     ///
1389     /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1390     #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1391     #[stable(feature = "pointer_methods", since = "1.26.0")]
1392     #[inline(always)]
1393     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1394     pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1395     where
1396         T: Sized,
1397     {
1398         // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1399         unsafe { copy_nonoverlapping(self, dest, count) }
1400     }
1401
1402     /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1403     /// and destination may overlap.
1404     ///
1405     /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1406     ///
1407     /// See [`ptr::copy`] for safety concerns and examples.
1408     ///
1409     /// [`ptr::copy`]: crate::ptr::copy()
1410     #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1411     #[stable(feature = "pointer_methods", since = "1.26.0")]
1412     #[inline(always)]
1413     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1414     pub const unsafe fn copy_from(self, src: *const T, count: usize)
1415     where
1416         T: Sized,
1417     {
1418         // SAFETY: the caller must uphold the safety contract for `copy`.
1419         unsafe { copy(src, self, count) }
1420     }
1421
1422     /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1423     /// and destination may *not* overlap.
1424     ///
1425     /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1426     ///
1427     /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1428     ///
1429     /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1430     #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1431     #[stable(feature = "pointer_methods", since = "1.26.0")]
1432     #[inline(always)]
1433     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1434     pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1435     where
1436         T: Sized,
1437     {
1438         // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1439         unsafe { copy_nonoverlapping(src, self, count) }
1440     }
1441
1442     /// Executes the destructor (if any) of the pointed-to value.
1443     ///
1444     /// See [`ptr::drop_in_place`] for safety concerns and examples.
1445     ///
1446     /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1447     #[stable(feature = "pointer_methods", since = "1.26.0")]
1448     #[inline(always)]
1449     pub unsafe fn drop_in_place(self) {
1450         // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1451         unsafe { drop_in_place(self) }
1452     }
1453
1454     /// Overwrites a memory location with the given value without reading or
1455     /// dropping the old value.
1456     ///
1457     /// See [`ptr::write`] for safety concerns and examples.
1458     ///
1459     /// [`ptr::write`]: crate::ptr::write()
1460     #[stable(feature = "pointer_methods", since = "1.26.0")]
1461     #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1462     #[inline(always)]
1463     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1464     pub const unsafe fn write(self, val: T)
1465     where
1466         T: Sized,
1467     {
1468         // SAFETY: the caller must uphold the safety contract for `write`.
1469         unsafe { write(self, val) }
1470     }
1471
1472     /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1473     /// bytes of memory starting at `self` to `val`.
1474     ///
1475     /// See [`ptr::write_bytes`] for safety concerns and examples.
1476     ///
1477     /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1478     #[doc(alias = "memset")]
1479     #[stable(feature = "pointer_methods", since = "1.26.0")]
1480     #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1481     #[inline(always)]
1482     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1483     pub const unsafe fn write_bytes(self, val: u8, count: usize)
1484     where
1485         T: Sized,
1486     {
1487         // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1488         unsafe { write_bytes(self, val, count) }
1489     }
1490
1491     /// Performs a volatile write of a memory location with the given value without
1492     /// reading or dropping the old value.
1493     ///
1494     /// Volatile operations are intended to act on I/O memory, and are guaranteed
1495     /// to not be elided or reordered by the compiler across other volatile
1496     /// operations.
1497     ///
1498     /// See [`ptr::write_volatile`] for safety concerns and examples.
1499     ///
1500     /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1501     #[stable(feature = "pointer_methods", since = "1.26.0")]
1502     #[inline(always)]
1503     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1504     pub unsafe fn write_volatile(self, val: T)
1505     where
1506         T: Sized,
1507     {
1508         // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1509         unsafe { write_volatile(self, val) }
1510     }
1511
1512     /// Overwrites a memory location with the given value without reading or
1513     /// dropping the old value.
1514     ///
1515     /// Unlike `write`, the pointer may be unaligned.
1516     ///
1517     /// See [`ptr::write_unaligned`] for safety concerns and examples.
1518     ///
1519     /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1520     #[stable(feature = "pointer_methods", since = "1.26.0")]
1521     #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1522     #[inline(always)]
1523     #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1524     pub const unsafe fn write_unaligned(self, val: T)
1525     where
1526         T: Sized,
1527     {
1528         // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1529         unsafe { write_unaligned(self, val) }
1530     }
1531
1532     /// Replaces the value at `self` with `src`, returning the old
1533     /// value, without dropping either.
1534     ///
1535     /// See [`ptr::replace`] for safety concerns and examples.
1536     ///
1537     /// [`ptr::replace`]: crate::ptr::replace()
1538     #[stable(feature = "pointer_methods", since = "1.26.0")]
1539     #[inline(always)]
1540     pub unsafe fn replace(self, src: T) -> T
1541     where
1542         T: Sized,
1543     {
1544         // SAFETY: the caller must uphold the safety contract for `replace`.
1545         unsafe { replace(self, src) }
1546     }
1547
1548     /// Swaps the values at two mutable locations of the same type, without
1549     /// deinitializing either. They may overlap, unlike `mem::swap` which is
1550     /// otherwise equivalent.
1551     ///
1552     /// See [`ptr::swap`] for safety concerns and examples.
1553     ///
1554     /// [`ptr::swap`]: crate::ptr::swap()
1555     #[stable(feature = "pointer_methods", since = "1.26.0")]
1556     #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
1557     #[inline(always)]
1558     pub const unsafe fn swap(self, with: *mut T)
1559     where
1560         T: Sized,
1561     {
1562         // SAFETY: the caller must uphold the safety contract for `swap`.
1563         unsafe { swap(self, with) }
1564     }
1565
1566     /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1567     /// `align`.
1568     ///
1569     /// If it is not possible to align the pointer, the implementation returns
1570     /// `usize::MAX`. It is permissible for the implementation to *always*
1571     /// return `usize::MAX`. Only your algorithm's performance can depend
1572     /// on getting a usable offset here, not its correctness.
1573     ///
1574     /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1575     /// used with the `wrapping_add` method.
1576     ///
1577     /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1578     /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1579     /// the returned offset is correct in all terms other than alignment.
1580     ///
1581     /// # Panics
1582     ///
1583     /// The function panics if `align` is not a power-of-two.
1584     ///
1585     /// # Examples
1586     ///
1587     /// Accessing adjacent `u8` as `u16`
1588     ///
1589     /// ```
1590     /// use std::mem::align_of;
1591     ///
1592     /// # unsafe {
1593     /// let mut x = [5_u8, 6, 7, 8, 9];
1594     /// let ptr = x.as_mut_ptr();
1595     /// let offset = ptr.align_offset(align_of::<u16>());
1596     ///
1597     /// if offset < x.len() - 1 {
1598     ///     let u16_ptr = ptr.add(offset).cast::<u16>();
1599     ///     *u16_ptr = 0;
1600     ///
1601     ///     assert!(x == [0, 0, 7, 8, 9] || x == [5, 0, 0, 8, 9]);
1602     /// } else {
1603     ///     // while the pointer can be aligned via `offset`, it would point
1604     ///     // outside the allocation
1605     /// }
1606     /// # }
1607     /// ```
1608     #[must_use]
1609     #[inline]
1610     #[stable(feature = "align_offset", since = "1.36.0")]
1611     #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1612     pub const fn align_offset(self, align: usize) -> usize
1613     where
1614         T: Sized,
1615     {
1616         if !align.is_power_of_two() {
1617             panic!("align_offset: align is not a power-of-two");
1618         }
1619
1620         {
1621             // SAFETY: `align` has been checked to be a power of 2 above
1622             unsafe { align_offset(self, align) }
1623         }
1624     }
1625
1626     /// Returns whether the pointer is properly aligned for `T`.
1627     ///
1628     /// # Examples
1629     ///
1630     /// Basic usage:
1631     /// ```
1632     /// #![feature(pointer_is_aligned)]
1633     /// #![feature(pointer_byte_offsets)]
1634     ///
1635     /// // On some platforms, the alignment of i32 is less than 4.
1636     /// #[repr(align(4))]
1637     /// struct AlignedI32(i32);
1638     ///
1639     /// let mut data = AlignedI32(42);
1640     /// let ptr = &mut data as *mut AlignedI32;
1641     ///
1642     /// assert!(ptr.is_aligned());
1643     /// assert!(!ptr.wrapping_byte_add(1).is_aligned());
1644     /// ```
1645     ///
1646     /// # At compiletime
1647     /// **Note: Alignment at compiletime is experimental and subject to change. See the
1648     /// [tracking issue] for details.**
1649     ///
1650     /// At compiletime, the compiler may not know where a value will end up in memory.
1651     /// Calling this function on a pointer created from a reference at compiletime will only
1652     /// return `true` if the pointer is guaranteed to be aligned. This means that the pointer
1653     /// is never aligned if cast to a type with a stricter alignment than the reference's
1654     /// underlying allocation.
1655     ///
1656     /// ```
1657     /// #![feature(pointer_is_aligned)]
1658     /// #![feature(const_pointer_is_aligned)]
1659     /// #![feature(const_mut_refs)]
1660     ///
1661     /// // On some platforms, the alignment of primitives is less than their size.
1662     /// #[repr(align(4))]
1663     /// struct AlignedI32(i32);
1664     /// #[repr(align(8))]
1665     /// struct AlignedI64(i64);
1666     ///
1667     /// const _: () = {
1668     ///     let mut data = AlignedI32(42);
1669     ///     let ptr = &mut data as *mut AlignedI32;
1670     ///     assert!(ptr.is_aligned());
1671     ///
1672     ///     // At runtime either `ptr1` or `ptr2` would be aligned, but at compiletime neither is aligned.
1673     ///     let ptr1 = ptr.cast::<AlignedI64>();
1674     ///     let ptr2 = ptr.wrapping_add(1).cast::<AlignedI64>();
1675     ///     assert!(!ptr1.is_aligned());
1676     ///     assert!(!ptr2.is_aligned());
1677     /// };
1678     /// ```
1679     ///
1680     /// Due to this behavior, it is possible that a runtime pointer derived from a compiletime
1681     /// pointer is aligned, even if the compiletime pointer wasn't aligned.
1682     ///
1683     /// ```
1684     /// #![feature(pointer_is_aligned)]
1685     /// #![feature(const_pointer_is_aligned)]
1686     ///
1687     /// // On some platforms, the alignment of primitives is less than their size.
1688     /// #[repr(align(4))]
1689     /// struct AlignedI32(i32);
1690     /// #[repr(align(8))]
1691     /// struct AlignedI64(i64);
1692     ///
1693     /// // At compiletime, neither `COMPTIME_PTR` nor `COMPTIME_PTR + 1` is aligned.
1694     /// // Also, note that mutable references are not allowed in the final value of constants.
1695     /// const COMPTIME_PTR: *mut AlignedI32 = (&AlignedI32(42) as *const AlignedI32).cast_mut();
1696     /// const _: () = assert!(!COMPTIME_PTR.cast::<AlignedI64>().is_aligned());
1697     /// const _: () = assert!(!COMPTIME_PTR.wrapping_add(1).cast::<AlignedI64>().is_aligned());
1698     ///
1699     /// // At runtime, either `runtime_ptr` or `runtime_ptr + 1` is aligned.
1700     /// let runtime_ptr = COMPTIME_PTR;
1701     /// assert_ne!(
1702     ///     runtime_ptr.cast::<AlignedI64>().is_aligned(),
1703     ///     runtime_ptr.wrapping_add(1).cast::<AlignedI64>().is_aligned(),
1704     /// );
1705     /// ```
1706     ///
1707     /// If a pointer is created from a fixed address, this function behaves the same during
1708     /// runtime and compiletime.
1709     ///
1710     /// ```
1711     /// #![feature(pointer_is_aligned)]
1712     /// #![feature(const_pointer_is_aligned)]
1713     ///
1714     /// // On some platforms, the alignment of primitives is less than their size.
1715     /// #[repr(align(4))]
1716     /// struct AlignedI32(i32);
1717     /// #[repr(align(8))]
1718     /// struct AlignedI64(i64);
1719     ///
1720     /// const _: () = {
1721     ///     let ptr = 40 as *mut AlignedI32;
1722     ///     assert!(ptr.is_aligned());
1723     ///
1724     ///     // For pointers with a known address, runtime and compiletime behavior are identical.
1725     ///     let ptr1 = ptr.cast::<AlignedI64>();
1726     ///     let ptr2 = ptr.wrapping_add(1).cast::<AlignedI64>();
1727     ///     assert!(ptr1.is_aligned());
1728     ///     assert!(!ptr2.is_aligned());
1729     /// };
1730     /// ```
1731     ///
1732     /// [tracking issue]: https://github.com/rust-lang/rust/issues/104203
1733     #[must_use]
1734     #[inline]
1735     #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1736     #[rustc_const_unstable(feature = "const_pointer_is_aligned", issue = "104203")]
1737     pub const fn is_aligned(self) -> bool
1738     where
1739         T: Sized,
1740     {
1741         self.is_aligned_to(mem::align_of::<T>())
1742     }
1743
1744     /// Returns whether the pointer is aligned to `align`.
1745     ///
1746     /// For non-`Sized` pointees this operation considers only the data pointer,
1747     /// ignoring the metadata.
1748     ///
1749     /// # Panics
1750     ///
1751     /// The function panics if `align` is not a power-of-two (this includes 0).
1752     ///
1753     /// # Examples
1754     ///
1755     /// Basic usage:
1756     /// ```
1757     /// #![feature(pointer_is_aligned)]
1758     /// #![feature(pointer_byte_offsets)]
1759     ///
1760     /// // On some platforms, the alignment of i32 is less than 4.
1761     /// #[repr(align(4))]
1762     /// struct AlignedI32(i32);
1763     ///
1764     /// let mut data = AlignedI32(42);
1765     /// let ptr = &mut data as *mut AlignedI32;
1766     ///
1767     /// assert!(ptr.is_aligned_to(1));
1768     /// assert!(ptr.is_aligned_to(2));
1769     /// assert!(ptr.is_aligned_to(4));
1770     ///
1771     /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1772     /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1773     ///
1774     /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1775     /// ```
1776     ///
1777     /// # At compiletime
1778     /// **Note: Alignment at compiletime is experimental and subject to change. See the
1779     /// [tracking issue] for details.**
1780     ///
1781     /// At compiletime, the compiler may not know where a value will end up in memory.
1782     /// Calling this function on a pointer created from a reference at compiletime will only
1783     /// return `true` if the pointer is guaranteed to be aligned. This means that the pointer
1784     /// cannot be stricter aligned than the reference's underlying allocation.
1785     ///
1786     /// ```
1787     /// #![feature(pointer_is_aligned)]
1788     /// #![feature(const_pointer_is_aligned)]
1789     /// #![feature(const_mut_refs)]
1790     ///
1791     /// // On some platforms, the alignment of i32 is less than 4.
1792     /// #[repr(align(4))]
1793     /// struct AlignedI32(i32);
1794     ///
1795     /// const _: () = {
1796     ///     let mut data = AlignedI32(42);
1797     ///     let ptr = &mut data as *mut AlignedI32;
1798     ///
1799     ///     assert!(ptr.is_aligned_to(1));
1800     ///     assert!(ptr.is_aligned_to(2));
1801     ///     assert!(ptr.is_aligned_to(4));
1802     ///
1803     ///     // At compiletime, we know for sure that the pointer isn't aligned to 8.
1804     ///     assert!(!ptr.is_aligned_to(8));
1805     ///     assert!(!ptr.wrapping_add(1).is_aligned_to(8));
1806     /// };
1807     /// ```
1808     ///
1809     /// Due to this behavior, it is possible that a runtime pointer derived from a compiletime
1810     /// pointer is aligned, even if the compiletime pointer wasn't aligned.
1811     ///
1812     /// ```
1813     /// #![feature(pointer_is_aligned)]
1814     /// #![feature(const_pointer_is_aligned)]
1815     ///
1816     /// // On some platforms, the alignment of i32 is less than 4.
1817     /// #[repr(align(4))]
1818     /// struct AlignedI32(i32);
1819     ///
1820     /// // At compiletime, neither `COMPTIME_PTR` nor `COMPTIME_PTR + 1` is aligned.
1821     /// // Also, note that mutable references are not allowed in the final value of constants.
1822     /// const COMPTIME_PTR: *mut AlignedI32 = (&AlignedI32(42) as *const AlignedI32).cast_mut();
1823     /// const _: () = assert!(!COMPTIME_PTR.is_aligned_to(8));
1824     /// const _: () = assert!(!COMPTIME_PTR.wrapping_add(1).is_aligned_to(8));
1825     ///
1826     /// // At runtime, either `runtime_ptr` or `runtime_ptr + 1` is aligned.
1827     /// let runtime_ptr = COMPTIME_PTR;
1828     /// assert_ne!(
1829     ///     runtime_ptr.is_aligned_to(8),
1830     ///     runtime_ptr.wrapping_add(1).is_aligned_to(8),
1831     /// );
1832     /// ```
1833     ///
1834     /// If a pointer is created from a fixed address, this function behaves the same during
1835     /// runtime and compiletime.
1836     ///
1837     /// ```
1838     /// #![feature(pointer_is_aligned)]
1839     /// #![feature(const_pointer_is_aligned)]
1840     ///
1841     /// const _: () = {
1842     ///     let ptr = 40 as *mut u8;
1843     ///     assert!(ptr.is_aligned_to(1));
1844     ///     assert!(ptr.is_aligned_to(2));
1845     ///     assert!(ptr.is_aligned_to(4));
1846     ///     assert!(ptr.is_aligned_to(8));
1847     ///     assert!(!ptr.is_aligned_to(16));
1848     /// };
1849     /// ```
1850     ///
1851     /// [tracking issue]: https://github.com/rust-lang/rust/issues/104203
1852     #[must_use]
1853     #[inline]
1854     #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1855     #[rustc_const_unstable(feature = "const_pointer_is_aligned", issue = "104203")]
1856     pub const fn is_aligned_to(self, align: usize) -> bool {
1857         if !align.is_power_of_two() {
1858             panic!("is_aligned_to: align is not a power-of-two");
1859         }
1860
1861         #[inline]
1862         fn runtime_impl(ptr: *mut (), align: usize) -> bool {
1863             ptr.addr() & (align - 1) == 0
1864         }
1865
1866         #[inline]
1867         const fn const_impl(ptr: *mut (), align: usize) -> bool {
1868             // We can't use the address of `self` in a `const fn`, so we use `align_offset` instead.
1869             // The cast to `()` is used to
1870             //   1. deal with fat pointers; and
1871             //   2. ensure that `align_offset` doesn't actually try to compute an offset.
1872             ptr.align_offset(align) == 0
1873         }
1874
1875         // SAFETY: The two versions are equivalent at runtime.
1876         unsafe { const_eval_select((self.cast::<()>(), align), const_impl, runtime_impl) }
1877     }
1878 }
1879
1880 impl<T> *mut [T] {
1881     /// Returns the length of a raw slice.
1882     ///
1883     /// The returned value is the number of **elements**, not the number of bytes.
1884     ///
1885     /// This function is safe, even when the raw slice cannot be cast to a slice
1886     /// reference because the pointer is null or unaligned.
1887     ///
1888     /// # Examples
1889     ///
1890     /// ```rust
1891     /// #![feature(slice_ptr_len)]
1892     /// use std::ptr;
1893     ///
1894     /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1895     /// assert_eq!(slice.len(), 3);
1896     /// ```
1897     #[inline(always)]
1898     #[unstable(feature = "slice_ptr_len", issue = "71146")]
1899     #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1900     pub const fn len(self) -> usize {
1901         metadata(self)
1902     }
1903
1904     /// Returns `true` if the raw slice has a length of 0.
1905     ///
1906     /// # Examples
1907     ///
1908     /// ```
1909     /// #![feature(slice_ptr_len)]
1910     ///
1911     /// let mut a = [1, 2, 3];
1912     /// let ptr = &mut a as *mut [_];
1913     /// assert!(!ptr.is_empty());
1914     /// ```
1915     #[inline(always)]
1916     #[unstable(feature = "slice_ptr_len", issue = "71146")]
1917     #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1918     pub const fn is_empty(self) -> bool {
1919         self.len() == 0
1920     }
1921
1922     /// Divides one mutable raw slice into two at an index.
1923     ///
1924     /// The first will contain all indices from `[0, mid)` (excluding
1925     /// the index `mid` itself) and the second will contain all
1926     /// indices from `[mid, len)` (excluding the index `len` itself).
1927     ///
1928     /// # Panics
1929     ///
1930     /// Panics if `mid > len`.
1931     ///
1932     /// # Safety
1933     ///
1934     /// `mid` must be [in-bounds] of the underlying [allocated object].
1935     /// Which means `self` must be dereferenceable and span a single allocation
1936     /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1937     /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1938     ///
1939     /// Since `len` being in-bounds it is not a safety invariant of `*mut [T]` the
1940     /// safety requirements of this method are the same as for [`split_at_mut_unchecked`].
1941     /// The explicit bounds check is only as useful as `len` is correct.
1942     ///
1943     /// [`split_at_mut_unchecked`]: #method.split_at_mut_unchecked
1944     /// [in-bounds]: #method.add
1945     /// [allocated object]: crate::ptr#allocated-object
1946     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1947     ///
1948     /// # Examples
1949     ///
1950     /// ```
1951     /// #![feature(raw_slice_split)]
1952     /// #![feature(slice_ptr_get)]
1953     ///
1954     /// let mut v = [1, 0, 3, 0, 5, 6];
1955     /// let ptr = &mut v as *mut [_];
1956     /// unsafe {
1957     ///     let (left, right) = ptr.split_at_mut(2);
1958     ///     assert_eq!(&*left, [1, 0]);
1959     ///     assert_eq!(&*right, [3, 0, 5, 6]);
1960     /// }
1961     /// ```
1962     #[inline(always)]
1963     #[track_caller]
1964     #[unstable(feature = "raw_slice_split", issue = "95595")]
1965     pub unsafe fn split_at_mut(self, mid: usize) -> (*mut [T], *mut [T]) {
1966         assert!(mid <= self.len());
1967         // SAFETY: The assert above is only a safety-net as long as `self.len()` is correct
1968         // The actual safety requirements of this function are the same as for `split_at_mut_unchecked`
1969         unsafe { self.split_at_mut_unchecked(mid) }
1970     }
1971
1972     /// Divides one mutable raw slice into two at an index, without doing bounds checking.
1973     ///
1974     /// The first will contain all indices from `[0, mid)` (excluding
1975     /// the index `mid` itself) and the second will contain all
1976     /// indices from `[mid, len)` (excluding the index `len` itself).
1977     ///
1978     /// # Safety
1979     ///
1980     /// `mid` must be [in-bounds] of the underlying [allocated object].
1981     /// Which means `self` must be dereferenceable and span a single allocation
1982     /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1983     /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1984     ///
1985     /// [in-bounds]: #method.add
1986     /// [out-of-bounds index]: #method.add
1987     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1988     ///
1989     /// # Examples
1990     ///
1991     /// ```
1992     /// #![feature(raw_slice_split)]
1993     ///
1994     /// let mut v = [1, 0, 3, 0, 5, 6];
1995     /// // scoped to restrict the lifetime of the borrows
1996     /// unsafe {
1997     ///     let ptr = &mut v as *mut [_];
1998     ///     let (left, right) = ptr.split_at_mut_unchecked(2);
1999     ///     assert_eq!(&*left, [1, 0]);
2000     ///     assert_eq!(&*right, [3, 0, 5, 6]);
2001     ///     (&mut *left)[1] = 2;
2002     ///     (&mut *right)[1] = 4;
2003     /// }
2004     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
2005     /// ```
2006     #[inline(always)]
2007     #[unstable(feature = "raw_slice_split", issue = "95595")]
2008     pub unsafe fn split_at_mut_unchecked(self, mid: usize) -> (*mut [T], *mut [T]) {
2009         let len = self.len();
2010         let ptr = self.as_mut_ptr();
2011
2012         // SAFETY: Caller must pass a valid pointer and an index that is in-bounds.
2013         let tail = unsafe { ptr.add(mid) };
2014         (
2015             crate::ptr::slice_from_raw_parts_mut(ptr, mid),
2016             crate::ptr::slice_from_raw_parts_mut(tail, len - mid),
2017         )
2018     }
2019
2020     /// Returns a raw pointer to the slice's buffer.
2021     ///
2022     /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
2023     ///
2024     /// # Examples
2025     ///
2026     /// ```rust
2027     /// #![feature(slice_ptr_get)]
2028     /// use std::ptr;
2029     ///
2030     /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
2031     /// assert_eq!(slice.as_mut_ptr(), ptr::null_mut());
2032     /// ```
2033     #[inline(always)]
2034     #[unstable(feature = "slice_ptr_get", issue = "74265")]
2035     #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
2036     pub const fn as_mut_ptr(self) -> *mut T {
2037         self as *mut T
2038     }
2039
2040     /// Returns a raw pointer to an element or subslice, without doing bounds
2041     /// checking.
2042     ///
2043     /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
2044     /// is *[undefined behavior]* even if the resulting pointer is not used.
2045     ///
2046     /// [out-of-bounds index]: #method.add
2047     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2048     ///
2049     /// # Examples
2050     ///
2051     /// ```
2052     /// #![feature(slice_ptr_get)]
2053     ///
2054     /// let x = &mut [1, 2, 4] as *mut [i32];
2055     ///
2056     /// unsafe {
2057     ///     assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
2058     /// }
2059     /// ```
2060     #[unstable(feature = "slice_ptr_get", issue = "74265")]
2061     #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
2062     #[inline(always)]
2063     pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
2064     where
2065         I: ~const SliceIndex<[T]>,
2066     {
2067         // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
2068         unsafe { index.get_unchecked_mut(self) }
2069     }
2070
2071     /// Returns `None` if the pointer is null, or else returns a shared slice to
2072     /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
2073     /// that the value has to be initialized.
2074     ///
2075     /// For the mutable counterpart see [`as_uninit_slice_mut`].
2076     ///
2077     /// [`as_ref`]: #method.as_ref-1
2078     /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
2079     ///
2080     /// # Safety
2081     ///
2082     /// When calling this method, you have to ensure that *either* the pointer is null *or*
2083     /// all of the following is true:
2084     ///
2085     /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
2086     ///   and it must be properly aligned. This means in particular:
2087     ///
2088     ///     * The entire memory range of this slice must be contained within a single [allocated object]!
2089     ///       Slices can never span across multiple allocated objects.
2090     ///
2091     ///     * The pointer must be aligned even for zero-length slices. One
2092     ///       reason for this is that enum layout optimizations may rely on references
2093     ///       (including slices of any length) being aligned and non-null to distinguish
2094     ///       them from other data. You can obtain a pointer that is usable as `data`
2095     ///       for zero-length slices using [`NonNull::dangling()`].
2096     ///
2097     /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
2098     ///   See the safety documentation of [`pointer::offset`].
2099     ///
2100     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
2101     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
2102     ///   In particular, while this reference exists, the memory the pointer points to must
2103     ///   not get mutated (except inside `UnsafeCell`).
2104     ///
2105     /// This applies even if the result of this method is unused!
2106     ///
2107     /// See also [`slice::from_raw_parts`][].
2108     ///
2109     /// [valid]: crate::ptr#safety
2110     /// [allocated object]: crate::ptr#allocated-object
2111     #[inline]
2112     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
2113     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
2114     pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
2115         if self.is_null() {
2116             None
2117         } else {
2118             // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
2119             Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
2120         }
2121     }
2122
2123     /// Returns `None` if the pointer is null, or else returns a unique slice to
2124     /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
2125     /// that the value has to be initialized.
2126     ///
2127     /// For the shared counterpart see [`as_uninit_slice`].
2128     ///
2129     /// [`as_mut`]: #method.as_mut
2130     /// [`as_uninit_slice`]: #method.as_uninit_slice-1
2131     ///
2132     /// # Safety
2133     ///
2134     /// When calling this method, you have to ensure that *either* the pointer is null *or*
2135     /// all of the following is true:
2136     ///
2137     /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
2138     ///   many bytes, and it must be properly aligned. This means in particular:
2139     ///
2140     ///     * The entire memory range of this slice must be contained within a single [allocated object]!
2141     ///       Slices can never span across multiple allocated objects.
2142     ///
2143     ///     * The pointer must be aligned even for zero-length slices. One
2144     ///       reason for this is that enum layout optimizations may rely on references
2145     ///       (including slices of any length) being aligned and non-null to distinguish
2146     ///       them from other data. You can obtain a pointer that is usable as `data`
2147     ///       for zero-length slices using [`NonNull::dangling()`].
2148     ///
2149     /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
2150     ///   See the safety documentation of [`pointer::offset`].
2151     ///
2152     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
2153     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
2154     ///   In particular, while this reference exists, the memory the pointer points to must
2155     ///   not get accessed (read or written) through any other pointer.
2156     ///
2157     /// This applies even if the result of this method is unused!
2158     ///
2159     /// See also [`slice::from_raw_parts_mut`][].
2160     ///
2161     /// [valid]: crate::ptr#safety
2162     /// [allocated object]: crate::ptr#allocated-object
2163     #[inline]
2164     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
2165     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
2166     pub const unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
2167         if self.is_null() {
2168             None
2169         } else {
2170             // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
2171             Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
2172         }
2173     }
2174 }
2175
2176 // Equality for pointers
2177 #[stable(feature = "rust1", since = "1.0.0")]
2178 impl<T: ?Sized> PartialEq for *mut T {
2179     #[inline(always)]
2180     fn eq(&self, other: &*mut T) -> bool {
2181         *self == *other
2182     }
2183 }
2184
2185 #[stable(feature = "rust1", since = "1.0.0")]
2186 impl<T: ?Sized> Eq for *mut T {}
2187
2188 #[stable(feature = "rust1", since = "1.0.0")]
2189 impl<T: ?Sized> Ord for *mut T {
2190     #[inline]
2191     fn cmp(&self, other: &*mut T) -> Ordering {
2192         if self < other {
2193             Less
2194         } else if self == other {
2195             Equal
2196         } else {
2197             Greater
2198         }
2199     }
2200 }
2201
2202 #[stable(feature = "rust1", since = "1.0.0")]
2203 impl<T: ?Sized> PartialOrd for *mut T {
2204     #[inline(always)]
2205     fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2206         Some(self.cmp(other))
2207     }
2208
2209     #[inline(always)]
2210     fn lt(&self, other: &*mut T) -> bool {
2211         *self < *other
2212     }
2213
2214     #[inline(always)]
2215     fn le(&self, other: &*mut T) -> bool {
2216         *self <= *other
2217     }
2218
2219     #[inline(always)]
2220     fn gt(&self, other: &*mut T) -> bool {
2221         *self > *other
2222     }
2223
2224     #[inline(always)]
2225     fn ge(&self, other: &*mut T) -> bool {
2226         *self >= *other
2227     }
2228 }