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