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