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