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