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