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