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