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