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