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