]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/mut_ptr.rs
Rollup merge of #94839 - TaKO8Ki:suggest-using-double-colon-for-struct-field-type...
[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 #[lang = "mut_ptr"]
7 impl<T: ?Sized> *mut T {
8     /// Returns `true` if the pointer is null.
9     ///
10     /// Note that unsized types have many possible null pointers, as only the
11     /// raw data pointer is considered, not their length, vtable, etc.
12     /// Therefore, two pointers that are null may still not compare equal to
13     /// each other.
14     ///
15     /// ## Behavior during const evaluation
16     ///
17     /// When this function is used during const evaluation, it may return `false` for pointers
18     /// that turn out to be null at runtime. Specifically, when a pointer to some memory
19     /// is offset beyond its bounds in such a way that the resulting pointer is null,
20     /// the function will still return `false`. There is no way for CTFE to know
21     /// the absolute position of that memory, so we cannot tell if the pointer is
22     /// null or not.
23     ///
24     /// # Examples
25     ///
26     /// Basic usage:
27     ///
28     /// ```
29     /// let mut s = [1, 2, 3];
30     /// let ptr: *mut u32 = s.as_mut_ptr();
31     /// assert!(!ptr.is_null());
32     /// ```
33     #[stable(feature = "rust1", since = "1.0.0")]
34     #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")]
35     #[inline]
36     pub const fn is_null(self) -> bool {
37         // Compare via a cast to a thin pointer, so fat pointers are only
38         // considering their "data" part for null-ness.
39         (self as *mut u8).guaranteed_eq(null_mut())
40     }
41
42     /// Casts to a pointer of another type.
43     #[stable(feature = "ptr_cast", since = "1.38.0")]
44     #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
45     #[inline(always)]
46     pub const fn cast<U>(self) -> *mut U {
47         self as _
48     }
49
50     /// Changes constness without changing the type.
51     ///
52     /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
53     /// refactored.
54     ///
55     /// While not strictly required (`*mut T` coerces to `*const T`), this is provided for symmetry
56     /// with `as_mut()` on `*const T` and may have documentation value if used instead of implicit
57     /// coercion.
58     #[unstable(feature = "ptr_const_cast", issue = "92675")]
59     #[rustc_const_unstable(feature = "ptr_const_cast", issue = "92675")]
60     pub const fn as_const(self) -> *const T {
61         self as _
62     }
63
64     /// Casts a pointer to its raw bits.
65     ///
66     /// This is equivalent to `as usize`, but is more specific to enhance readability.
67     /// The inverse method is [`from_bits`](#method.from_bits-1).
68     ///
69     /// In particular, `*p as usize` and `p as usize` will both compile for
70     /// pointers to numeric types but do very different things, so using this
71     /// helps emphasize that reading the bits was intentional.
72     ///
73     /// # Examples
74     ///
75     /// ```
76     /// #![feature(ptr_to_from_bits)]
77     /// let mut array = [13, 42];
78     /// let mut it = array.iter_mut();
79     /// let p0: *mut i32 = it.next().unwrap();
80     /// assert_eq!(<*mut _>::from_bits(p0.to_bits()), p0);
81     /// let p1: *mut i32 = it.next().unwrap();
82     /// assert_eq!(p1.to_bits() - p0.to_bits(), 4);
83     /// ```
84     #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
85     pub fn to_bits(self) -> usize
86     where
87         T: Sized,
88     {
89         self as usize
90     }
91
92     /// Creates a pointer from its raw bits.
93     ///
94     /// This is equivalent to `as *mut T`, but is more specific to enhance readability.
95     /// The inverse method is [`to_bits`](#method.to_bits-1).
96     ///
97     /// # Examples
98     ///
99     /// ```
100     /// #![feature(ptr_to_from_bits)]
101     /// use std::ptr::NonNull;
102     /// let dangling: *mut u8 = NonNull::dangling().as_ptr();
103     /// assert_eq!(<*mut u8>::from_bits(1), dangling);
104     /// ```
105     #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
106     pub fn from_bits(bits: usize) -> Self
107     where
108         T: Sized,
109     {
110         bits as Self
111     }
112
113     /// Decompose a (possibly wide) pointer into its address and metadata components.
114     ///
115     /// The pointer can be later reconstructed with [`from_raw_parts_mut`].
116     #[unstable(feature = "ptr_metadata", issue = "81513")]
117     #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
118     #[inline]
119     pub const fn to_raw_parts(self) -> (*mut (), <T as super::Pointee>::Metadata) {
120         (self.cast(), super::metadata(self))
121     }
122
123     /// Returns `None` if the pointer is null, or else returns a shared reference to
124     /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
125     /// must be used instead.
126     ///
127     /// For the mutable counterpart see [`as_mut`].
128     ///
129     /// [`as_uninit_ref`]: #method.as_uninit_ref-1
130     /// [`as_mut`]: #method.as_mut
131     ///
132     /// # Safety
133     ///
134     /// When calling this method, you have to ensure that *either* the pointer is null *or*
135     /// all of the following is true:
136     ///
137     /// * The pointer must be properly aligned.
138     ///
139     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
140     ///
141     /// * The pointer must point to an initialized instance of `T`.
142     ///
143     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
144     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
145     ///   In particular, for the duration of this lifetime, the memory the pointer points to must
146     ///   not get mutated (except inside `UnsafeCell`).
147     ///
148     /// This applies even if the result of this method is unused!
149     /// (The part about being initialized is not yet fully decided, but until
150     /// it is, the only safe approach is to ensure that they are indeed initialized.)
151     ///
152     /// [the module documentation]: crate::ptr#safety
153     ///
154     /// # Examples
155     ///
156     /// Basic usage:
157     ///
158     /// ```
159     /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
160     ///
161     /// unsafe {
162     ///     if let Some(val_back) = ptr.as_ref() {
163     ///         println!("We got back the value: {val_back}!");
164     ///     }
165     /// }
166     /// ```
167     ///
168     /// # Null-unchecked version
169     ///
170     /// If you are sure the pointer can never be null and are looking for some kind of
171     /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
172     /// dereference the pointer directly.
173     ///
174     /// ```
175     /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
176     ///
177     /// unsafe {
178     ///     let val_back = &*ptr;
179     ///     println!("We got back the value: {val_back}!");
180     /// }
181     /// ```
182     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
183     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
184     #[inline]
185     pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
186         // SAFETY: the caller must guarantee that `self` is valid for a
187         // reference if it isn't null.
188         if self.is_null() { None } else { unsafe { Some(&*self) } }
189     }
190
191     /// Returns `None` if the pointer is null, or else returns a shared reference to
192     /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
193     /// that the value has to be initialized.
194     ///
195     /// For the mutable counterpart see [`as_uninit_mut`].
196     ///
197     /// [`as_ref`]: #method.as_ref-1
198     /// [`as_uninit_mut`]: #method.as_uninit_mut
199     ///
200     /// # Safety
201     ///
202     /// When calling this method, you have to ensure that *either* the pointer is null *or*
203     /// all of the following is true:
204     ///
205     /// * The pointer must be properly aligned.
206     ///
207     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
208     ///
209     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
210     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
211     ///   In particular, for the duration of this lifetime, the memory the pointer points to must
212     ///   not get mutated (except inside `UnsafeCell`).
213     ///
214     /// This applies even if the result of this method is unused!
215     ///
216     /// [the module documentation]: crate::ptr#safety
217     ///
218     /// # Examples
219     ///
220     /// Basic usage:
221     ///
222     /// ```
223     /// #![feature(ptr_as_uninit)]
224     ///
225     /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
226     ///
227     /// unsafe {
228     ///     if let Some(val_back) = ptr.as_uninit_ref() {
229     ///         println!("We got back the value: {}!", val_back.assume_init());
230     ///     }
231     /// }
232     /// ```
233     #[inline]
234     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
235     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
236     pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
237     where
238         T: Sized,
239     {
240         // SAFETY: the caller must guarantee that `self` meets all the
241         // requirements for a reference.
242         if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
243     }
244
245     /// Calculates the offset from a pointer.
246     ///
247     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
248     /// offset of `3 * size_of::<T>()` bytes.
249     ///
250     /// # Safety
251     ///
252     /// If any of the following conditions are violated, the result is Undefined
253     /// Behavior:
254     ///
255     /// * Both the starting and resulting pointer must be either in bounds or one
256     ///   byte past the end of the same [allocated object].
257     ///
258     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
259     ///
260     /// * The offset being in bounds cannot rely on "wrapping around" the address
261     ///   space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
262     ///
263     /// The compiler and standard library generally tries to ensure allocations
264     /// never reach a size where an offset is a concern. For instance, `Vec`
265     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
266     /// `vec.as_ptr().add(vec.len())` is always safe.
267     ///
268     /// Most platforms fundamentally can't even construct such an allocation.
269     /// For instance, no known 64-bit platform can ever serve a request
270     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
271     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
272     /// more than `isize::MAX` bytes with things like Physical Address
273     /// Extension. As such, memory acquired directly from allocators or memory
274     /// mapped files *may* be too large to handle with this function.
275     ///
276     /// Consider using [`wrapping_offset`] instead if these constraints are
277     /// difficult to satisfy. The only advantage of this method is that it
278     /// enables more aggressive compiler optimizations.
279     ///
280     /// [`wrapping_offset`]: #method.wrapping_offset
281     /// [allocated object]: crate::ptr#allocated-object
282     ///
283     /// # Examples
284     ///
285     /// Basic usage:
286     ///
287     /// ```
288     /// let mut s = [1, 2, 3];
289     /// let ptr: *mut u32 = s.as_mut_ptr();
290     ///
291     /// unsafe {
292     ///     println!("{}", *ptr.offset(1));
293     ///     println!("{}", *ptr.offset(2));
294     /// }
295     /// ```
296     #[stable(feature = "rust1", since = "1.0.0")]
297     #[must_use = "returns a new pointer rather than modifying its argument"]
298     #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
299     #[inline(always)]
300     pub const unsafe fn offset(self, count: isize) -> *mut T
301     where
302         T: Sized,
303     {
304         // SAFETY: the caller must uphold the safety contract for `offset`.
305         // The obtained pointer is valid for writes since the caller must
306         // guarantee that it points to the same allocated object as `self`.
307         unsafe { intrinsics::offset(self, count) as *mut T }
308     }
309
310     /// Calculates the offset from a pointer using wrapping arithmetic.
311     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
312     /// offset of `3 * size_of::<T>()` bytes.
313     ///
314     /// # Safety
315     ///
316     /// This operation itself is always safe, but using the resulting pointer is not.
317     ///
318     /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
319     /// be used to read or write other allocated objects.
320     ///
321     /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
322     /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
323     /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
324     /// `x` and `y` point into the same allocated object.
325     ///
326     /// Compared to [`offset`], this method basically delays the requirement of staying within the
327     /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
328     /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
329     /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
330     /// can be optimized better and is thus preferable in performance-sensitive code.
331     ///
332     /// The delayed check only considers the value of the pointer that was dereferenced, not the
333     /// intermediate values used during the computation of the final result. For example,
334     /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
335     /// words, leaving the allocated object and then re-entering it later is permitted.
336     ///
337     /// [`offset`]: #method.offset
338     /// [allocated object]: crate::ptr#allocated-object
339     ///
340     /// # Examples
341     ///
342     /// Basic usage:
343     ///
344     /// ```
345     /// // Iterate using a raw pointer in increments of two elements
346     /// let mut data = [1u8, 2, 3, 4, 5];
347     /// let mut ptr: *mut u8 = data.as_mut_ptr();
348     /// let step = 2;
349     /// let end_rounded_up = ptr.wrapping_offset(6);
350     ///
351     /// while ptr != end_rounded_up {
352     ///     unsafe {
353     ///         *ptr = 0;
354     ///     }
355     ///     ptr = ptr.wrapping_offset(step);
356     /// }
357     /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
358     /// ```
359     #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
360     #[must_use = "returns a new pointer rather than modifying its argument"]
361     #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
362     #[inline(always)]
363     pub const fn wrapping_offset(self, count: isize) -> *mut T
364     where
365         T: Sized,
366     {
367         // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
368         unsafe { intrinsics::arith_offset(self, count) as *mut T }
369     }
370
371     /// Returns `None` if the pointer is null, or else returns a unique reference to
372     /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
373     /// must be used instead.
374     ///
375     /// For the shared counterpart see [`as_ref`].
376     ///
377     /// [`as_uninit_mut`]: #method.as_uninit_mut
378     /// [`as_ref`]: #method.as_ref-1
379     ///
380     /// # Safety
381     ///
382     /// When calling this method, you have to ensure that *either* the pointer is null *or*
383     /// all of the following is true:
384     ///
385     /// * The pointer must be properly aligned.
386     ///
387     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
388     ///
389     /// * The pointer must point to an initialized instance of `T`.
390     ///
391     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
392     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
393     ///   In particular, for the duration of this lifetime, the memory the pointer points to must
394     ///   not get accessed (read or written) through any other pointer.
395     ///
396     /// This applies even if the result of this method is unused!
397     /// (The part about being initialized is not yet fully decided, but until
398     /// it is, the only safe approach is to ensure that they are indeed initialized.)
399     ///
400     /// [the module documentation]: crate::ptr#safety
401     ///
402     /// # Examples
403     ///
404     /// Basic usage:
405     ///
406     /// ```
407     /// let mut s = [1, 2, 3];
408     /// let ptr: *mut u32 = s.as_mut_ptr();
409     /// let first_value = unsafe { ptr.as_mut().unwrap() };
410     /// *first_value = 4;
411     /// # assert_eq!(s, [4, 2, 3]);
412     /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
413     /// ```
414     ///
415     /// # Null-unchecked version
416     ///
417     /// If you are sure the pointer can never be null and are looking for some kind of
418     /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
419     /// you can dereference the pointer directly.
420     ///
421     /// ```
422     /// let mut s = [1, 2, 3];
423     /// let ptr: *mut u32 = s.as_mut_ptr();
424     /// let first_value = unsafe { &mut *ptr };
425     /// *first_value = 4;
426     /// # assert_eq!(s, [4, 2, 3]);
427     /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
428     /// ```
429     #[stable(feature = "ptr_as_ref", since = "1.9.0")]
430     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
431     #[inline]
432     pub const unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
433         // SAFETY: the caller must guarantee that `self` is be valid for
434         // a mutable reference if it isn't null.
435         if self.is_null() { None } else { unsafe { Some(&mut *self) } }
436     }
437
438     /// Returns `None` if the pointer is null, or else returns a unique reference to
439     /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
440     /// that the value has to be initialized.
441     ///
442     /// For the shared counterpart see [`as_uninit_ref`].
443     ///
444     /// [`as_mut`]: #method.as_mut
445     /// [`as_uninit_ref`]: #method.as_uninit_ref-1
446     ///
447     /// # Safety
448     ///
449     /// When calling this method, you have to ensure that *either* the pointer is null *or*
450     /// all of the following is true:
451     ///
452     /// * The pointer must be properly aligned.
453     ///
454     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
455     ///
456     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
457     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
458     ///   In particular, for the duration of this lifetime, the memory the pointer points to must
459     ///   not get accessed (read or written) through any other pointer.
460     ///
461     /// This applies even if the result of this method is unused!
462     ///
463     /// [the module documentation]: crate::ptr#safety
464     #[inline]
465     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
466     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
467     pub const unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
468     where
469         T: Sized,
470     {
471         // SAFETY: the caller must guarantee that `self` meets all the
472         // requirements for a reference.
473         if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
474     }
475
476     /// Returns whether two pointers are guaranteed to be equal.
477     ///
478     /// At runtime this function behaves like `self == other`.
479     /// However, in some contexts (e.g., compile-time evaluation),
480     /// it is not always possible to determine equality of two pointers, so this function may
481     /// spuriously return `false` for pointers that later actually turn out to be equal.
482     /// But when it returns `true`, the pointers are guaranteed to be equal.
483     ///
484     /// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
485     /// comparisons for which both functions return `false`.
486     ///
487     /// [`guaranteed_ne`]: #method.guaranteed_ne
488     ///
489     /// The return value may change depending on the compiler version and unsafe code might not
490     /// rely on the result of this function for soundness. It is suggested to only use this function
491     /// for performance optimizations where spurious `false` return values by this function do not
492     /// affect the outcome, but just the performance.
493     /// The consequences of using this method to make runtime and compile-time code behave
494     /// differently have not been explored. This method should not be used to introduce such
495     /// differences, and it should also not be stabilized before we have a better understanding
496     /// of this issue.
497     #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
498     #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
499     #[inline]
500     pub const fn guaranteed_eq(self, other: *mut T) -> bool
501     where
502         T: Sized,
503     {
504         intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _)
505     }
506
507     /// Returns whether two pointers are guaranteed to be unequal.
508     ///
509     /// At runtime this function behaves like `self != other`.
510     /// However, in some contexts (e.g., compile-time evaluation),
511     /// it is not always possible to determine the inequality of two pointers, so this function may
512     /// spuriously return `false` for pointers that later actually turn out to be unequal.
513     /// But when it returns `true`, the pointers are guaranteed to be unequal.
514     ///
515     /// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
516     /// comparisons for which both functions return `false`.
517     ///
518     /// [`guaranteed_eq`]: #method.guaranteed_eq
519     ///
520     /// The return value may change depending on the compiler version and unsafe code might not
521     /// rely on the result of this function for soundness. It is suggested to only use this function
522     /// for performance optimizations where spurious `false` return values by this function do not
523     /// affect the outcome, but just the performance.
524     /// The consequences of using this method to make runtime and compile-time code behave
525     /// differently have not been explored. This method should not be used to introduce such
526     /// differences, and it should also not be stabilized before we have a better understanding
527     /// of this issue.
528     #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
529     #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
530     #[inline]
531     pub const unsafe fn guaranteed_ne(self, other: *mut T) -> bool
532     where
533         T: Sized,
534     {
535         intrinsics::ptr_guaranteed_ne(self as *const _, other as *const _)
536     }
537
538     /// Calculates the distance between two pointers. The returned value is in
539     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
540     ///
541     /// This function is the inverse of [`offset`].
542     ///
543     /// [`offset`]: #method.offset-1
544     ///
545     /// # Safety
546     ///
547     /// If any of the following conditions are violated, the result is Undefined
548     /// Behavior:
549     ///
550     /// * Both the starting and other pointer must be either in bounds or one
551     ///   byte past the end of the same [allocated object].
552     ///
553     /// * Both pointers must be *derived from* a pointer to the same object.
554     ///   (See below for an example.)
555     ///
556     /// * The distance between the pointers, in bytes, must be an exact multiple
557     ///   of the size of `T`.
558     ///
559     /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
560     ///
561     /// * The distance being in bounds cannot rely on "wrapping around" the address space.
562     ///
563     /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
564     /// address space, so two pointers within some value of any Rust type `T` will always satisfy
565     /// the last two conditions. The standard library also generally ensures that allocations
566     /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
567     /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
568     /// always satisfies the last two conditions.
569     ///
570     /// Most platforms fundamentally can't even construct such a large allocation.
571     /// For instance, no known 64-bit platform can ever serve a request
572     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
573     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
574     /// more than `isize::MAX` bytes with things like Physical Address
575     /// Extension. As such, memory acquired directly from allocators or memory
576     /// mapped files *may* be too large to handle with this function.
577     /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
578     /// such large allocations either.)
579     ///
580     /// [`add`]: #method.add
581     /// [allocated object]: crate::ptr#allocated-object
582     ///
583     /// # Panics
584     ///
585     /// This function panics if `T` is a Zero-Sized Type ("ZST").
586     ///
587     /// # Examples
588     ///
589     /// Basic usage:
590     ///
591     /// ```
592     /// let mut a = [0; 5];
593     /// let ptr1: *mut i32 = &mut a[1];
594     /// let ptr2: *mut i32 = &mut a[3];
595     /// unsafe {
596     ///     assert_eq!(ptr2.offset_from(ptr1), 2);
597     ///     assert_eq!(ptr1.offset_from(ptr2), -2);
598     ///     assert_eq!(ptr1.offset(2), ptr2);
599     ///     assert_eq!(ptr2.offset(-2), ptr1);
600     /// }
601     /// ```
602     ///
603     /// *Incorrect* usage:
604     ///
605     /// ```rust,no_run
606     /// let ptr1 = Box::into_raw(Box::new(0u8));
607     /// let ptr2 = Box::into_raw(Box::new(1u8));
608     /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
609     /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
610     /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff);
611     /// assert_eq!(ptr2 as usize, ptr2_other as usize);
612     /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
613     /// // computing their offset is undefined behavior, even though
614     /// // they point to the same address!
615     /// unsafe {
616     ///     let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
617     /// }
618     /// ```
619     #[stable(feature = "ptr_offset_from", since = "1.47.0")]
620     #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "92980")]
621     #[inline(always)]
622     pub const unsafe fn offset_from(self, origin: *const T) -> isize
623     where
624         T: Sized,
625     {
626         // SAFETY: the caller must uphold the safety contract for `offset_from`.
627         unsafe { (self as *const T).offset_from(origin) }
628     }
629
630     /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
631     ///
632     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
633     /// offset of `3 * size_of::<T>()` bytes.
634     ///
635     /// # Safety
636     ///
637     /// If any of the following conditions are violated, the result is Undefined
638     /// Behavior:
639     ///
640     /// * Both the starting and resulting pointer must be either in bounds or one
641     ///   byte past the end of the same [allocated object].
642     ///
643     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
644     ///
645     /// * The offset being in bounds cannot rely on "wrapping around" the address
646     ///   space. That is, the infinite-precision sum must fit in a `usize`.
647     ///
648     /// The compiler and standard library generally tries to ensure allocations
649     /// never reach a size where an offset is a concern. For instance, `Vec`
650     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
651     /// `vec.as_ptr().add(vec.len())` is always safe.
652     ///
653     /// Most platforms fundamentally can't even construct such an allocation.
654     /// For instance, no known 64-bit platform can ever serve a request
655     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
656     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
657     /// more than `isize::MAX` bytes with things like Physical Address
658     /// Extension. As such, memory acquired directly from allocators or memory
659     /// mapped files *may* be too large to handle with this function.
660     ///
661     /// Consider using [`wrapping_add`] instead if these constraints are
662     /// difficult to satisfy. The only advantage of this method is that it
663     /// enables more aggressive compiler optimizations.
664     ///
665     /// [`wrapping_add`]: #method.wrapping_add
666     /// [allocated object]: crate::ptr#allocated-object
667     ///
668     /// # Examples
669     ///
670     /// Basic usage:
671     ///
672     /// ```
673     /// let s: &str = "123";
674     /// let ptr: *const u8 = s.as_ptr();
675     ///
676     /// unsafe {
677     ///     println!("{}", *ptr.add(1) as char);
678     ///     println!("{}", *ptr.add(2) as char);
679     /// }
680     /// ```
681     #[stable(feature = "pointer_methods", since = "1.26.0")]
682     #[must_use = "returns a new pointer rather than modifying its argument"]
683     #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
684     #[inline(always)]
685     pub const unsafe fn add(self, count: usize) -> Self
686     where
687         T: Sized,
688     {
689         // SAFETY: the caller must uphold the safety contract for `offset`.
690         unsafe { self.offset(count as isize) }
691     }
692
693     /// Calculates the offset from a pointer (convenience for
694     /// `.offset((count as isize).wrapping_neg())`).
695     ///
696     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
697     /// offset of `3 * size_of::<T>()` bytes.
698     ///
699     /// # Safety
700     ///
701     /// If any of the following conditions are violated, the result is Undefined
702     /// Behavior:
703     ///
704     /// * Both the starting and resulting pointer must be either in bounds or one
705     ///   byte past the end of the same [allocated object].
706     ///
707     /// * The computed offset cannot exceed `isize::MAX` **bytes**.
708     ///
709     /// * The offset being in bounds cannot rely on "wrapping around" the address
710     ///   space. That is, the infinite-precision sum must fit in a usize.
711     ///
712     /// The compiler and standard library generally tries to ensure allocations
713     /// never reach a size where an offset is a concern. For instance, `Vec`
714     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
715     /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
716     ///
717     /// Most platforms fundamentally can't even construct such an allocation.
718     /// For instance, no known 64-bit platform can ever serve a request
719     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
720     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
721     /// more than `isize::MAX` bytes with things like Physical Address
722     /// Extension. As such, memory acquired directly from allocators or memory
723     /// mapped files *may* be too large to handle with this function.
724     ///
725     /// Consider using [`wrapping_sub`] instead if these constraints are
726     /// difficult to satisfy. The only advantage of this method is that it
727     /// enables more aggressive compiler optimizations.
728     ///
729     /// [`wrapping_sub`]: #method.wrapping_sub
730     /// [allocated object]: crate::ptr#allocated-object
731     ///
732     /// # Examples
733     ///
734     /// Basic usage:
735     ///
736     /// ```
737     /// let s: &str = "123";
738     ///
739     /// unsafe {
740     ///     let end: *const u8 = s.as_ptr().add(3);
741     ///     println!("{}", *end.sub(1) as char);
742     ///     println!("{}", *end.sub(2) as char);
743     /// }
744     /// ```
745     #[stable(feature = "pointer_methods", since = "1.26.0")]
746     #[must_use = "returns a new pointer rather than modifying its argument"]
747     #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
748     #[inline]
749     pub const unsafe fn sub(self, count: usize) -> Self
750     where
751         T: Sized,
752     {
753         // SAFETY: the caller must uphold the safety contract for `offset`.
754         unsafe { self.offset((count as isize).wrapping_neg()) }
755     }
756
757     /// Calculates the offset from a pointer using wrapping arithmetic.
758     /// (convenience for `.wrapping_offset(count as isize)`)
759     ///
760     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
761     /// offset of `3 * size_of::<T>()` bytes.
762     ///
763     /// # Safety
764     ///
765     /// This operation itself is always safe, but using the resulting pointer is not.
766     ///
767     /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
768     /// be used to read or write other allocated objects.
769     ///
770     /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
771     /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
772     /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
773     /// `x` and `y` point into the same allocated object.
774     ///
775     /// Compared to [`add`], this method basically delays the requirement of staying within the
776     /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
777     /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
778     /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
779     /// can be optimized better and is thus preferable in performance-sensitive code.
780     ///
781     /// The delayed check only considers the value of the pointer that was dereferenced, not the
782     /// intermediate values used during the computation of the final result. For example,
783     /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
784     /// allocated object and then re-entering it later is permitted.
785     ///
786     /// [`add`]: #method.add
787     /// [allocated object]: crate::ptr#allocated-object
788     ///
789     /// # Examples
790     ///
791     /// Basic usage:
792     ///
793     /// ```
794     /// // Iterate using a raw pointer in increments of two elements
795     /// let data = [1u8, 2, 3, 4, 5];
796     /// let mut ptr: *const u8 = data.as_ptr();
797     /// let step = 2;
798     /// let end_rounded_up = ptr.wrapping_add(6);
799     ///
800     /// // This loop prints "1, 3, 5, "
801     /// while ptr != end_rounded_up {
802     ///     unsafe {
803     ///         print!("{}, ", *ptr);
804     ///     }
805     ///     ptr = ptr.wrapping_add(step);
806     /// }
807     /// ```
808     #[stable(feature = "pointer_methods", since = "1.26.0")]
809     #[must_use = "returns a new pointer rather than modifying its argument"]
810     #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
811     #[inline(always)]
812     pub const fn wrapping_add(self, count: usize) -> Self
813     where
814         T: Sized,
815     {
816         self.wrapping_offset(count as isize)
817     }
818
819     /// Calculates the offset from a pointer using wrapping arithmetic.
820     /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
821     ///
822     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
823     /// offset of `3 * size_of::<T>()` bytes.
824     ///
825     /// # Safety
826     ///
827     /// This operation itself is always safe, but using the resulting pointer is not.
828     ///
829     /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
830     /// be used to read or write other allocated objects.
831     ///
832     /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
833     /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
834     /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
835     /// `x` and `y` point into the same allocated object.
836     ///
837     /// Compared to [`sub`], this method basically delays the requirement of staying within the
838     /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
839     /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
840     /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
841     /// can be optimized better and is thus preferable in performance-sensitive code.
842     ///
843     /// The delayed check only considers the value of the pointer that was dereferenced, not the
844     /// intermediate values used during the computation of the final result. For example,
845     /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
846     /// allocated object and then re-entering it later is permitted.
847     ///
848     /// [`sub`]: #method.sub
849     /// [allocated object]: crate::ptr#allocated-object
850     ///
851     /// # Examples
852     ///
853     /// Basic usage:
854     ///
855     /// ```
856     /// // Iterate using a raw pointer in increments of two elements (backwards)
857     /// let data = [1u8, 2, 3, 4, 5];
858     /// let mut ptr: *const u8 = data.as_ptr();
859     /// let start_rounded_down = ptr.wrapping_sub(2);
860     /// ptr = ptr.wrapping_add(4);
861     /// let step = 2;
862     /// // This loop prints "5, 3, 1, "
863     /// while ptr != start_rounded_down {
864     ///     unsafe {
865     ///         print!("{}, ", *ptr);
866     ///     }
867     ///     ptr = ptr.wrapping_sub(step);
868     /// }
869     /// ```
870     #[stable(feature = "pointer_methods", since = "1.26.0")]
871     #[must_use = "returns a new pointer rather than modifying its argument"]
872     #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
873     #[inline]
874     pub const fn wrapping_sub(self, count: usize) -> Self
875     where
876         T: Sized,
877     {
878         self.wrapping_offset((count as isize).wrapping_neg())
879     }
880
881     /// Sets the pointer value to `ptr`.
882     ///
883     /// In case `self` is a (fat) pointer to an unsized type, this operation
884     /// will only affect the pointer part, whereas for (thin) pointers to
885     /// sized types, this has the same effect as a simple assignment.
886     ///
887     /// The resulting pointer will have provenance of `val`, i.e., for a fat
888     /// pointer, this operation is semantically the same as creating a new
889     /// fat pointer with the data pointer value of `val` but the metadata of
890     /// `self`.
891     ///
892     /// # Examples
893     ///
894     /// This function is primarily useful for allowing byte-wise pointer
895     /// arithmetic on potentially fat pointers:
896     ///
897     /// ```
898     /// #![feature(set_ptr_value)]
899     /// # use core::fmt::Debug;
900     /// let mut arr: [i32; 3] = [1, 2, 3];
901     /// let mut ptr = arr.as_mut_ptr() as *mut dyn Debug;
902     /// let thin = ptr as *mut u8;
903     /// unsafe {
904     ///     ptr = ptr.set_ptr_value(thin.add(8));
905     ///     # assert_eq!(*(ptr as *mut i32), 3);
906     ///     println!("{:?}", &*ptr); // will print "3"
907     /// }
908     /// ```
909     #[unstable(feature = "set_ptr_value", issue = "75091")]
910     #[must_use = "returns a new pointer rather than modifying its argument"]
911     #[inline]
912     pub fn set_ptr_value(mut self, val: *mut u8) -> Self {
913         let thin = &mut self as *mut *mut T as *mut *mut u8;
914         // SAFETY: In case of a thin pointer, this operations is identical
915         // to a simple assignment. In case of a fat pointer, with the current
916         // fat pointer layout implementation, the first field of such a
917         // pointer is always the data pointer, which is likewise assigned.
918         unsafe { *thin = val };
919         self
920     }
921
922     /// Reads the value from `self` without moving it. This leaves the
923     /// memory in `self` unchanged.
924     ///
925     /// See [`ptr::read`] for safety concerns and examples.
926     ///
927     /// [`ptr::read`]: crate::ptr::read()
928     #[stable(feature = "pointer_methods", since = "1.26.0")]
929     #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
930     #[inline(always)]
931     pub const unsafe fn read(self) -> T
932     where
933         T: Sized,
934     {
935         // SAFETY: the caller must uphold the safety contract for ``.
936         unsafe { read(self) }
937     }
938
939     /// Performs a volatile read of the value from `self` without moving it. This
940     /// leaves the memory in `self` unchanged.
941     ///
942     /// Volatile operations are intended to act on I/O memory, and are guaranteed
943     /// to not be elided or reordered by the compiler across other volatile
944     /// operations.
945     ///
946     /// See [`ptr::read_volatile`] for safety concerns and examples.
947     ///
948     /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
949     #[stable(feature = "pointer_methods", since = "1.26.0")]
950     #[inline(always)]
951     pub unsafe fn read_volatile(self) -> T
952     where
953         T: Sized,
954     {
955         // SAFETY: the caller must uphold the safety contract for `read_volatile`.
956         unsafe { read_volatile(self) }
957     }
958
959     /// Reads the value from `self` without moving it. This leaves the
960     /// memory in `self` unchanged.
961     ///
962     /// Unlike `read`, the pointer may be unaligned.
963     ///
964     /// See [`ptr::read_unaligned`] for safety concerns and examples.
965     ///
966     /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
967     #[stable(feature = "pointer_methods", since = "1.26.0")]
968     #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
969     #[inline(always)]
970     pub const unsafe fn read_unaligned(self) -> T
971     where
972         T: Sized,
973     {
974         // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
975         unsafe { read_unaligned(self) }
976     }
977
978     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
979     /// and destination may overlap.
980     ///
981     /// NOTE: this has the *same* argument order as [`ptr::copy`].
982     ///
983     /// See [`ptr::copy`] for safety concerns and examples.
984     ///
985     /// [`ptr::copy`]: crate::ptr::copy()
986     #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
987     #[stable(feature = "pointer_methods", since = "1.26.0")]
988     #[inline(always)]
989     pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
990     where
991         T: Sized,
992     {
993         // SAFETY: the caller must uphold the safety contract for `copy`.
994         unsafe { copy(self, dest, count) }
995     }
996
997     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
998     /// and destination may *not* overlap.
999     ///
1000     /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1001     ///
1002     /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1003     ///
1004     /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1005     #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
1006     #[stable(feature = "pointer_methods", since = "1.26.0")]
1007     #[inline(always)]
1008     pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1009     where
1010         T: Sized,
1011     {
1012         // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1013         unsafe { copy_nonoverlapping(self, dest, count) }
1014     }
1015
1016     /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1017     /// and destination may overlap.
1018     ///
1019     /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1020     ///
1021     /// See [`ptr::copy`] for safety concerns and examples.
1022     ///
1023     /// [`ptr::copy`]: crate::ptr::copy()
1024     #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
1025     #[stable(feature = "pointer_methods", since = "1.26.0")]
1026     #[inline(always)]
1027     pub const unsafe fn copy_from(self, src: *const T, count: usize)
1028     where
1029         T: Sized,
1030     {
1031         // SAFETY: the caller must uphold the safety contract for `copy`.
1032         unsafe { copy(src, self, count) }
1033     }
1034
1035     /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1036     /// and destination may *not* overlap.
1037     ///
1038     /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1039     ///
1040     /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1041     ///
1042     /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1043     #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
1044     #[stable(feature = "pointer_methods", since = "1.26.0")]
1045     #[inline(always)]
1046     pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1047     where
1048         T: Sized,
1049     {
1050         // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1051         unsafe { copy_nonoverlapping(src, self, count) }
1052     }
1053
1054     /// Executes the destructor (if any) of the pointed-to value.
1055     ///
1056     /// See [`ptr::drop_in_place`] for safety concerns and examples.
1057     ///
1058     /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1059     #[stable(feature = "pointer_methods", since = "1.26.0")]
1060     #[inline(always)]
1061     pub unsafe fn drop_in_place(self) {
1062         // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1063         unsafe { drop_in_place(self) }
1064     }
1065
1066     /// Overwrites a memory location with the given value without reading or
1067     /// dropping the old value.
1068     ///
1069     /// See [`ptr::write`] for safety concerns and examples.
1070     ///
1071     /// [`ptr::write`]: crate::ptr::write()
1072     #[stable(feature = "pointer_methods", since = "1.26.0")]
1073     #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1074     #[inline(always)]
1075     pub const unsafe fn write(self, val: T)
1076     where
1077         T: Sized,
1078     {
1079         // SAFETY: the caller must uphold the safety contract for `write`.
1080         unsafe { write(self, val) }
1081     }
1082
1083     /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1084     /// bytes of memory starting at `self` to `val`.
1085     ///
1086     /// See [`ptr::write_bytes`] for safety concerns and examples.
1087     ///
1088     /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1089     #[stable(feature = "pointer_methods", since = "1.26.0")]
1090     #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1091     #[inline(always)]
1092     pub const unsafe fn write_bytes(self, val: u8, count: usize)
1093     where
1094         T: Sized,
1095     {
1096         // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1097         unsafe { write_bytes(self, val, count) }
1098     }
1099
1100     /// Performs a volatile write of a memory location with the given value without
1101     /// reading or dropping the old value.
1102     ///
1103     /// Volatile operations are intended to act on I/O memory, and are guaranteed
1104     /// to not be elided or reordered by the compiler across other volatile
1105     /// operations.
1106     ///
1107     /// See [`ptr::write_volatile`] for safety concerns and examples.
1108     ///
1109     /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1110     #[stable(feature = "pointer_methods", since = "1.26.0")]
1111     #[inline(always)]
1112     pub unsafe fn write_volatile(self, val: T)
1113     where
1114         T: Sized,
1115     {
1116         // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1117         unsafe { write_volatile(self, val) }
1118     }
1119
1120     /// Overwrites a memory location with the given value without reading or
1121     /// dropping the old value.
1122     ///
1123     /// Unlike `write`, the pointer may be unaligned.
1124     ///
1125     /// See [`ptr::write_unaligned`] for safety concerns and examples.
1126     ///
1127     /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1128     #[stable(feature = "pointer_methods", since = "1.26.0")]
1129     #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1130     #[inline(always)]
1131     pub const unsafe fn write_unaligned(self, val: T)
1132     where
1133         T: Sized,
1134     {
1135         // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1136         unsafe { write_unaligned(self, val) }
1137     }
1138
1139     /// Replaces the value at `self` with `src`, returning the old
1140     /// value, without dropping either.
1141     ///
1142     /// See [`ptr::replace`] for safety concerns and examples.
1143     ///
1144     /// [`ptr::replace`]: crate::ptr::replace()
1145     #[stable(feature = "pointer_methods", since = "1.26.0")]
1146     #[inline(always)]
1147     pub unsafe fn replace(self, src: T) -> T
1148     where
1149         T: Sized,
1150     {
1151         // SAFETY: the caller must uphold the safety contract for `replace`.
1152         unsafe { replace(self, src) }
1153     }
1154
1155     /// Swaps the values at two mutable locations of the same type, without
1156     /// deinitializing either. They may overlap, unlike `mem::swap` which is
1157     /// otherwise equivalent.
1158     ///
1159     /// See [`ptr::swap`] for safety concerns and examples.
1160     ///
1161     /// [`ptr::swap`]: crate::ptr::swap()
1162     #[stable(feature = "pointer_methods", since = "1.26.0")]
1163     #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
1164     #[inline(always)]
1165     pub const unsafe fn swap(self, with: *mut T)
1166     where
1167         T: Sized,
1168     {
1169         // SAFETY: the caller must uphold the safety contract for `swap`.
1170         unsafe { swap(self, with) }
1171     }
1172
1173     /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1174     /// `align`.
1175     ///
1176     /// If it is not possible to align the pointer, the implementation returns
1177     /// `usize::MAX`. It is permissible for the implementation to *always*
1178     /// return `usize::MAX`. Only your algorithm's performance can depend
1179     /// on getting a usable offset here, not its correctness.
1180     ///
1181     /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1182     /// used with the `wrapping_add` method.
1183     ///
1184     /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1185     /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1186     /// the returned offset is correct in all terms other than alignment.
1187     ///
1188     /// # Panics
1189     ///
1190     /// The function panics if `align` is not a power-of-two.
1191     ///
1192     /// # Examples
1193     ///
1194     /// Accessing adjacent `u8` as `u16`
1195     ///
1196     /// ```
1197     /// # fn foo(n: usize) {
1198     /// # use std::mem::align_of;
1199     /// # unsafe {
1200     /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1201     /// let ptr = x.as_ptr().add(n) as *const u8;
1202     /// let offset = ptr.align_offset(align_of::<u16>());
1203     /// if offset < x.len() - n - 1 {
1204     ///     let u16_ptr = ptr.add(offset) as *const u16;
1205     ///     assert_ne!(*u16_ptr, 500);
1206     /// } else {
1207     ///     // while the pointer can be aligned via `offset`, it would point
1208     ///     // outside the allocation
1209     /// }
1210     /// # } }
1211     /// ```
1212     #[stable(feature = "align_offset", since = "1.36.0")]
1213     #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1214     pub const fn align_offset(self, align: usize) -> usize
1215     where
1216         T: Sized,
1217     {
1218         if !align.is_power_of_two() {
1219             panic!("align_offset: align is not a power-of-two");
1220         }
1221
1222         fn rt_impl<T>(p: *mut T, align: usize) -> usize {
1223             // SAFETY: `align` has been checked to be a power of 2 above
1224             unsafe { align_offset(p, align) }
1225         }
1226
1227         const fn ctfe_impl<T>(_: *mut T, _: usize) -> usize {
1228             usize::MAX
1229         }
1230
1231         // SAFETY:
1232         // It is permisseble for `align_offset` to always return `usize::MAX`,
1233         // algorithm correctness can not depend on `align_offset` returning non-max values.
1234         //
1235         // As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
1236         unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
1237     }
1238 }
1239
1240 #[lang = "mut_slice_ptr"]
1241 impl<T> *mut [T] {
1242     /// Returns the length of a raw slice.
1243     ///
1244     /// The returned value is the number of **elements**, not the number of bytes.
1245     ///
1246     /// This function is safe, even when the raw slice cannot be cast to a slice
1247     /// reference because the pointer is null or unaligned.
1248     ///
1249     /// # Examples
1250     ///
1251     /// ```rust
1252     /// #![feature(slice_ptr_len)]
1253     /// use std::ptr;
1254     ///
1255     /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1256     /// assert_eq!(slice.len(), 3);
1257     /// ```
1258     #[inline(always)]
1259     #[unstable(feature = "slice_ptr_len", issue = "71146")]
1260     #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1261     pub const fn len(self) -> usize {
1262         metadata(self)
1263     }
1264
1265     /// Returns a raw pointer to the slice's buffer.
1266     ///
1267     /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
1268     ///
1269     /// # Examples
1270     ///
1271     /// ```rust
1272     /// #![feature(slice_ptr_get)]
1273     /// use std::ptr;
1274     ///
1275     /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1276     /// assert_eq!(slice.as_mut_ptr(), 0 as *mut i8);
1277     /// ```
1278     #[inline(always)]
1279     #[unstable(feature = "slice_ptr_get", issue = "74265")]
1280     #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
1281     pub const fn as_mut_ptr(self) -> *mut T {
1282         self as *mut T
1283     }
1284
1285     /// Returns a raw pointer to an element or subslice, without doing bounds
1286     /// checking.
1287     ///
1288     /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
1289     /// is *[undefined behavior]* even if the resulting pointer is not used.
1290     ///
1291     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1292     ///
1293     /// # Examples
1294     ///
1295     /// ```
1296     /// #![feature(slice_ptr_get)]
1297     ///
1298     /// let x = &mut [1, 2, 4] as *mut [i32];
1299     ///
1300     /// unsafe {
1301     ///     assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
1302     /// }
1303     /// ```
1304     #[unstable(feature = "slice_ptr_get", issue = "74265")]
1305     #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
1306     #[inline(always)]
1307     pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
1308     where
1309         I: ~const SliceIndex<[T]>,
1310     {
1311         // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1312         unsafe { index.get_unchecked_mut(self) }
1313     }
1314
1315     /// Returns `None` if the pointer is null, or else returns a shared slice to
1316     /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1317     /// that the value has to be initialized.
1318     ///
1319     /// For the mutable counterpart see [`as_uninit_slice_mut`].
1320     ///
1321     /// [`as_ref`]: #method.as_ref-1
1322     /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
1323     ///
1324     /// # Safety
1325     ///
1326     /// When calling this method, you have to ensure that *either* the pointer is null *or*
1327     /// all of the following is true:
1328     ///
1329     /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1330     ///   and it must be properly aligned. This means in particular:
1331     ///
1332     ///     * The entire memory range of this slice must be contained within a single [allocated object]!
1333     ///       Slices can never span across multiple allocated objects.
1334     ///
1335     ///     * The pointer must be aligned even for zero-length slices. One
1336     ///       reason for this is that enum layout optimizations may rely on references
1337     ///       (including slices of any length) being aligned and non-null to distinguish
1338     ///       them from other data. You can obtain a pointer that is usable as `data`
1339     ///       for zero-length slices using [`NonNull::dangling()`].
1340     ///
1341     /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1342     ///   See the safety documentation of [`pointer::offset`].
1343     ///
1344     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1345     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1346     ///   In particular, for the duration of this lifetime, the memory the pointer points to must
1347     ///   not get mutated (except inside `UnsafeCell`).
1348     ///
1349     /// This applies even if the result of this method is unused!
1350     ///
1351     /// See also [`slice::from_raw_parts`][].
1352     ///
1353     /// [valid]: crate::ptr#safety
1354     /// [allocated object]: crate::ptr#allocated-object
1355     #[inline]
1356     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1357     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1358     pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1359         if self.is_null() {
1360             None
1361         } else {
1362             // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1363             Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1364         }
1365     }
1366
1367     /// Returns `None` if the pointer is null, or else returns a unique slice to
1368     /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
1369     /// that the value has to be initialized.
1370     ///
1371     /// For the shared counterpart see [`as_uninit_slice`].
1372     ///
1373     /// [`as_mut`]: #method.as_mut
1374     /// [`as_uninit_slice`]: #method.as_uninit_slice-1
1375     ///
1376     /// # Safety
1377     ///
1378     /// When calling this method, you have to ensure that *either* the pointer is null *or*
1379     /// all of the following is true:
1380     ///
1381     /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
1382     ///   many bytes, and it must be properly aligned. This means in particular:
1383     ///
1384     ///     * The entire memory range of this slice must be contained within a single [allocated object]!
1385     ///       Slices can never span across multiple allocated objects.
1386     ///
1387     ///     * The pointer must be aligned even for zero-length slices. One
1388     ///       reason for this is that enum layout optimizations may rely on references
1389     ///       (including slices of any length) being aligned and non-null to distinguish
1390     ///       them from other data. You can obtain a pointer that is usable as `data`
1391     ///       for zero-length slices using [`NonNull::dangling()`].
1392     ///
1393     /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1394     ///   See the safety documentation of [`pointer::offset`].
1395     ///
1396     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1397     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1398     ///   In particular, for the duration of this lifetime, the memory the pointer points to must
1399     ///   not get accessed (read or written) through any other pointer.
1400     ///
1401     /// This applies even if the result of this method is unused!
1402     ///
1403     /// See also [`slice::from_raw_parts_mut`][].
1404     ///
1405     /// [valid]: crate::ptr#safety
1406     /// [allocated object]: crate::ptr#allocated-object
1407     #[inline]
1408     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1409     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1410     pub const unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
1411         if self.is_null() {
1412             None
1413         } else {
1414             // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
1415             Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
1416         }
1417     }
1418 }
1419
1420 // Equality for pointers
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 impl<T: ?Sized> PartialEq for *mut T {
1423     #[inline(always)]
1424     fn eq(&self, other: &*mut T) -> bool {
1425         *self == *other
1426     }
1427 }
1428
1429 #[stable(feature = "rust1", since = "1.0.0")]
1430 impl<T: ?Sized> Eq for *mut T {}
1431
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 impl<T: ?Sized> Ord for *mut T {
1434     #[inline]
1435     fn cmp(&self, other: &*mut T) -> Ordering {
1436         if self < other {
1437             Less
1438         } else if self == other {
1439             Equal
1440         } else {
1441             Greater
1442         }
1443     }
1444 }
1445
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 impl<T: ?Sized> PartialOrd for *mut T {
1448     #[inline(always)]
1449     fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
1450         Some(self.cmp(other))
1451     }
1452
1453     #[inline(always)]
1454     fn lt(&self, other: &*mut T) -> bool {
1455         *self < *other
1456     }
1457
1458     #[inline(always)]
1459     fn le(&self, other: &*mut T) -> bool {
1460         *self <= *other
1461     }
1462
1463     #[inline(always)]
1464     fn gt(&self, other: &*mut T) -> bool {
1465         *self > *other
1466     }
1467
1468     #[inline(always)]
1469     fn ge(&self, other: &*mut T) -> bool {
1470         *self >= *other
1471     }
1472 }