]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr/const_ptr.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / libcore / 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
6 // ignore-tidy-undocumented-unsafe
7
8 #[lang = "const_ptr"]
9 impl<T: ?Sized> *const T {
10     /// Returns `true` if the pointer is null.
11     ///
12     /// Note that unsized types have many possible null pointers, as only the
13     /// raw data pointer is considered, not their length, vtable, etc.
14     /// Therefore, two pointers that are null may still not compare equal to
15     /// each other.
16     ///
17     /// # Examples
18     ///
19     /// Basic usage:
20     ///
21     /// ```
22     /// let s: &str = "Follow the rabbit";
23     /// let ptr: *const u8 = s.as_ptr();
24     /// assert!(!ptr.is_null());
25     /// ```
26     #[stable(feature = "rust1", since = "1.0.0")]
27     #[inline]
28     pub fn is_null(self) -> bool {
29         // Compare via a cast to a thin pointer, so fat pointers are only
30         // considering their "data" part for null-ness.
31         (self as *const u8) == null()
32     }
33
34     /// Casts to a pointer of another type.
35     #[stable(feature = "ptr_cast", since = "1.38.0")]
36     #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
37     #[inline]
38     pub const fn cast<U>(self) -> *const U {
39         self as _
40     }
41
42     /// Returns `None` if the pointer is null, or else returns a reference to
43     /// the value wrapped in `Some`.
44     ///
45     /// # Safety
46     ///
47     /// While this method and its mutable counterpart are useful for
48     /// null-safety, it is important to note that this is still an unsafe
49     /// operation because the returned value could be pointing to invalid
50     /// memory.
51     ///
52     /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
53     /// all of the following is true:
54     /// - it is properly aligned
55     /// - it must point to an initialized instance of T; in particular, the pointer must be
56     ///   "dereferenceable" in the sense defined [here].
57     ///
58     /// This applies even if the result of this method is unused!
59     /// (The part about being initialized is not yet fully decided, but until
60     /// it is, the only safe approach is to ensure that they are indeed initialized.)
61     ///
62     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
63     /// not necessarily reflect the actual lifetime of the data. *You* must enforce
64     /// Rust's aliasing rules. In particular, for the duration of this lifetime,
65     /// the memory the pointer points to must not get mutated (except inside `UnsafeCell`).
66     ///
67     /// [here]: 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         if self.is_null() { None } else { Some(&*self) }
101     }
102
103     /// Calculates the offset from a pointer.
104     ///
105     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
106     /// offset of `3 * size_of::<T>()` bytes.
107     ///
108     /// # Safety
109     ///
110     /// If any of the following conditions are violated, the result is Undefined
111     /// Behavior:
112     ///
113     /// * Both the starting and resulting pointer must be either in bounds or one
114     ///   byte past the end of the same allocated object. Note that in Rust,
115     ///   every (stack-allocated) variable is considered a separate allocated object.
116     ///
117     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
118     ///
119     /// * The offset being in bounds cannot rely on "wrapping around" the address
120     ///   space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
121     ///
122     /// The compiler and standard library generally tries to ensure allocations
123     /// never reach a size where an offset is a concern. For instance, `Vec`
124     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
125     /// `vec.as_ptr().add(vec.len())` is always safe.
126     ///
127     /// Most platforms fundamentally can't even construct such an allocation.
128     /// For instance, no known 64-bit platform can ever serve a request
129     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
130     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
131     /// more than `isize::MAX` bytes with things like Physical Address
132     /// Extension. As such, memory acquired directly from allocators or memory
133     /// mapped files *may* be too large to handle with this function.
134     ///
135     /// Consider using [`wrapping_offset`] instead if these constraints are
136     /// difficult to satisfy. The only advantage of this method is that it
137     /// enables more aggressive compiler optimizations.
138     ///
139     /// [`wrapping_offset`]: #method.wrapping_offset
140     ///
141     /// # Examples
142     ///
143     /// Basic usage:
144     ///
145     /// ```
146     /// let s: &str = "123";
147     /// let ptr: *const u8 = s.as_ptr();
148     ///
149     /// unsafe {
150     ///     println!("{}", *ptr.offset(1) as char);
151     ///     println!("{}", *ptr.offset(2) as char);
152     /// }
153     /// ```
154     #[stable(feature = "rust1", since = "1.0.0")]
155     #[inline]
156     pub unsafe fn offset(self, count: isize) -> *const T
157     where
158         T: Sized,
159     {
160         intrinsics::offset(self, count)
161     }
162
163     /// Calculates the offset from a pointer using wrapping arithmetic.
164     ///
165     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
166     /// offset of `3 * size_of::<T>()` bytes.
167     ///
168     /// # Safety
169     ///
170     /// The resulting pointer does not need to be in bounds, but it is
171     /// potentially hazardous to dereference (which requires `unsafe`).
172     ///
173     /// In particular, the resulting pointer remains attached to the same allocated
174     /// object that `self` points to. It may *not* be used to access a
175     /// different allocated object. Note that in Rust,
176     /// every (stack-allocated) variable is considered a separate allocated object.
177     ///
178     /// In other words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
179     /// *not* the same as `y`, and dereferencing it is undefined behavior
180     /// unless `x` and `y` point into the same allocated object.
181     ///
182     /// Compared to [`offset`], this method basically delays the requirement of staying
183     /// within the same allocated object: [`offset`] is immediate Undefined Behavior when
184     /// crossing object boundaries; `wrapping_offset` produces a pointer but still leads
185     /// to Undefined Behavior if that pointer is dereferenced. [`offset`] can be optimized
186     /// better and is thus preferable in performance-sensitive code.
187     ///
188     /// If you need to cross object boundaries, cast the pointer to an integer and
189     /// do the arithmetic there.
190     ///
191     /// [`offset`]: #method.offset
192     ///
193     /// # Examples
194     ///
195     /// Basic usage:
196     ///
197     /// ```
198     /// // Iterate using a raw pointer in increments of two elements
199     /// let data = [1u8, 2, 3, 4, 5];
200     /// let mut ptr: *const u8 = data.as_ptr();
201     /// let step = 2;
202     /// let end_rounded_up = ptr.wrapping_offset(6);
203     ///
204     /// // This loop prints "1, 3, 5, "
205     /// while ptr != end_rounded_up {
206     ///     unsafe {
207     ///         print!("{}, ", *ptr);
208     ///     }
209     ///     ptr = ptr.wrapping_offset(step);
210     /// }
211     /// ```
212     #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
213     #[inline]
214     pub fn wrapping_offset(self, count: isize) -> *const T
215     where
216         T: Sized,
217     {
218         unsafe { intrinsics::arith_offset(self, count) }
219     }
220
221     /// Calculates the distance between two pointers. The returned value is in
222     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
223     ///
224     /// This function is the inverse of [`offset`].
225     ///
226     /// [`offset`]: #method.offset
227     /// [`wrapping_offset_from`]: #method.wrapping_offset_from
228     ///
229     /// # Safety
230     ///
231     /// If any of the following conditions are violated, the result is Undefined
232     /// Behavior:
233     ///
234     /// * Both the starting and other pointer must be either in bounds or one
235     ///   byte past the end of the same allocated object. Note that in Rust,
236     ///   every (stack-allocated) variable is considered a separate allocated object.
237     ///
238     /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
239     ///
240     /// * The distance between the pointers, in bytes, must be an exact multiple
241     ///   of the size of `T`.
242     ///
243     /// * The distance being in bounds cannot rely on "wrapping around" the address space.
244     ///
245     /// The compiler and standard library generally try to ensure allocations
246     /// never reach a size where an offset is a concern. For instance, `Vec`
247     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
248     /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
249     ///
250     /// Most platforms fundamentally can't even construct such an allocation.
251     /// For instance, no known 64-bit platform can ever serve a request
252     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
253     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
254     /// more than `isize::MAX` bytes with things like Physical Address
255     /// Extension. As such, memory acquired directly from allocators or memory
256     /// mapped files *may* be too large to handle with this function.
257     ///
258     /// Consider using [`wrapping_offset_from`] instead if these constraints are
259     /// difficult to satisfy. The only advantage of this method is that it
260     /// enables more aggressive compiler optimizations.
261     ///
262     /// # Panics
263     ///
264     /// This function panics if `T` is a Zero-Sized Type ("ZST").
265     ///
266     /// # Examples
267     ///
268     /// Basic usage:
269     ///
270     /// ```
271     /// #![feature(ptr_offset_from)]
272     ///
273     /// let a = [0; 5];
274     /// let ptr1: *const i32 = &a[1];
275     /// let ptr2: *const i32 = &a[3];
276     /// unsafe {
277     ///     assert_eq!(ptr2.offset_from(ptr1), 2);
278     ///     assert_eq!(ptr1.offset_from(ptr2), -2);
279     ///     assert_eq!(ptr1.offset(2), ptr2);
280     ///     assert_eq!(ptr2.offset(-2), ptr1);
281     /// }
282     /// ```
283     #[unstable(feature = "ptr_offset_from", issue = "41079")]
284     #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")]
285     #[inline]
286     pub const unsafe fn offset_from(self, origin: *const T) -> isize
287     where
288         T: Sized,
289     {
290         let pointee_size = mem::size_of::<T>();
291         assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
292         intrinsics::ptr_offset_from(self, origin)
293     }
294
295     /// Calculates the distance between two pointers. The returned value is in
296     /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
297     ///
298     /// If the address different between the two pointers is not a multiple of
299     /// `mem::size_of::<T>()` then the result of the division is rounded towards
300     /// zero.
301     ///
302     /// Though this method is safe for any two pointers, note that its result
303     /// will be mostly useless if the two pointers aren't into the same allocated
304     /// object, for example if they point to two different local variables.
305     ///
306     /// # Panics
307     ///
308     /// This function panics if `T` is a zero-sized type.
309     ///
310     /// # Examples
311     ///
312     /// Basic usage:
313     ///
314     /// ```
315     /// #![feature(ptr_wrapping_offset_from)]
316     ///
317     /// let a = [0; 5];
318     /// let ptr1: *const i32 = &a[1];
319     /// let ptr2: *const i32 = &a[3];
320     /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
321     /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
322     /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
323     /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
324     ///
325     /// let ptr1: *const i32 = 3 as _;
326     /// let ptr2: *const i32 = 13 as _;
327     /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
328     /// ```
329     #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
330     #[inline]
331     pub fn wrapping_offset_from(self, origin: *const T) -> isize
332     where
333         T: Sized,
334     {
335         let pointee_size = mem::size_of::<T>();
336         assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
337
338         let d = isize::wrapping_sub(self as _, origin as _);
339         d.wrapping_div(pointee_size as _)
340     }
341
342     /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
343     ///
344     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
345     /// offset of `3 * size_of::<T>()` bytes.
346     ///
347     /// # Safety
348     ///
349     /// If any of the following conditions are violated, the result is Undefined
350     /// Behavior:
351     ///
352     /// * Both the starting and resulting pointer must be either in bounds or one
353     ///   byte past the end of the same allocated object. Note that in Rust,
354     ///   every (stack-allocated) variable is considered a separate allocated object.
355     ///
356     /// * The computed offset, **in bytes**, cannot overflow an `isize`.
357     ///
358     /// * The offset being in bounds cannot rely on "wrapping around" the address
359     ///   space. That is, the infinite-precision sum must fit in a `usize`.
360     ///
361     /// The compiler and standard library generally tries to ensure allocations
362     /// never reach a size where an offset is a concern. For instance, `Vec`
363     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
364     /// `vec.as_ptr().add(vec.len())` is always safe.
365     ///
366     /// Most platforms fundamentally can't even construct such an allocation.
367     /// For instance, no known 64-bit platform can ever serve a request
368     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
369     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
370     /// more than `isize::MAX` bytes with things like Physical Address
371     /// Extension. As such, memory acquired directly from allocators or memory
372     /// mapped files *may* be too large to handle with this function.
373     ///
374     /// Consider using [`wrapping_add`] instead if these constraints are
375     /// difficult to satisfy. The only advantage of this method is that it
376     /// enables more aggressive compiler optimizations.
377     ///
378     /// [`wrapping_add`]: #method.wrapping_add
379     ///
380     /// # Examples
381     ///
382     /// Basic usage:
383     ///
384     /// ```
385     /// let s: &str = "123";
386     /// let ptr: *const u8 = s.as_ptr();
387     ///
388     /// unsafe {
389     ///     println!("{}", *ptr.add(1) as char);
390     ///     println!("{}", *ptr.add(2) as char);
391     /// }
392     /// ```
393     #[stable(feature = "pointer_methods", since = "1.26.0")]
394     #[inline]
395     pub unsafe fn add(self, count: usize) -> Self
396     where
397         T: Sized,
398     {
399         self.offset(count as isize)
400     }
401
402     /// Calculates the offset from a pointer (convenience for
403     /// `.offset((count as isize).wrapping_neg())`).
404     ///
405     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
406     /// offset of `3 * size_of::<T>()` bytes.
407     ///
408     /// # Safety
409     ///
410     /// If any of the following conditions are violated, the result is Undefined
411     /// Behavior:
412     ///
413     /// * Both the starting and resulting pointer must be either in bounds or one
414     ///   byte past the end of the same allocated object. Note that in Rust,
415     ///   every (stack-allocated) variable is considered a separate allocated object.
416     ///
417     /// * The computed offset cannot exceed `isize::MAX` **bytes**.
418     ///
419     /// * The offset being in bounds cannot rely on "wrapping around" the address
420     ///   space. That is, the infinite-precision sum must fit in a usize.
421     ///
422     /// The compiler and standard library generally tries to ensure allocations
423     /// never reach a size where an offset is a concern. For instance, `Vec`
424     /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
425     /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
426     ///
427     /// Most platforms fundamentally can't even construct such an allocation.
428     /// For instance, no known 64-bit platform can ever serve a request
429     /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
430     /// However, some 32-bit and 16-bit platforms may successfully serve a request for
431     /// more than `isize::MAX` bytes with things like Physical Address
432     /// Extension. As such, memory acquired directly from allocators or memory
433     /// mapped files *may* be too large to handle with this function.
434     ///
435     /// Consider using [`wrapping_sub`] instead if these constraints are
436     /// difficult to satisfy. The only advantage of this method is that it
437     /// enables more aggressive compiler optimizations.
438     ///
439     /// [`wrapping_sub`]: #method.wrapping_sub
440     ///
441     /// # Examples
442     ///
443     /// Basic usage:
444     ///
445     /// ```
446     /// let s: &str = "123";
447     ///
448     /// unsafe {
449     ///     let end: *const u8 = s.as_ptr().add(3);
450     ///     println!("{}", *end.sub(1) as char);
451     ///     println!("{}", *end.sub(2) as char);
452     /// }
453     /// ```
454     #[stable(feature = "pointer_methods", since = "1.26.0")]
455     #[inline]
456     pub unsafe fn sub(self, count: usize) -> Self
457     where
458         T: Sized,
459     {
460         self.offset((count as isize).wrapping_neg())
461     }
462
463     /// Calculates the offset from a pointer using wrapping arithmetic.
464     /// (convenience for `.wrapping_offset(count as isize)`)
465     ///
466     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
467     /// offset of `3 * size_of::<T>()` bytes.
468     ///
469     /// # Safety
470     ///
471     /// The resulting pointer does not need to be in bounds, but it is
472     /// potentially hazardous to dereference (which requires `unsafe`).
473     ///
474     /// In particular, the resulting pointer remains attached to the same allocated
475     /// object that `self` points to. It may *not* be used to access a
476     /// different allocated object. Note that in Rust,
477     /// every (stack-allocated) variable is considered a separate allocated object.
478     ///
479     /// Compared to [`add`], this method basically delays the requirement of staying
480     /// within the same allocated object: [`add`] is immediate Undefined Behavior when
481     /// crossing object boundaries; `wrapping_add` produces a pointer but still leads
482     /// to Undefined Behavior if that pointer is dereferenced. [`add`] can be optimized
483     /// better and is thus preferable in performance-sensitive code.
484     ///
485     /// If you need to cross object boundaries, cast the pointer to an integer and
486     /// do the arithmetic there.
487     ///
488     /// [`add`]: #method.add
489     ///
490     /// # Examples
491     ///
492     /// Basic usage:
493     ///
494     /// ```
495     /// // Iterate using a raw pointer in increments of two elements
496     /// let data = [1u8, 2, 3, 4, 5];
497     /// let mut ptr: *const u8 = data.as_ptr();
498     /// let step = 2;
499     /// let end_rounded_up = ptr.wrapping_add(6);
500     ///
501     /// // This loop prints "1, 3, 5, "
502     /// while ptr != end_rounded_up {
503     ///     unsafe {
504     ///         print!("{}, ", *ptr);
505     ///     }
506     ///     ptr = ptr.wrapping_add(step);
507     /// }
508     /// ```
509     #[stable(feature = "pointer_methods", since = "1.26.0")]
510     #[inline]
511     pub fn wrapping_add(self, count: usize) -> Self
512     where
513         T: Sized,
514     {
515         self.wrapping_offset(count as isize)
516     }
517
518     /// Calculates the offset from a pointer using wrapping arithmetic.
519     /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
520     ///
521     /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
522     /// offset of `3 * size_of::<T>()` bytes.
523     ///
524     /// # Safety
525     ///
526     /// The resulting pointer does not need to be in bounds, but it is
527     /// potentially hazardous to dereference (which requires `unsafe`).
528     ///
529     /// In particular, the resulting pointer remains attached to the same allocated
530     /// object that `self` points to. It may *not* be used to access a
531     /// different allocated object. Note that in Rust,
532     /// every (stack-allocated) variable is considered a separate allocated object.
533     ///
534     /// Compared to [`sub`], this method basically delays the requirement of staying
535     /// within the same allocated object: [`sub`] is immediate Undefined Behavior when
536     /// crossing object boundaries; `wrapping_sub` produces a pointer but still leads
537     /// to Undefined Behavior if that pointer is dereferenced. [`sub`] can be optimized
538     /// better and is thus preferable in performance-sensitive code.
539     ///
540     /// If you need to cross object boundaries, cast the pointer to an integer and
541     /// do the arithmetic there.
542     ///
543     /// [`sub`]: #method.sub
544     ///
545     /// # Examples
546     ///
547     /// Basic usage:
548     ///
549     /// ```
550     /// // Iterate using a raw pointer in increments of two elements (backwards)
551     /// let data = [1u8, 2, 3, 4, 5];
552     /// let mut ptr: *const u8 = data.as_ptr();
553     /// let start_rounded_down = ptr.wrapping_sub(2);
554     /// ptr = ptr.wrapping_add(4);
555     /// let step = 2;
556     /// // This loop prints "5, 3, 1, "
557     /// while ptr != start_rounded_down {
558     ///     unsafe {
559     ///         print!("{}, ", *ptr);
560     ///     }
561     ///     ptr = ptr.wrapping_sub(step);
562     /// }
563     /// ```
564     #[stable(feature = "pointer_methods", since = "1.26.0")]
565     #[inline]
566     pub fn wrapping_sub(self, count: usize) -> Self
567     where
568         T: Sized,
569     {
570         self.wrapping_offset((count as isize).wrapping_neg())
571     }
572
573     /// Reads the value from `self` without moving it. This leaves the
574     /// memory in `self` unchanged.
575     ///
576     /// See [`ptr::read`] for safety concerns and examples.
577     ///
578     /// [`ptr::read`]: ./ptr/fn.read.html
579     #[stable(feature = "pointer_methods", since = "1.26.0")]
580     #[inline]
581     pub unsafe fn read(self) -> T
582     where
583         T: Sized,
584     {
585         read(self)
586     }
587
588     /// Performs a volatile read of the value from `self` without moving it. This
589     /// leaves the memory in `self` unchanged.
590     ///
591     /// Volatile operations are intended to act on I/O memory, and are guaranteed
592     /// to not be elided or reordered by the compiler across other volatile
593     /// operations.
594     ///
595     /// See [`ptr::read_volatile`] for safety concerns and examples.
596     ///
597     /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
598     #[stable(feature = "pointer_methods", since = "1.26.0")]
599     #[inline]
600     pub unsafe fn read_volatile(self) -> T
601     where
602         T: Sized,
603     {
604         read_volatile(self)
605     }
606
607     /// Reads the value from `self` without moving it. This leaves the
608     /// memory in `self` unchanged.
609     ///
610     /// Unlike `read`, the pointer may be unaligned.
611     ///
612     /// See [`ptr::read_unaligned`] for safety concerns and examples.
613     ///
614     /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
615     #[stable(feature = "pointer_methods", since = "1.26.0")]
616     #[inline]
617     pub unsafe fn read_unaligned(self) -> T
618     where
619         T: Sized,
620     {
621         read_unaligned(self)
622     }
623
624     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
625     /// and destination may overlap.
626     ///
627     /// NOTE: this has the *same* argument order as [`ptr::copy`].
628     ///
629     /// See [`ptr::copy`] for safety concerns and examples.
630     ///
631     /// [`ptr::copy`]: ./ptr/fn.copy.html
632     #[stable(feature = "pointer_methods", since = "1.26.0")]
633     #[inline]
634     pub unsafe fn copy_to(self, dest: *mut T, count: usize)
635     where
636         T: Sized,
637     {
638         copy(self, dest, count)
639     }
640
641     /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
642     /// and destination may *not* overlap.
643     ///
644     /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
645     ///
646     /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
647     ///
648     /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
649     #[stable(feature = "pointer_methods", since = "1.26.0")]
650     #[inline]
651     pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
652     where
653         T: Sized,
654     {
655         copy_nonoverlapping(self, dest, count)
656     }
657
658     /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
659     /// `align`.
660     ///
661     /// If it is not possible to align the pointer, the implementation returns
662     /// `usize::max_value()`. It is permissible for the implementation to *always*
663     /// return `usize::max_value()`. Only your algorithm's performance can depend
664     /// on getting a usable offset here, not its correctness.
665     ///
666     /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
667     /// used with the `wrapping_add` method.
668     ///
669     /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
670     /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
671     /// the returned offset is correct in all terms other than alignment.
672     ///
673     /// # Panics
674     ///
675     /// The function panics if `align` is not a power-of-two.
676     ///
677     /// # Examples
678     ///
679     /// Accessing adjacent `u8` as `u16`
680     ///
681     /// ```
682     /// # fn foo(n: usize) {
683     /// # use std::mem::align_of;
684     /// # unsafe {
685     /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
686     /// let ptr = &x[n] as *const u8;
687     /// let offset = ptr.align_offset(align_of::<u16>());
688     /// if offset < x.len() - n - 1 {
689     ///     let u16_ptr = ptr.add(offset) as *const u16;
690     ///     assert_ne!(*u16_ptr, 500);
691     /// } else {
692     ///     // while the pointer can be aligned via `offset`, it would point
693     ///     // outside the allocation
694     /// }
695     /// # } }
696     /// ```
697     #[stable(feature = "align_offset", since = "1.36.0")]
698     pub fn align_offset(self, align: usize) -> usize
699     where
700         T: Sized,
701     {
702         if !align.is_power_of_two() {
703             panic!("align_offset: align is not a power-of-two");
704         }
705         unsafe { align_offset(self, align) }
706     }
707 }
708
709 // Equality for pointers
710 #[stable(feature = "rust1", since = "1.0.0")]
711 impl<T: ?Sized> PartialEq for *const T {
712     #[inline]
713     fn eq(&self, other: &*const T) -> bool {
714         *self == *other
715     }
716 }
717
718 #[stable(feature = "rust1", since = "1.0.0")]
719 impl<T: ?Sized> Eq for *const T {}
720
721 // Comparison for pointers
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl<T: ?Sized> Ord for *const T {
724     #[inline]
725     fn cmp(&self, other: &*const T) -> Ordering {
726         if self < other {
727             Less
728         } else if self == other {
729             Equal
730         } else {
731             Greater
732         }
733     }
734 }
735
736 #[stable(feature = "rust1", since = "1.0.0")]
737 impl<T: ?Sized> PartialOrd for *const T {
738     #[inline]
739     fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
740         Some(self.cmp(other))
741     }
742
743     #[inline]
744     fn lt(&self, other: &*const T) -> bool {
745         *self < *other
746     }
747
748     #[inline]
749     fn le(&self, other: &*const T) -> bool {
750         *self <= *other
751     }
752
753     #[inline]
754     fn gt(&self, other: &*const T) -> bool {
755         *self > *other
756     }
757
758     #[inline]
759     fn ge(&self, other: &*const T) -> bool {
760         *self >= *other
761     }
762 }