]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/mut_ptr.rs
Auto merge of #99598 - GuillaumeGomez:clean-trait-fields-on-demand, r=notriddle
[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     #[unstable(feature = "ptr_const_cast", issue = "92675")]
104     #[rustc_const_unstable(feature = "ptr_const_cast", issue = "92675")]
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 dereferencable 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.cast::<u8>().wrapping_offset(offset).cast::<T>()
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     pub const unsafe fn offset(self, count: isize) -> *mut T
465     where
466         T: Sized,
467     {
468         // SAFETY: the caller must uphold the safety contract for `offset`.
469         // The obtained pointer is valid for writes since the caller must
470         // guarantee that it points to the same allocated object as `self`.
471         unsafe { intrinsics::offset(self, count) as *mut T }
472     }
473
474     /// Calculates the offset from a pointer in bytes.
475     ///
476     /// `count` is in units of **bytes**.
477     ///
478     /// This is purely a convenience for casting to a `u8` pointer and
479     /// using [offset][pointer::offset] on it. See that method for documentation
480     /// and safety requirements.
481     ///
482     /// For non-`Sized` pointees this operation changes only the data pointer,
483     /// leaving the metadata untouched.
484     #[must_use]
485     #[inline(always)]
486     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
487     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
488     pub const unsafe fn byte_offset(self, count: isize) -> Self {
489         // SAFETY: the caller must uphold the safety contract for `offset`.
490         let this = unsafe { self.cast::<u8>().offset(count).cast::<()>() };
491         from_raw_parts_mut::<T>(this, metadata(self))
492     }
493
494     /// Calculates the offset from a pointer using wrapping arithmetic.
495     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
496     /// offset of `3 * size_of::<T>()` bytes.
497     ///
498     /// # Safety
499     ///
500     /// This operation itself is always safe, but using the resulting pointer is not.
501     ///
502     /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
503     /// be used to read or write other allocated objects.
504     ///
505     /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
506     /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
507     /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
508     /// `x` and `y` point into the same allocated object.
509     ///
510     /// Compared to [`offset`], this method basically delays the requirement of staying within the
511     /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
512     /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
513     /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
514     /// can be optimized better and is thus preferable in performance-sensitive code.
515     ///
516     /// The delayed check only considers the value of the pointer that was dereferenced, not the
517     /// intermediate values used during the computation of the final result. For example,
518     /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
519     /// words, leaving the allocated object and then re-entering it later is permitted.
520     ///
521     /// [`offset`]: #method.offset
522     /// [allocated object]: crate::ptr#allocated-object
523     ///
524     /// # Examples
525     ///
526     /// Basic usage:
527     ///
528     /// ```
529     /// // Iterate using a raw pointer in increments of two elements
530     /// let mut data = [1u8, 2, 3, 4, 5];
531     /// let mut ptr: *mut u8 = data.as_mut_ptr();
532     /// let step = 2;
533     /// let end_rounded_up = ptr.wrapping_offset(6);
534     ///
535     /// while ptr != end_rounded_up {
536     ///     unsafe {
537     ///         *ptr = 0;
538     ///     }
539     ///     ptr = ptr.wrapping_offset(step);
540     /// }
541     /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
542     /// ```
543     #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
544     #[must_use = "returns a new pointer rather than modifying its argument"]
545     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
546     #[inline(always)]
547     pub const fn wrapping_offset(self, count: isize) -> *mut T
548     where
549         T: Sized,
550     {
551         // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
552         unsafe { intrinsics::arith_offset(self, count) as *mut T }
553     }
554
555     /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
556     ///
557     /// `count` is in units of **bytes**.
558     ///
559     /// This is purely a convenience for casting to a `u8` pointer and
560     /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
561     /// for documentation.
562     ///
563     /// For non-`Sized` pointees this operation changes only the data pointer,
564     /// leaving the metadata untouched.
565     #[must_use]
566     #[inline(always)]
567     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
568     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
569     pub const fn wrapping_byte_offset(self, count: isize) -> Self {
570         from_raw_parts_mut::<T>(
571             self.cast::<u8>().wrapping_offset(count).cast::<()>(),
572             metadata(self),
573         )
574     }
575
576     /// Returns `None` if the pointer is null, or else returns a unique reference to
577     /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
578     /// must be used instead.
579     ///
580     /// For the shared counterpart see [`as_ref`].
581     ///
582     /// [`as_uninit_mut`]: #method.as_uninit_mut
583     /// [`as_ref`]: #method.as_ref-1
584     ///
585     /// # Safety
586     ///
587     /// When calling this method, you have to ensure that *either* the pointer is null *or*
588     /// all of the following is true:
589     ///
590     /// * The pointer must be properly aligned.
591     ///
592     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
593     ///
594     /// * The pointer must point to an initialized instance of `T`.
595     ///
596     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
597     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
598     ///   In particular, while this reference exists, the memory the pointer points to must
599     ///   not get accessed (read or written) through any other pointer.
600     ///
601     /// This applies even if the result of this method is unused!
602     /// (The part about being initialized is not yet fully decided, but until
603     /// it is, the only safe approach is to ensure that they are indeed initialized.)
604     ///
605     /// [the module documentation]: crate::ptr#safety
606     ///
607     /// # Examples
608     ///
609     /// Basic usage:
610     ///
611     /// ```
612     /// let mut s = [1, 2, 3];
613     /// let ptr: *mut u32 = s.as_mut_ptr();
614     /// let first_value = unsafe { ptr.as_mut().unwrap() };
615     /// *first_value = 4;
616     /// # assert_eq!(s, [4, 2, 3]);
617     /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
618     /// ```
619     ///
620     /// # Null-unchecked version
621     ///
622     /// If you are sure the pointer can never be null and are looking for some kind of
623     /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
624     /// you can dereference the pointer directly.
625     ///
626     /// ```
627     /// let mut s = [1, 2, 3];
628     /// let ptr: *mut u32 = s.as_mut_ptr();
629     /// let first_value = unsafe { &mut *ptr };
630     /// *first_value = 4;
631     /// # assert_eq!(s, [4, 2, 3]);
632     /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
633     /// ```
634     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
635     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
636     #[inline]
637     pub const unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
638         // SAFETY: the caller must guarantee that `self` is be valid for
639         // a mutable reference if it isn't null.
640         if self.is_null() { None } else { unsafe { Some(&mut *self) } }
641     }
642
643     /// Returns `None` if the pointer is null, or else returns a unique reference to
644     /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
645     /// that the value has to be initialized.
646     ///
647     /// For the shared counterpart see [`as_uninit_ref`].
648     ///
649     /// [`as_mut`]: #method.as_mut
650     /// [`as_uninit_ref`]: #method.as_uninit_ref-1
651     ///
652     /// # Safety
653     ///
654     /// When calling this method, you have to ensure that *either* the pointer is null *or*
655     /// all of the following is true:
656     ///
657     /// * The pointer must be properly aligned.
658     ///
659     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
660     ///
661     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
662     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
663     ///   In particular, while this reference exists, the memory the pointer points to must
664     ///   not get accessed (read or written) through any other pointer.
665     ///
666     /// This applies even if the result of this method is unused!
667     ///
668     /// [the module documentation]: crate::ptr#safety
669     #[inline]
670     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
671     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
672     pub const unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
673     where
674         T: Sized,
675     {
676         // SAFETY: the caller must guarantee that `self` meets all the
677         // requirements for a reference.
678         if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
679     }
680
681     /// Returns whether two pointers are guaranteed to be equal.
682     ///
683     /// At runtime this function behaves like `self == other`.
684     /// However, in some contexts (e.g., compile-time evaluation),
685     /// it is not always possible to determine equality of two pointers, so this function may
686     /// spuriously return `false` for pointers that later actually turn out to be equal.
687     /// But when it returns `true`, the pointers are guaranteed to be equal.
688     ///
689     /// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
690     /// comparisons for which both functions return `false`.
691     ///
692     /// [`guaranteed_ne`]: #method.guaranteed_ne
693     ///
694     /// The return value may change depending on the compiler version and unsafe code might not
695     /// rely on the result of this function for soundness. It is suggested to only use this function
696     /// for performance optimizations where spurious `false` return values by this function do not
697     /// affect the outcome, but just the performance.
698     /// The consequences of using this method to make runtime and compile-time code behave
699     /// differently have not been explored. This method should not be used to introduce such
700     /// differences, and it should also not be stabilized before we have a better understanding
701     /// of this issue.
702     #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
703     #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
704     #[inline]
705     pub const fn guaranteed_eq(self, other: *mut T) -> bool
706     where
707         T: Sized,
708     {
709         intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _)
710     }
711
712     /// Returns whether two pointers are guaranteed to be unequal.
713     ///
714     /// At runtime this function behaves like `self != other`.
715     /// However, in some contexts (e.g., compile-time evaluation),
716     /// it is not always possible to determine the inequality of two pointers, so this function may
717     /// spuriously return `false` for pointers that later actually turn out to be unequal.
718     /// But when it returns `true`, the pointers are guaranteed to be unequal.
719     ///
720     /// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
721     /// comparisons for which both functions return `false`.
722     ///
723     /// [`guaranteed_eq`]: #method.guaranteed_eq
724     ///
725     /// The return value may change depending on the compiler version and unsafe code might not
726     /// rely on the result of this function for soundness. It is suggested to only use this function
727     /// for performance optimizations where spurious `false` return values by this function do not
728     /// affect the outcome, but just the performance.
729     /// The consequences of using this method to make runtime and compile-time code behave
730     /// differently have not been explored. This method should not be used to introduce such
731     /// differences, and it should also not be stabilized before we have a better understanding
732     /// of this issue.
733     #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
734     #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
735     #[inline]
736     pub const unsafe fn guaranteed_ne(self, other: *mut T) -> bool
737     where
738         T: Sized,
739     {
740         intrinsics::ptr_guaranteed_ne(self as *const _, other as *const _)
741     }
742
743     /// Calculates the distance between two pointers. The returned value is in
744     /// units of T: the distance in bytes divided by `mem::size_of::<T>()`.
745     ///
746     /// This function is the inverse of [`offset`].
747     ///
748     /// [`offset`]: #method.offset-1
749     ///
750     /// # Safety
751     ///
752     /// If any of the following conditions are violated, the result is Undefined
753     /// Behavior:
754     ///
755     /// * Both the starting and other pointer must be either in bounds or one
756     ///   byte past the end of the same [allocated object].
757     ///
758     /// * Both pointers must be *derived from* a pointer to the same object.
759     ///   (See below for an example.)
760     ///
761     /// * The distance between the pointers, in bytes, must be an exact multiple
762     ///   of the size of `T`.
763     ///
764     /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
765     ///
766     /// * The distance being in bounds cannot rely on "wrapping around" the address space.
767     ///
768     /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
769     /// address space, so two pointers within some value of any Rust type `T` will always satisfy
770     /// the last two conditions. The standard library also generally ensures that allocations
771     /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
772     /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
773     /// always satisfies the last two conditions.
774     ///
775     /// Most platforms fundamentally can't even construct such a large allocation.
776     /// For instance, no known 64-bit platform can ever serve a request
777     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
778     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
779     /// more than `isize::MAX` bytes with things like Physical Address
780     /// Extension. As such, memory acquired directly from allocators or memory
781     /// mapped files *may* be too large to handle with this function.
782     /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
783     /// such large allocations either.)
784     ///
785     /// [`add`]: #method.add
786     /// [allocated object]: crate::ptr#allocated-object
787     ///
788     /// # Panics
789     ///
790     /// This function panics if `T` is a Zero-Sized Type ("ZST").
791     ///
792     /// # Examples
793     ///
794     /// Basic usage:
795     ///
796     /// ```
797     /// let mut a = [0; 5];
798     /// let ptr1: *mut i32 = &mut a[1];
799     /// let ptr2: *mut i32 = &mut a[3];
800     /// unsafe {
801     ///     assert_eq!(ptr2.offset_from(ptr1), 2);
802     ///     assert_eq!(ptr1.offset_from(ptr2), -2);
803     ///     assert_eq!(ptr1.offset(2), ptr2);
804     ///     assert_eq!(ptr2.offset(-2), ptr1);
805     /// }
806     /// ```
807     ///
808     /// *Incorrect* usage:
809     ///
810     /// ```rust,no_run
811     /// let ptr1 = Box::into_raw(Box::new(0u8));
812     /// let ptr2 = Box::into_raw(Box::new(1u8));
813     /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
814     /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
815     /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff);
816     /// assert_eq!(ptr2 as usize, ptr2_other as usize);
817     /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
818     /// // computing their offset is undefined behavior, even though
819     /// // they point to the same address!
820     /// unsafe {
821     ///     let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
822     /// }
823     /// ```
824     #[stable(feature = "ptr_offset_from", since = "1.47.0")]
825     #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "92980")]
826     #[inline(always)]
827     pub const unsafe fn offset_from(self, origin: *const T) -> isize
828     where
829         T: Sized,
830     {
831         // SAFETY: the caller must uphold the safety contract for `offset_from`.
832         unsafe { (self as *const T).offset_from(origin) }
833     }
834
835     /// Calculates the distance between two pointers. The returned value is in
836     /// units of **bytes**.
837     ///
838     /// This is purely a convenience for casting to a `u8` pointer and
839     /// using [offset_from][pointer::offset_from] on it. See that method for
840     /// documentation and safety requirements.
841     ///
842     /// For non-`Sized` pointees this operation considers only the data pointers,
843     /// ignoring the metadata.
844     #[inline(always)]
845     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
846     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
847     pub const unsafe fn byte_offset_from(self, origin: *const T) -> isize {
848         // SAFETY: the caller must uphold the safety contract for `offset_from`.
849         unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
850     }
851
852     /// Calculates the distance between two pointers, *where it's known that
853     /// `self` is equal to or greater than `origin`*. The returned value is in
854     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
855     ///
856     /// This computes the same value that [`offset_from`](#method.offset_from)
857     /// would compute, but with the added precondition that that the offset is
858     /// guaranteed to be non-negative.  This method is equivalent to
859     /// `usize::from(self.offset_from(origin)).unwrap_unchecked()`,
860     /// but it provides slightly more information to the optimizer, which can
861     /// sometimes allow it to optimize slightly better with some backends.
862     ///
863     /// This method can be though of as recovering the `count` that was passed
864     /// to [`add`](#method.add) (or, with the parameters in the other order,
865     /// to [`sub`](#method.sub)).  The following are all equivalent, assuming
866     /// that their safety preconditions are met:
867     /// ```rust
868     /// # #![feature(ptr_sub_ptr)]
869     /// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool {
870     /// ptr.sub_ptr(origin) == count
871     /// # &&
872     /// origin.add(count) == ptr
873     /// # &&
874     /// ptr.sub(count) == origin
875     /// # }
876     /// ```
877     ///
878     /// # Safety
879     ///
880     /// - The distance between the pointers must be non-negative (`self >= origin`)
881     ///
882     /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
883     ///   apply to this method as well; see it for the full details.
884     ///
885     /// Importantly, despite the return type of this method being able to represent
886     /// a larger offset, it's still *not permitted* to pass pointers which differ
887     /// by more than `isize::MAX` *bytes*.  As such, the result of this method will
888     /// always be less than or equal to `isize::MAX as usize`.
889     ///
890     /// # Panics
891     ///
892     /// This function panics if `T` is a Zero-Sized Type ("ZST").
893     ///
894     /// # Examples
895     ///
896     /// ```
897     /// #![feature(ptr_sub_ptr)]
898     ///
899     /// let mut a = [0; 5];
900     /// let p: *mut i32 = a.as_mut_ptr();
901     /// unsafe {
902     ///     let ptr1: *mut i32 = p.add(1);
903     ///     let ptr2: *mut i32 = p.add(3);
904     ///
905     ///     assert_eq!(ptr2.sub_ptr(ptr1), 2);
906     ///     assert_eq!(ptr1.add(2), ptr2);
907     ///     assert_eq!(ptr2.sub(2), ptr1);
908     ///     assert_eq!(ptr2.sub_ptr(ptr2), 0);
909     /// }
910     ///
911     /// // This would be incorrect, as the pointers are not correctly ordered:
912     /// // ptr1.offset_from(ptr2)
913     #[unstable(feature = "ptr_sub_ptr", issue = "95892")]
914     #[rustc_const_unstable(feature = "const_ptr_sub_ptr", issue = "95892")]
915     #[inline]
916     pub const unsafe fn sub_ptr(self, origin: *const T) -> usize
917     where
918         T: Sized,
919     {
920         // SAFETY: the caller must uphold the safety contract for `sub_ptr`.
921         unsafe { (self as *const T).sub_ptr(origin) }
922     }
923
924     /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
925     ///
926     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
927     /// offset of `3 * size_of::<T>()` bytes.
928     ///
929     /// # Safety
930     ///
931     /// If any of the following conditions are violated, the result is Undefined
932     /// Behavior:
933     ///
934     /// * Both the starting and resulting pointer must be either in bounds or one
935     ///   byte past the end of the same [allocated object].
936     ///
937     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
938     ///
939     /// * The offset being in bounds cannot rely on "wrapping around" the address
940     ///   space. That is, the infinite-precision sum must fit in a `usize`.
941     ///
942     /// The compiler and standard library generally tries to ensure allocations
943     /// never reach a size where an offset is a concern. For instance, `Vec`
944     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
945     /// `vec.as_ptr().add(vec.len())` is always safe.
946     ///
947     /// Most platforms fundamentally can't even construct such an allocation.
948     /// For instance, no known 64-bit platform can ever serve a request
949     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
950     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
951     /// more than `isize::MAX` bytes with things like Physical Address
952     /// Extension. As such, memory acquired directly from allocators or memory
953     /// mapped files *may* be too large to handle with this function.
954     ///
955     /// Consider using [`wrapping_add`] instead if these constraints are
956     /// difficult to satisfy. The only advantage of this method is that it
957     /// enables more aggressive compiler optimizations.
958     ///
959     /// [`wrapping_add`]: #method.wrapping_add
960     /// [allocated object]: crate::ptr#allocated-object
961     ///
962     /// # Examples
963     ///
964     /// Basic usage:
965     ///
966     /// ```
967     /// let s: &str = "123";
968     /// let ptr: *const u8 = s.as_ptr();
969     ///
970     /// unsafe {
971     ///     println!("{}", *ptr.add(1) as char);
972     ///     println!("{}", *ptr.add(2) as char);
973     /// }
974     /// ```
975     #[stable(feature = "pointer_methods", since = "1.26.0")]
976     #[must_use = "returns a new pointer rather than modifying its argument"]
977     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
978     #[inline(always)]
979     pub const unsafe fn add(self, count: usize) -> Self
980     where
981         T: Sized,
982     {
983         // SAFETY: the caller must uphold the safety contract for `offset`.
984         unsafe { self.offset(count as isize) }
985     }
986
987     /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
988     ///
989     /// `count` is in units of bytes.
990     ///
991     /// This is purely a convenience for casting to a `u8` pointer and
992     /// using [add][pointer::add] on it. See that method for documentation
993     /// and safety requirements.
994     ///
995     /// For non-`Sized` pointees this operation changes only the data pointer,
996     /// leaving the metadata untouched.
997     #[must_use]
998     #[inline(always)]
999     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1000     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1001     pub const unsafe fn byte_add(self, count: usize) -> Self {
1002         // SAFETY: the caller must uphold the safety contract for `add`.
1003         let this = unsafe { self.cast::<u8>().add(count).cast::<()>() };
1004         from_raw_parts_mut::<T>(this, metadata(self))
1005     }
1006
1007     /// Calculates the offset from a pointer (convenience for
1008     /// `.offset((count as isize).wrapping_neg())`).
1009     ///
1010     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1011     /// offset of `3 * size_of::<T>()` bytes.
1012     ///
1013     /// # Safety
1014     ///
1015     /// If any of the following conditions are violated, the result is Undefined
1016     /// Behavior:
1017     ///
1018     /// * Both the starting and resulting pointer must be either in bounds or one
1019     ///   byte past the end of the same [allocated object].
1020     ///
1021     /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1022     ///
1023     /// * The offset being in bounds cannot rely on "wrapping around" the address
1024     ///   space. That is, the infinite-precision sum must fit in a usize.
1025     ///
1026     /// The compiler and standard library generally tries to ensure allocations
1027     /// never reach a size where an offset is a concern. For instance, `Vec`
1028     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1029     /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1030     ///
1031     /// Most platforms fundamentally can't even construct such an allocation.
1032     /// For instance, no known 64-bit platform can ever serve a request
1033     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1034     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1035     /// more than `isize::MAX` bytes with things like Physical Address
1036     /// Extension. As such, memory acquired directly from allocators or memory
1037     /// mapped files *may* be too large to handle with this function.
1038     ///
1039     /// Consider using [`wrapping_sub`] instead if these constraints are
1040     /// difficult to satisfy. The only advantage of this method is that it
1041     /// enables more aggressive compiler optimizations.
1042     ///
1043     /// [`wrapping_sub`]: #method.wrapping_sub
1044     /// [allocated object]: crate::ptr#allocated-object
1045     ///
1046     /// # Examples
1047     ///
1048     /// Basic usage:
1049     ///
1050     /// ```
1051     /// let s: &str = "123";
1052     ///
1053     /// unsafe {
1054     ///     let end: *const u8 = s.as_ptr().add(3);
1055     ///     println!("{}", *end.sub(1) as char);
1056     ///     println!("{}", *end.sub(2) as char);
1057     /// }
1058     /// ```
1059     #[stable(feature = "pointer_methods", since = "1.26.0")]
1060     #[must_use = "returns a new pointer rather than modifying its argument"]
1061     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1062     #[inline]
1063     pub const unsafe fn sub(self, count: usize) -> Self
1064     where
1065         T: Sized,
1066     {
1067         // SAFETY: the caller must uphold the safety contract for `offset`.
1068         unsafe { self.offset((count as isize).wrapping_neg()) }
1069     }
1070
1071     /// Calculates the offset from a pointer in bytes (convenience for
1072     /// `.byte_offset((count as isize).wrapping_neg())`).
1073     ///
1074     /// `count` is in units of bytes.
1075     ///
1076     /// This is purely a convenience for casting to a `u8` pointer and
1077     /// using [sub][pointer::sub] on it. See that method for documentation
1078     /// and safety requirements.
1079     ///
1080     /// For non-`Sized` pointees this operation changes only the data pointer,
1081     /// leaving the metadata untouched.
1082     #[must_use]
1083     #[inline(always)]
1084     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1085     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1086     pub const unsafe fn byte_sub(self, count: usize) -> Self {
1087         // SAFETY: the caller must uphold the safety contract for `sub`.
1088         let this = unsafe { self.cast::<u8>().sub(count).cast::<()>() };
1089         from_raw_parts_mut::<T>(this, metadata(self))
1090     }
1091
1092     /// Calculates the offset from a pointer using wrapping arithmetic.
1093     /// (convenience for `.wrapping_offset(count as isize)`)
1094     ///
1095     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1096     /// offset of `3 * size_of::<T>()` bytes.
1097     ///
1098     /// # Safety
1099     ///
1100     /// This operation itself is always safe, but using the resulting pointer is not.
1101     ///
1102     /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1103     /// be used to read or write other allocated objects.
1104     ///
1105     /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1106     /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1107     /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1108     /// `x` and `y` point into the same allocated object.
1109     ///
1110     /// Compared to [`add`], this method basically delays the requirement of staying within the
1111     /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
1112     /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1113     /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1114     /// can be optimized better and is thus preferable in performance-sensitive code.
1115     ///
1116     /// The delayed check only considers the value of the pointer that was dereferenced, not the
1117     /// intermediate values used during the computation of the final result. For example,
1118     /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1119     /// allocated object and then re-entering it later is permitted.
1120     ///
1121     /// [`add`]: #method.add
1122     /// [allocated object]: crate::ptr#allocated-object
1123     ///
1124     /// # Examples
1125     ///
1126     /// Basic usage:
1127     ///
1128     /// ```
1129     /// // Iterate using a raw pointer in increments of two elements
1130     /// let data = [1u8, 2, 3, 4, 5];
1131     /// let mut ptr: *const u8 = data.as_ptr();
1132     /// let step = 2;
1133     /// let end_rounded_up = ptr.wrapping_add(6);
1134     ///
1135     /// // This loop prints "1, 3, 5, "
1136     /// while ptr != end_rounded_up {
1137     ///     unsafe {
1138     ///         print!("{}, ", *ptr);
1139     ///     }
1140     ///     ptr = ptr.wrapping_add(step);
1141     /// }
1142     /// ```
1143     #[stable(feature = "pointer_methods", since = "1.26.0")]
1144     #[must_use = "returns a new pointer rather than modifying its argument"]
1145     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1146     #[inline(always)]
1147     pub const fn wrapping_add(self, count: usize) -> Self
1148     where
1149         T: Sized,
1150     {
1151         self.wrapping_offset(count as isize)
1152     }
1153
1154     /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1155     /// (convenience for `.wrapping_byte_offset(count as isize)`)
1156     ///
1157     /// `count` is in units of bytes.
1158     ///
1159     /// This is purely a convenience for casting to a `u8` pointer and
1160     /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1161     ///
1162     /// For non-`Sized` pointees this operation changes only the data pointer,
1163     /// leaving the metadata untouched.
1164     #[must_use]
1165     #[inline(always)]
1166     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1167     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1168     pub const fn wrapping_byte_add(self, count: usize) -> Self {
1169         from_raw_parts_mut::<T>(self.cast::<u8>().wrapping_add(count).cast::<()>(), metadata(self))
1170     }
1171
1172     /// Calculates the offset from a pointer using wrapping arithmetic.
1173     /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1174     ///
1175     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1176     /// offset of `3 * size_of::<T>()` bytes.
1177     ///
1178     /// # Safety
1179     ///
1180     /// This operation itself is always safe, but using the resulting pointer is not.
1181     ///
1182     /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1183     /// be used to read or write other allocated objects.
1184     ///
1185     /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1186     /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1187     /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1188     /// `x` and `y` point into the same allocated object.
1189     ///
1190     /// Compared to [`sub`], this method basically delays the requirement of staying within the
1191     /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
1192     /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1193     /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1194     /// can be optimized better and is thus preferable in performance-sensitive code.
1195     ///
1196     /// The delayed check only considers the value of the pointer that was dereferenced, not the
1197     /// intermediate values used during the computation of the final result. For example,
1198     /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1199     /// allocated object and then re-entering it later is permitted.
1200     ///
1201     /// [`sub`]: #method.sub
1202     /// [allocated object]: crate::ptr#allocated-object
1203     ///
1204     /// # Examples
1205     ///
1206     /// Basic usage:
1207     ///
1208     /// ```
1209     /// // Iterate using a raw pointer in increments of two elements (backwards)
1210     /// let data = [1u8, 2, 3, 4, 5];
1211     /// let mut ptr: *const u8 = data.as_ptr();
1212     /// let start_rounded_down = ptr.wrapping_sub(2);
1213     /// ptr = ptr.wrapping_add(4);
1214     /// let step = 2;
1215     /// // This loop prints "5, 3, 1, "
1216     /// while ptr != start_rounded_down {
1217     ///     unsafe {
1218     ///         print!("{}, ", *ptr);
1219     ///     }
1220     ///     ptr = ptr.wrapping_sub(step);
1221     /// }
1222     /// ```
1223     #[stable(feature = "pointer_methods", since = "1.26.0")]
1224     #[must_use = "returns a new pointer rather than modifying its argument"]
1225     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1226     #[inline]
1227     pub const fn wrapping_sub(self, count: usize) -> Self
1228     where
1229         T: Sized,
1230     {
1231         self.wrapping_offset((count as isize).wrapping_neg())
1232     }
1233
1234     /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1235     /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1236     ///
1237     /// `count` is in units of bytes.
1238     ///
1239     /// This is purely a convenience for casting to a `u8` pointer and
1240     /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1241     ///
1242     /// For non-`Sized` pointees this operation changes only the data pointer,
1243     /// leaving the metadata untouched.
1244     #[must_use]
1245     #[inline(always)]
1246     #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1247     #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1248     pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1249         from_raw_parts_mut::<T>(self.cast::<u8>().wrapping_sub(count).cast::<()>(), metadata(self))
1250     }
1251
1252     /// Reads the value from `self` without moving it. This leaves the
1253     /// memory in `self` unchanged.
1254     ///
1255     /// See [`ptr::read`] for safety concerns and examples.
1256     ///
1257     /// [`ptr::read`]: crate::ptr::read()
1258     #[stable(feature = "pointer_methods", since = "1.26.0")]
1259     #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1260     #[inline(always)]
1261     pub const unsafe fn read(self) -> T
1262     where
1263         T: Sized,
1264     {
1265         // SAFETY: the caller must uphold the safety contract for ``.
1266         unsafe { read(self) }
1267     }
1268
1269     /// Performs a volatile read of the value from `self` without moving it. This
1270     /// leaves the memory in `self` unchanged.
1271     ///
1272     /// Volatile operations are intended to act on I/O memory, and are guaranteed
1273     /// to not be elided or reordered by the compiler across other volatile
1274     /// operations.
1275     ///
1276     /// See [`ptr::read_volatile`] for safety concerns and examples.
1277     ///
1278     /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1279     #[stable(feature = "pointer_methods", since = "1.26.0")]
1280     #[inline(always)]
1281     pub unsafe fn read_volatile(self) -> T
1282     where
1283         T: Sized,
1284     {
1285         // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1286         unsafe { read_volatile(self) }
1287     }
1288
1289     /// Reads the value from `self` without moving it. This leaves the
1290     /// memory in `self` unchanged.
1291     ///
1292     /// Unlike `read`, the pointer may be unaligned.
1293     ///
1294     /// See [`ptr::read_unaligned`] for safety concerns and examples.
1295     ///
1296     /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1297     #[stable(feature = "pointer_methods", since = "1.26.0")]
1298     #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1299     #[inline(always)]
1300     pub const unsafe fn read_unaligned(self) -> T
1301     where
1302         T: Sized,
1303     {
1304         // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1305         unsafe { read_unaligned(self) }
1306     }
1307
1308     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1309     /// and destination may overlap.
1310     ///
1311     /// NOTE: this has the *same* argument order as [`ptr::copy`].
1312     ///
1313     /// See [`ptr::copy`] for safety concerns and examples.
1314     ///
1315     /// [`ptr::copy`]: crate::ptr::copy()
1316     #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1317     #[stable(feature = "pointer_methods", since = "1.26.0")]
1318     #[inline(always)]
1319     pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1320     where
1321         T: Sized,
1322     {
1323         // SAFETY: the caller must uphold the safety contract for `copy`.
1324         unsafe { copy(self, dest, count) }
1325     }
1326
1327     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1328     /// and destination may *not* overlap.
1329     ///
1330     /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1331     ///
1332     /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1333     ///
1334     /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1335     #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1336     #[stable(feature = "pointer_methods", since = "1.26.0")]
1337     #[inline(always)]
1338     pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1339     where
1340         T: Sized,
1341     {
1342         // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1343         unsafe { copy_nonoverlapping(self, dest, count) }
1344     }
1345
1346     /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1347     /// and destination may overlap.
1348     ///
1349     /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1350     ///
1351     /// See [`ptr::copy`] for safety concerns and examples.
1352     ///
1353     /// [`ptr::copy`]: crate::ptr::copy()
1354     #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1355     #[stable(feature = "pointer_methods", since = "1.26.0")]
1356     #[inline(always)]
1357     pub const unsafe fn copy_from(self, src: *const T, count: usize)
1358     where
1359         T: Sized,
1360     {
1361         // SAFETY: the caller must uphold the safety contract for `copy`.
1362         unsafe { copy(src, self, count) }
1363     }
1364
1365     /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1366     /// and destination may *not* overlap.
1367     ///
1368     /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1369     ///
1370     /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1371     ///
1372     /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1373     #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1374     #[stable(feature = "pointer_methods", since = "1.26.0")]
1375     #[inline(always)]
1376     pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1377     where
1378         T: Sized,
1379     {
1380         // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1381         unsafe { copy_nonoverlapping(src, self, count) }
1382     }
1383
1384     /// Executes the destructor (if any) of the pointed-to value.
1385     ///
1386     /// See [`ptr::drop_in_place`] for safety concerns and examples.
1387     ///
1388     /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1389     #[stable(feature = "pointer_methods", since = "1.26.0")]
1390     #[inline(always)]
1391     pub unsafe fn drop_in_place(self) {
1392         // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1393         unsafe { drop_in_place(self) }
1394     }
1395
1396     /// Overwrites a memory location with the given value without reading or
1397     /// dropping the old value.
1398     ///
1399     /// See [`ptr::write`] for safety concerns and examples.
1400     ///
1401     /// [`ptr::write`]: crate::ptr::write()
1402     #[stable(feature = "pointer_methods", since = "1.26.0")]
1403     #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1404     #[inline(always)]
1405     pub const unsafe fn write(self, val: T)
1406     where
1407         T: Sized,
1408     {
1409         // SAFETY: the caller must uphold the safety contract for `write`.
1410         unsafe { write(self, val) }
1411     }
1412
1413     /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1414     /// bytes of memory starting at `self` to `val`.
1415     ///
1416     /// See [`ptr::write_bytes`] for safety concerns and examples.
1417     ///
1418     /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1419     #[doc(alias = "memset")]
1420     #[stable(feature = "pointer_methods", since = "1.26.0")]
1421     #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1422     #[inline(always)]
1423     pub const unsafe fn write_bytes(self, val: u8, count: usize)
1424     where
1425         T: Sized,
1426     {
1427         // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1428         unsafe { write_bytes(self, val, count) }
1429     }
1430
1431     /// Performs a volatile write of a memory location with the given value without
1432     /// reading or dropping the old value.
1433     ///
1434     /// Volatile operations are intended to act on I/O memory, and are guaranteed
1435     /// to not be elided or reordered by the compiler across other volatile
1436     /// operations.
1437     ///
1438     /// See [`ptr::write_volatile`] for safety concerns and examples.
1439     ///
1440     /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1441     #[stable(feature = "pointer_methods", since = "1.26.0")]
1442     #[inline(always)]
1443     pub unsafe fn write_volatile(self, val: T)
1444     where
1445         T: Sized,
1446     {
1447         // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1448         unsafe { write_volatile(self, val) }
1449     }
1450
1451     /// Overwrites a memory location with the given value without reading or
1452     /// dropping the old value.
1453     ///
1454     /// Unlike `write`, the pointer may be unaligned.
1455     ///
1456     /// See [`ptr::write_unaligned`] for safety concerns and examples.
1457     ///
1458     /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1459     #[stable(feature = "pointer_methods", since = "1.26.0")]
1460     #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1461     #[inline(always)]
1462     pub const unsafe fn write_unaligned(self, val: T)
1463     where
1464         T: Sized,
1465     {
1466         // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1467         unsafe { write_unaligned(self, val) }
1468     }
1469
1470     /// Replaces the value at `self` with `src`, returning the old
1471     /// value, without dropping either.
1472     ///
1473     /// See [`ptr::replace`] for safety concerns and examples.
1474     ///
1475     /// [`ptr::replace`]: crate::ptr::replace()
1476     #[stable(feature = "pointer_methods", since = "1.26.0")]
1477     #[inline(always)]
1478     pub unsafe fn replace(self, src: T) -> T
1479     where
1480         T: Sized,
1481     {
1482         // SAFETY: the caller must uphold the safety contract for `replace`.
1483         unsafe { replace(self, src) }
1484     }
1485
1486     /// Swaps the values at two mutable locations of the same type, without
1487     /// deinitializing either. They may overlap, unlike `mem::swap` which is
1488     /// otherwise equivalent.
1489     ///
1490     /// See [`ptr::swap`] for safety concerns and examples.
1491     ///
1492     /// [`ptr::swap`]: crate::ptr::swap()
1493     #[stable(feature = "pointer_methods", since = "1.26.0")]
1494     #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
1495     #[inline(always)]
1496     pub const unsafe fn swap(self, with: *mut T)
1497     where
1498         T: Sized,
1499     {
1500         // SAFETY: the caller must uphold the safety contract for `swap`.
1501         unsafe { swap(self, with) }
1502     }
1503
1504     /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1505     /// `align`.
1506     ///
1507     /// If it is not possible to align the pointer, the implementation returns
1508     /// `usize::MAX`. It is permissible for the implementation to *always*
1509     /// return `usize::MAX`. Only your algorithm's performance can depend
1510     /// on getting a usable offset here, not its correctness.
1511     ///
1512     /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1513     /// used with the `wrapping_add` method.
1514     ///
1515     /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1516     /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1517     /// the returned offset is correct in all terms other than alignment.
1518     ///
1519     /// # Panics
1520     ///
1521     /// The function panics if `align` is not a power-of-two.
1522     ///
1523     /// # Examples
1524     ///
1525     /// Accessing adjacent `u8` as `u16`
1526     ///
1527     /// ```
1528     /// # fn foo(n: usize) {
1529     /// # use std::mem::align_of;
1530     /// # unsafe {
1531     /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1532     /// let ptr = x.as_ptr().add(n) as *const u8;
1533     /// let offset = ptr.align_offset(align_of::<u16>());
1534     /// if offset < x.len() - n - 1 {
1535     ///     let u16_ptr = ptr.add(offset) as *const u16;
1536     ///     assert_ne!(*u16_ptr, 500);
1537     /// } else {
1538     ///     // while the pointer can be aligned via `offset`, it would point
1539     ///     // outside the allocation
1540     /// }
1541     /// # } }
1542     /// ```
1543     #[stable(feature = "align_offset", since = "1.36.0")]
1544     #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1545     pub const fn align_offset(self, align: usize) -> usize
1546     where
1547         T: Sized,
1548     {
1549         if !align.is_power_of_two() {
1550             panic!("align_offset: align is not a power-of-two");
1551         }
1552
1553         fn rt_impl<T>(p: *mut T, align: usize) -> usize {
1554             // SAFETY: `align` has been checked to be a power of 2 above
1555             unsafe { align_offset(p, align) }
1556         }
1557
1558         const fn ctfe_impl<T>(_: *mut T, _: usize) -> usize {
1559             usize::MAX
1560         }
1561
1562         // SAFETY:
1563         // It is permissible for `align_offset` to always return `usize::MAX`,
1564         // algorithm correctness can not depend on `align_offset` returning non-max values.
1565         //
1566         // As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
1567         unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
1568     }
1569
1570     /// Returns whether the pointer is properly aligned for `T`.
1571     #[must_use]
1572     #[inline]
1573     #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1574     pub fn is_aligned(self) -> bool
1575     where
1576         T: Sized,
1577     {
1578         self.is_aligned_to(core::mem::align_of::<T>())
1579     }
1580
1581     /// Returns whether the pointer is aligned to `align`.
1582     ///
1583     /// For non-`Sized` pointees this operation considers only the data pointer,
1584     /// ignoring the metadata.
1585     ///
1586     /// # Panics
1587     ///
1588     /// The function panics if `align` is not a power-of-two (this includes 0).
1589     #[must_use]
1590     #[inline]
1591     #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1592     pub fn is_aligned_to(self, align: usize) -> bool {
1593         if !align.is_power_of_two() {
1594             panic!("is_aligned_to: align is not a power-of-two");
1595         }
1596
1597         // SAFETY: `is_power_of_two()` will return `false` for zero.
1598         unsafe { core::intrinsics::assume(align != 0) };
1599
1600         // Cast is needed for `T: !Sized`
1601         self.cast::<u8>().addr() % align == 0
1602     }
1603 }
1604
1605 impl<T> *mut [T] {
1606     /// Returns the length of a raw slice.
1607     ///
1608     /// The returned value is the number of **elements**, not the number of bytes.
1609     ///
1610     /// This function is safe, even when the raw slice cannot be cast to a slice
1611     /// reference because the pointer is null or unaligned.
1612     ///
1613     /// # Examples
1614     ///
1615     /// ```rust
1616     /// #![feature(slice_ptr_len)]
1617     /// use std::ptr;
1618     ///
1619     /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1620     /// assert_eq!(slice.len(), 3);
1621     /// ```
1622     #[inline(always)]
1623     #[unstable(feature = "slice_ptr_len", issue = "71146")]
1624     #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1625     pub const fn len(self) -> usize {
1626         metadata(self)
1627     }
1628
1629     /// Returns `true` if the raw slice has a length of 0.
1630     ///
1631     /// # Examples
1632     ///
1633     /// ```
1634     /// #![feature(slice_ptr_len)]
1635     ///
1636     /// let mut a = [1, 2, 3];
1637     /// let ptr = &mut a as *mut [_];
1638     /// assert!(!ptr.is_empty());
1639     /// ```
1640     #[inline(always)]
1641     #[unstable(feature = "slice_ptr_len", issue = "71146")]
1642     #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1643     pub const fn is_empty(self) -> bool {
1644         self.len() == 0
1645     }
1646
1647     /// Divides one mutable raw slice into two at an index.
1648     ///
1649     /// The first will contain all indices from `[0, mid)` (excluding
1650     /// the index `mid` itself) and the second will contain all
1651     /// indices from `[mid, len)` (excluding the index `len` itself).
1652     ///
1653     /// # Panics
1654     ///
1655     /// Panics if `mid > len`.
1656     ///
1657     /// # Safety
1658     ///
1659     /// `mid` must be [in-bounds] of the underlying [allocated object].
1660     /// Which means `self` must be dereferenceable and span a single allocation
1661     /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1662     /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1663     ///
1664     /// Since `len` being in-bounds it is not a safety invariant of `*mut [T]` the
1665     /// safety requirements of this method are the same as for [`split_at_mut_unchecked`].
1666     /// The explicit bounds check is only as useful as `len` is correct.
1667     ///
1668     /// [`split_at_mut_unchecked`]: #method.split_at_mut_unchecked
1669     /// [in-bounds]: #method.add
1670     /// [allocated object]: crate::ptr#allocated-object
1671     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1672     ///
1673     /// # Examples
1674     ///
1675     /// ```
1676     /// #![feature(raw_slice_split)]
1677     /// #![feature(slice_ptr_get)]
1678     ///
1679     /// let mut v = [1, 0, 3, 0, 5, 6];
1680     /// let ptr = &mut v as *mut [_];
1681     /// unsafe {
1682     ///     let (left, right) = ptr.split_at_mut(2);
1683     ///     assert_eq!(&*left, [1, 0]);
1684     ///     assert_eq!(&*right, [3, 0, 5, 6]);
1685     /// }
1686     /// ```
1687     #[inline(always)]
1688     #[track_caller]
1689     #[unstable(feature = "raw_slice_split", issue = "95595")]
1690     pub unsafe fn split_at_mut(self, mid: usize) -> (*mut [T], *mut [T]) {
1691         assert!(mid <= self.len());
1692         // SAFETY: The assert above is only a safety-net as long as `self.len()` is correct
1693         // The actual safety requirements of this function are the same as for `split_at_mut_unchecked`
1694         unsafe { self.split_at_mut_unchecked(mid) }
1695     }
1696
1697     /// Divides one mutable raw slice into two at an index, without doing bounds checking.
1698     ///
1699     /// The first will contain all indices from `[0, mid)` (excluding
1700     /// the index `mid` itself) and the second will contain all
1701     /// indices from `[mid, len)` (excluding the index `len` itself).
1702     ///
1703     /// # Safety
1704     ///
1705     /// `mid` must be [in-bounds] of the underlying [allocated object].
1706     /// Which means `self` must be dereferenceable and span a single allocation
1707     /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1708     /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1709     ///
1710     /// [in-bounds]: #method.add
1711     /// [out-of-bounds index]: #method.add
1712     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1713     ///
1714     /// # Examples
1715     ///
1716     /// ```
1717     /// #![feature(raw_slice_split)]
1718     ///
1719     /// let mut v = [1, 0, 3, 0, 5, 6];
1720     /// // scoped to restrict the lifetime of the borrows
1721     /// unsafe {
1722     ///     let ptr = &mut v as *mut [_];
1723     ///     let (left, right) = ptr.split_at_mut_unchecked(2);
1724     ///     assert_eq!(&*left, [1, 0]);
1725     ///     assert_eq!(&*right, [3, 0, 5, 6]);
1726     ///     (&mut *left)[1] = 2;
1727     ///     (&mut *right)[1] = 4;
1728     /// }
1729     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1730     /// ```
1731     #[inline(always)]
1732     #[unstable(feature = "raw_slice_split", issue = "95595")]
1733     pub unsafe fn split_at_mut_unchecked(self, mid: usize) -> (*mut [T], *mut [T]) {
1734         let len = self.len();
1735         let ptr = self.as_mut_ptr();
1736
1737         // SAFETY: Caller must pass a valid pointer and an index that is in-bounds.
1738         let tail = unsafe { ptr.add(mid) };
1739         (
1740             crate::ptr::slice_from_raw_parts_mut(ptr, mid),
1741             crate::ptr::slice_from_raw_parts_mut(tail, len - mid),
1742         )
1743     }
1744
1745     /// Returns a raw pointer to the slice's buffer.
1746     ///
1747     /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
1748     ///
1749     /// # Examples
1750     ///
1751     /// ```rust
1752     /// #![feature(slice_ptr_get)]
1753     /// use std::ptr;
1754     ///
1755     /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1756     /// assert_eq!(slice.as_mut_ptr(), ptr::null_mut());
1757     /// ```
1758     #[inline(always)]
1759     #[unstable(feature = "slice_ptr_get", issue = "74265")]
1760     #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
1761     pub const fn as_mut_ptr(self) -> *mut T {
1762         self as *mut T
1763     }
1764
1765     /// Returns a raw pointer to an element or subslice, without doing bounds
1766     /// checking.
1767     ///
1768     /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
1769     /// is *[undefined behavior]* even if the resulting pointer is not used.
1770     ///
1771     /// [out-of-bounds index]: #method.add
1772     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1773     ///
1774     /// # Examples
1775     ///
1776     /// ```
1777     /// #![feature(slice_ptr_get)]
1778     ///
1779     /// let x = &mut [1, 2, 4] as *mut [i32];
1780     ///
1781     /// unsafe {
1782     ///     assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
1783     /// }
1784     /// ```
1785     #[unstable(feature = "slice_ptr_get", issue = "74265")]
1786     #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
1787     #[inline(always)]
1788     pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
1789     where
1790         I: ~const SliceIndex<[T]>,
1791     {
1792         // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1793         unsafe { index.get_unchecked_mut(self) }
1794     }
1795
1796     /// Returns `None` if the pointer is null, or else returns a shared slice to
1797     /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1798     /// that the value has to be initialized.
1799     ///
1800     /// For the mutable counterpart see [`as_uninit_slice_mut`].
1801     ///
1802     /// [`as_ref`]: #method.as_ref-1
1803     /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
1804     ///
1805     /// # Safety
1806     ///
1807     /// When calling this method, you have to ensure that *either* the pointer is null *or*
1808     /// all of the following is true:
1809     ///
1810     /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1811     ///   and it must be properly aligned. This means in particular:
1812     ///
1813     ///     * The entire memory range of this slice must be contained within a single [allocated object]!
1814     ///       Slices can never span across multiple allocated objects.
1815     ///
1816     ///     * The pointer must be aligned even for zero-length slices. One
1817     ///       reason for this is that enum layout optimizations may rely on references
1818     ///       (including slices of any length) being aligned and non-null to distinguish
1819     ///       them from other data. You can obtain a pointer that is usable as `data`
1820     ///       for zero-length slices using [`NonNull::dangling()`].
1821     ///
1822     /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1823     ///   See the safety documentation of [`pointer::offset`].
1824     ///
1825     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1826     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1827     ///   In particular, while this reference exists, the memory the pointer points to must
1828     ///   not get mutated (except inside `UnsafeCell`).
1829     ///
1830     /// This applies even if the result of this method is unused!
1831     ///
1832     /// See also [`slice::from_raw_parts`][].
1833     ///
1834     /// [valid]: crate::ptr#safety
1835     /// [allocated object]: crate::ptr#allocated-object
1836     #[inline]
1837     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1838     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1839     pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1840         if self.is_null() {
1841             None
1842         } else {
1843             // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1844             Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1845         }
1846     }
1847
1848     /// Returns `None` if the pointer is null, or else returns a unique slice to
1849     /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
1850     /// that the value has to be initialized.
1851     ///
1852     /// For the shared counterpart see [`as_uninit_slice`].
1853     ///
1854     /// [`as_mut`]: #method.as_mut
1855     /// [`as_uninit_slice`]: #method.as_uninit_slice-1
1856     ///
1857     /// # Safety
1858     ///
1859     /// When calling this method, you have to ensure that *either* the pointer is null *or*
1860     /// all of the following is true:
1861     ///
1862     /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
1863     ///   many bytes, and it must be properly aligned. This means in particular:
1864     ///
1865     ///     * The entire memory range of this slice must be contained within a single [allocated object]!
1866     ///       Slices can never span across multiple allocated objects.
1867     ///
1868     ///     * The pointer must be aligned even for zero-length slices. One
1869     ///       reason for this is that enum layout optimizations may rely on references
1870     ///       (including slices of any length) being aligned and non-null to distinguish
1871     ///       them from other data. You can obtain a pointer that is usable as `data`
1872     ///       for zero-length slices using [`NonNull::dangling()`].
1873     ///
1874     /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1875     ///   See the safety documentation of [`pointer::offset`].
1876     ///
1877     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1878     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1879     ///   In particular, while this reference exists, the memory the pointer points to must
1880     ///   not get accessed (read or written) through any other pointer.
1881     ///
1882     /// This applies even if the result of this method is unused!
1883     ///
1884     /// See also [`slice::from_raw_parts_mut`][].
1885     ///
1886     /// [valid]: crate::ptr#safety
1887     /// [allocated object]: crate::ptr#allocated-object
1888     #[inline]
1889     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1890     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1891     pub const unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
1892         if self.is_null() {
1893             None
1894         } else {
1895             // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
1896             Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
1897         }
1898     }
1899 }
1900
1901 // Equality for pointers
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 impl<T: ?Sized> PartialEq for *mut T {
1904     #[inline(always)]
1905     fn eq(&self, other: &*mut T) -> bool {
1906         *self == *other
1907     }
1908 }
1909
1910 #[stable(feature = "rust1", since = "1.0.0")]
1911 impl<T: ?Sized> Eq for *mut T {}
1912
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 impl<T: ?Sized> Ord for *mut T {
1915     #[inline]
1916     fn cmp(&self, other: &*mut T) -> Ordering {
1917         if self < other {
1918             Less
1919         } else if self == other {
1920             Equal
1921         } else {
1922             Greater
1923         }
1924     }
1925 }
1926
1927 #[stable(feature = "rust1", since = "1.0.0")]
1928 impl<T: ?Sized> PartialOrd for *mut T {
1929     #[inline(always)]
1930     fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
1931         Some(self.cmp(other))
1932     }
1933
1934     #[inline(always)]
1935     fn lt(&self, other: &*mut T) -> bool {
1936         *self < *other
1937     }
1938
1939     #[inline(always)]
1940     fn le(&self, other: &*mut T) -> bool {
1941         *self <= *other
1942     }
1943
1944     #[inline(always)]
1945     fn gt(&self, other: &*mut T) -> bool {
1946         *self > *other
1947     }
1948
1949     #[inline(always)]
1950     fn ge(&self, other: &*mut T) -> bool {
1951         *self >= *other
1952     }
1953 }