2 use crate::cmp::Ordering::{self, Equal, Greater, Less};
6 // ignore-tidy-undocumented-unsafe
9 impl<T: ?Sized> *const T {
10 /// Returns `true` if the pointer is null.
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
22 /// let s: &str = "Follow the rabbit";
23 /// let ptr: *const u8 = s.as_ptr();
24 /// assert!(!ptr.is_null());
26 #[stable(feature = "rust1", since = "1.0.0")]
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()
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")]
38 pub const fn cast<U>(self) -> *const U {
42 /// Returns `None` if the pointer is null, or else returns a reference to
43 /// the value wrapped in `Some`.
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
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].
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.)
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`).
67 /// [here]: crate::ptr#safety
74 /// let ptr: *const u8 = &10u8 as *const u8;
77 /// if let Some(val_back) = ptr.as_ref() {
78 /// println!("We got back the value: {}!", val_back);
83 /// # Null-unchecked version
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.
90 /// let ptr: *const u8 = &10u8 as *const u8;
93 /// let val_back = &*ptr;
94 /// println!("We got back the value: {}!", val_back);
97 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
99 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
100 if self.is_null() { None } else { Some(&*self) }
103 /// Calculates the offset from a pointer.
105 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
106 /// offset of `3 * size_of::<T>()` bytes.
110 /// If any of the following conditions are violated, the result is Undefined
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.
117 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
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.
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.
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.
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.
139 /// [`wrapping_offset`]: #method.wrapping_offset
146 /// let s: &str = "123";
147 /// let ptr: *const u8 = s.as_ptr();
150 /// println!("{}", *ptr.offset(1) as char);
151 /// println!("{}", *ptr.offset(2) as char);
154 #[stable(feature = "rust1", since = "1.0.0")]
156 pub unsafe fn offset(self, count: isize) -> *const T
160 intrinsics::offset(self, count)
163 /// Calculates the offset from a pointer using wrapping arithmetic.
165 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
166 /// offset of `3 * size_of::<T>()` bytes.
170 /// The resulting pointer does not need to be in bounds, but it is
171 /// potentially hazardous to dereference (which requires `unsafe`).
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.
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.
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.
188 /// If you need to cross object boundaries, cast the pointer to an integer and
189 /// do the arithmetic there.
191 /// [`offset`]: #method.offset
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();
202 /// let end_rounded_up = ptr.wrapping_offset(6);
204 /// // This loop prints "1, 3, 5, "
205 /// while ptr != end_rounded_up {
207 /// print!("{}, ", *ptr);
209 /// ptr = ptr.wrapping_offset(step);
212 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
214 pub fn wrapping_offset(self, count: isize) -> *const T
218 unsafe { intrinsics::arith_offset(self, count) }
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>()`.
224 /// This function is the inverse of [`offset`].
226 /// [`offset`]: #method.offset
227 /// [`wrapping_offset_from`]: #method.wrapping_offset_from
231 /// If any of the following conditions are violated, the result is Undefined
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.
238 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
240 /// * The distance between the pointers, in bytes, must be an exact multiple
241 /// of the size of `T`.
243 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
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.
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.
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.
264 /// This function panics if `T` is a Zero-Sized Type ("ZST").
271 /// #![feature(ptr_offset_from)]
274 /// let ptr1: *const i32 = &a[1];
275 /// let ptr2: *const i32 = &a[3];
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);
283 #[unstable(feature = "ptr_offset_from", issue = "41079")]
284 #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")]
286 pub const unsafe fn offset_from(self, origin: *const T) -> isize
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)
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>()`.
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
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.
308 /// This function panics if `T` is a zero-sized type.
315 /// #![feature(ptr_wrapping_offset_from)]
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);
325 /// let ptr1: *const i32 = 3 as _;
326 /// let ptr2: *const i32 = 13 as _;
327 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
329 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
331 pub fn wrapping_offset_from(self, origin: *const T) -> isize
335 let pointee_size = mem::size_of::<T>();
336 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
338 let d = isize::wrapping_sub(self as _, origin as _);
339 d.wrapping_div(pointee_size as _)
342 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
344 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
345 /// offset of `3 * size_of::<T>()` bytes.
349 /// If any of the following conditions are violated, the result is Undefined
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.
356 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
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`.
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.
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.
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.
378 /// [`wrapping_add`]: #method.wrapping_add
385 /// let s: &str = "123";
386 /// let ptr: *const u8 = s.as_ptr();
389 /// println!("{}", *ptr.add(1) as char);
390 /// println!("{}", *ptr.add(2) as char);
393 #[stable(feature = "pointer_methods", since = "1.26.0")]
395 pub unsafe fn add(self, count: usize) -> Self
399 self.offset(count as isize)
402 /// Calculates the offset from a pointer (convenience for
403 /// `.offset((count as isize).wrapping_neg())`).
405 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
406 /// offset of `3 * size_of::<T>()` bytes.
410 /// If any of the following conditions are violated, the result is Undefined
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.
417 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
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.
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.
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.
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.
439 /// [`wrapping_sub`]: #method.wrapping_sub
446 /// let s: &str = "123";
449 /// let end: *const u8 = s.as_ptr().add(3);
450 /// println!("{}", *end.sub(1) as char);
451 /// println!("{}", *end.sub(2) as char);
454 #[stable(feature = "pointer_methods", since = "1.26.0")]
456 pub unsafe fn sub(self, count: usize) -> Self
460 self.offset((count as isize).wrapping_neg())
463 /// Calculates the offset from a pointer using wrapping arithmetic.
464 /// (convenience for `.wrapping_offset(count as isize)`)
466 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
467 /// offset of `3 * size_of::<T>()` bytes.
471 /// The resulting pointer does not need to be in bounds, but it is
472 /// potentially hazardous to dereference (which requires `unsafe`).
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.
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.
485 /// If you need to cross object boundaries, cast the pointer to an integer and
486 /// do the arithmetic there.
488 /// [`add`]: #method.add
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();
499 /// let end_rounded_up = ptr.wrapping_add(6);
501 /// // This loop prints "1, 3, 5, "
502 /// while ptr != end_rounded_up {
504 /// print!("{}, ", *ptr);
506 /// ptr = ptr.wrapping_add(step);
509 #[stable(feature = "pointer_methods", since = "1.26.0")]
511 pub fn wrapping_add(self, count: usize) -> Self
515 self.wrapping_offset(count as isize)
518 /// Calculates the offset from a pointer using wrapping arithmetic.
519 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
521 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
522 /// offset of `3 * size_of::<T>()` bytes.
526 /// The resulting pointer does not need to be in bounds, but it is
527 /// potentially hazardous to dereference (which requires `unsafe`).
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.
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.
540 /// If you need to cross object boundaries, cast the pointer to an integer and
541 /// do the arithmetic there.
543 /// [`sub`]: #method.sub
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);
556 /// // This loop prints "5, 3, 1, "
557 /// while ptr != start_rounded_down {
559 /// print!("{}, ", *ptr);
561 /// ptr = ptr.wrapping_sub(step);
564 #[stable(feature = "pointer_methods", since = "1.26.0")]
566 pub fn wrapping_sub(self, count: usize) -> Self
570 self.wrapping_offset((count as isize).wrapping_neg())
573 /// Reads the value from `self` without moving it. This leaves the
574 /// memory in `self` unchanged.
576 /// See [`ptr::read`] for safety concerns and examples.
578 /// [`ptr::read`]: ./ptr/fn.read.html
579 #[stable(feature = "pointer_methods", since = "1.26.0")]
581 pub unsafe fn read(self) -> T
588 /// Performs a volatile read of the value from `self` without moving it. This
589 /// leaves the memory in `self` unchanged.
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
595 /// See [`ptr::read_volatile`] for safety concerns and examples.
597 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
598 #[stable(feature = "pointer_methods", since = "1.26.0")]
600 pub unsafe fn read_volatile(self) -> T
607 /// Reads the value from `self` without moving it. This leaves the
608 /// memory in `self` unchanged.
610 /// Unlike `read`, the pointer may be unaligned.
612 /// See [`ptr::read_unaligned`] for safety concerns and examples.
614 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
615 #[stable(feature = "pointer_methods", since = "1.26.0")]
617 pub unsafe fn read_unaligned(self) -> T
624 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
625 /// and destination may overlap.
627 /// NOTE: this has the *same* argument order as [`ptr::copy`].
629 /// See [`ptr::copy`] for safety concerns and examples.
631 /// [`ptr::copy`]: ./ptr/fn.copy.html
632 #[stable(feature = "pointer_methods", since = "1.26.0")]
634 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
638 copy(self, dest, count)
641 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
642 /// and destination may *not* overlap.
644 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
646 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
648 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
649 #[stable(feature = "pointer_methods", since = "1.26.0")]
651 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
655 copy_nonoverlapping(self, dest, count)
658 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
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.
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.
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.
675 /// The function panics if `align` is not a power-of-two.
679 /// Accessing adjacent `u8` as `u16`
682 /// # fn foo(n: usize) {
683 /// # use std::mem::align_of;
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);
692 /// // while the pointer can be aligned via `offset`, it would point
693 /// // outside the allocation
697 #[stable(feature = "align_offset", since = "1.36.0")]
698 pub fn align_offset(self, align: usize) -> usize
702 if !align.is_power_of_two() {
703 panic!("align_offset: align is not a power-of-two");
705 unsafe { align_offset(self, align) }
709 // Equality for pointers
710 #[stable(feature = "rust1", since = "1.0.0")]
711 impl<T: ?Sized> PartialEq for *const T {
713 fn eq(&self, other: &*const T) -> bool {
718 #[stable(feature = "rust1", since = "1.0.0")]
719 impl<T: ?Sized> Eq for *const T {}
721 // Comparison for pointers
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl<T: ?Sized> Ord for *const T {
725 fn cmp(&self, other: &*const T) -> Ordering {
728 } else if self == other {
736 #[stable(feature = "rust1", since = "1.0.0")]
737 impl<T: ?Sized> PartialOrd for *const T {
739 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
740 Some(self.cmp(other))
744 fn lt(&self, other: &*const T) -> bool {
749 fn le(&self, other: &*const T) -> bool {
754 fn gt(&self, other: &*const T) -> bool {
759 fn ge(&self, other: &*const T) -> bool {