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