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