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