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