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