2 use crate::cmp::Ordering::{self, Equal, Greater, Less};
5 use crate::slice::{self, SliceIndex};
8 impl<T: ?Sized> *const T {
9 /// Returns `true` if the pointer is null.
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
21 /// let s: &str = "Follow the rabbit";
22 /// let ptr: *const u8 = s.as_ptr();
23 /// assert!(!ptr.is_null());
25 #[stable(feature = "rust1", since = "1.0.0")]
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()
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")]
37 pub const fn cast<U>(self) -> *const U {
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.
45 /// [`as_uninit_ref`]: #method.as_uninit_ref
49 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
50 /// all of the following is true:
52 /// * The pointer must be properly aligned.
54 /// * It must be "dereferencable" in the sense defined in [the module documentation].
56 /// * The pointer must point to an initialized instance of `T`.
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`).
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.)
67 /// [the module documentation]: 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 // 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) } }
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.
109 /// [`as_ref`]: #method.as_ref
113 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
114 /// all of the following is true:
116 /// * The pointer must be properly aligned.
118 /// * It must be "dereferencable" in the sense defined in [the module documentation].
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`).
125 /// This applies even if the result of this method is unused!
127 /// [the module documentation]: crate::ptr#safety
134 /// #![feature(ptr_as_uninit)]
136 /// let ptr: *const u8 = &10u8 as *const u8;
139 /// if let Some(val_back) = ptr.as_uninit_ref() {
140 /// println!("We got back the value: {}!", val_back.assume_init());
145 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
146 pub unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
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>) }) }
155 /// Calculates the offset from a pointer.
157 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
158 /// offset of `3 * size_of::<T>()` bytes.
162 /// If any of the following conditions are violated, the result is Undefined
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.
169 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
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.
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.
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.
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.
191 /// [`wrapping_offset`]: #method.wrapping_offset
198 /// let s: &str = "123";
199 /// let ptr: *const u8 = s.as_ptr();
202 /// println!("{}", *ptr.offset(1) as char);
203 /// println!("{}", *ptr.offset(2) as char);
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")]
210 pub const unsafe fn offset(self, count: isize) -> *const T
214 // SAFETY: the caller must uphold the safety contract for `offset`.
215 unsafe { intrinsics::offset(self, count) }
218 /// Calculates the offset from a pointer using wrapping arithmetic.
220 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
221 /// offset of `3 * size_of::<T>()` bytes.
225 /// The resulting pointer does not need to be in bounds, but it is
226 /// potentially hazardous to dereference (which requires `unsafe`).
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.
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.
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.
243 /// If you need to cross object boundaries, cast the pointer to an integer and
244 /// do the arithmetic there.
246 /// [`offset`]: #method.offset
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();
257 /// let end_rounded_up = ptr.wrapping_offset(6);
259 /// // This loop prints "1, 3, 5, "
260 /// while ptr != end_rounded_up {
262 /// print!("{}, ", *ptr);
264 /// ptr = ptr.wrapping_offset(step);
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")]
271 pub const fn wrapping_offset(self, count: isize) -> *const T
275 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
276 unsafe { intrinsics::arith_offset(self, count) }
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>()`.
282 /// This function is the inverse of [`offset`].
284 /// [`offset`]: #method.offset
285 /// [`wrapping_offset_from`]: #method.wrapping_offset_from
289 /// If any of the following conditions are violated, the result is Undefined
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.
296 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
298 /// * The distance between the pointers, in bytes, must be an exact multiple
299 /// of the size of `T`.
301 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
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.
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.
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.
322 /// This function panics if `T` is a Zero-Sized Type ("ZST").
329 /// #![feature(ptr_offset_from)]
332 /// let ptr1: *const i32 = &a[1];
333 /// let ptr2: *const i32 = &a[3];
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);
341 #[unstable(feature = "ptr_offset_from", issue = "41079")]
342 #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")]
344 pub const unsafe fn offset_from(self, origin: *const T) -> isize
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) }
354 /// Returns whether two pointers are guaranteed to be equal.
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.
362 /// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
363 /// comparisons for which both functions return `false`.
365 /// [`guaranteed_ne`]: #method.guaranteed_ne
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
375 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
376 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
378 pub const fn guaranteed_eq(self, other: *const T) -> bool
382 intrinsics::ptr_guaranteed_eq(self, other)
385 /// Returns whether two pointers are guaranteed to be unequal.
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.
393 /// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
394 /// comparisons for which both functions return `false`.
396 /// [`guaranteed_eq`]: #method.guaranteed_eq
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
406 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
407 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
409 pub const fn guaranteed_ne(self, other: *const T) -> bool
413 intrinsics::ptr_guaranteed_ne(self, other)
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>()`.
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
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.
429 /// This function panics if `T` is a zero-sized type.
436 /// #![feature(ptr_wrapping_offset_from)]
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);
446 /// let ptr1: *const i32 = 3 as _;
447 /// let ptr2: *const i32 = 13 as _;
448 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
450 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
453 reason = "Pointer distances across allocation \
454 boundaries are not typically meaningful. \
455 Use integer subtraction if you really need this."
458 pub fn wrapping_offset_from(self, origin: *const T) -> isize
462 let pointee_size = mem::size_of::<T>();
463 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
465 let d = isize::wrapping_sub(self as _, origin as _);
466 d.wrapping_div(pointee_size as _)
469 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
471 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
472 /// offset of `3 * size_of::<T>()` bytes.
476 /// If any of the following conditions are violated, the result is Undefined
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.
483 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
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`.
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.
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.
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.
505 /// [`wrapping_add`]: #method.wrapping_add
512 /// let s: &str = "123";
513 /// let ptr: *const u8 = s.as_ptr();
516 /// println!("{}", *ptr.add(1) as char);
517 /// println!("{}", *ptr.add(2) as char);
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")]
524 pub const unsafe fn add(self, count: usize) -> Self
528 // SAFETY: the caller must uphold the safety contract for `offset`.
529 unsafe { self.offset(count as isize) }
532 /// Calculates the offset from a pointer (convenience for
533 /// `.offset((count as isize).wrapping_neg())`).
535 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
536 /// offset of `3 * size_of::<T>()` bytes.
540 /// If any of the following conditions are violated, the result is Undefined
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.
547 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
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.
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.
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.
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.
569 /// [`wrapping_sub`]: #method.wrapping_sub
576 /// let s: &str = "123";
579 /// let end: *const u8 = s.as_ptr().add(3);
580 /// println!("{}", *end.sub(1) as char);
581 /// println!("{}", *end.sub(2) as char);
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")]
588 pub const unsafe fn sub(self, count: usize) -> Self
592 // SAFETY: the caller must uphold the safety contract for `offset`.
593 unsafe { self.offset((count as isize).wrapping_neg()) }
596 /// Calculates the offset from a pointer using wrapping arithmetic.
597 /// (convenience for `.wrapping_offset(count as isize)`)
599 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
600 /// offset of `3 * size_of::<T>()` bytes.
604 /// The resulting pointer does not need to be in bounds, but it is
605 /// potentially hazardous to dereference (which requires `unsafe`).
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.
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.
618 /// If you need to cross object boundaries, cast the pointer to an integer and
619 /// do the arithmetic there.
621 /// [`add`]: #method.add
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();
632 /// let end_rounded_up = ptr.wrapping_add(6);
634 /// // This loop prints "1, 3, 5, "
635 /// while ptr != end_rounded_up {
637 /// print!("{}, ", *ptr);
639 /// ptr = ptr.wrapping_add(step);
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")]
646 pub const fn wrapping_add(self, count: usize) -> Self
650 self.wrapping_offset(count as isize)
653 /// Calculates the offset from a pointer using wrapping arithmetic.
654 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
656 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
657 /// offset of `3 * size_of::<T>()` bytes.
661 /// The resulting pointer does not need to be in bounds, but it is
662 /// potentially hazardous to dereference (which requires `unsafe`).
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.
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.
675 /// If you need to cross object boundaries, cast the pointer to an integer and
676 /// do the arithmetic there.
678 /// [`sub`]: #method.sub
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);
691 /// // This loop prints "5, 3, 1, "
692 /// while ptr != start_rounded_down {
694 /// print!("{}, ", *ptr);
696 /// ptr = ptr.wrapping_sub(step);
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")]
703 pub const fn wrapping_sub(self, count: usize) -> Self
707 self.wrapping_offset((count as isize).wrapping_neg())
710 /// Sets the pointer value to `ptr`.
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.
718 /// This function is primarily useful for allowing byte-wise pointer
719 /// arithmetic on potentially fat pointers:
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);
730 #[unstable(feature = "set_ptr_value", issue = "75091")]
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 };
742 /// Reads the value from `self` without moving it. This leaves the
743 /// memory in `self` unchanged.
745 /// See [`ptr::read`] for safety concerns and examples.
747 /// [`ptr::read`]: ./ptr/fn.read.html
748 #[stable(feature = "pointer_methods", since = "1.26.0")]
750 pub unsafe fn read(self) -> T
754 // SAFETY: the caller must uphold the safety contract for `read`.
755 unsafe { read(self) }
758 /// Performs a volatile read of the value from `self` without moving it. This
759 /// leaves the memory in `self` unchanged.
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
765 /// See [`ptr::read_volatile`] for safety concerns and examples.
767 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
768 #[stable(feature = "pointer_methods", since = "1.26.0")]
770 pub unsafe fn read_volatile(self) -> T
774 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
775 unsafe { read_volatile(self) }
778 /// Reads the value from `self` without moving it. This leaves the
779 /// memory in `self` unchanged.
781 /// Unlike `read`, the pointer may be unaligned.
783 /// See [`ptr::read_unaligned`] for safety concerns and examples.
785 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
786 #[stable(feature = "pointer_methods", since = "1.26.0")]
788 pub unsafe fn read_unaligned(self) -> T
792 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
793 unsafe { read_unaligned(self) }
796 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
797 /// and destination may overlap.
799 /// NOTE: this has the *same* argument order as [`ptr::copy`].
801 /// See [`ptr::copy`] for safety concerns and examples.
803 /// [`ptr::copy`]: ./ptr/fn.copy.html
804 #[stable(feature = "pointer_methods", since = "1.26.0")]
806 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
810 // SAFETY: the caller must uphold the safety contract for `copy`.
811 unsafe { copy(self, dest, count) }
814 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
815 /// and destination may *not* overlap.
817 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
819 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
821 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
822 #[stable(feature = "pointer_methods", since = "1.26.0")]
824 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
828 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
829 unsafe { copy_nonoverlapping(self, dest, count) }
832 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
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.
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.
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.
849 /// The function panics if `align` is not a power-of-two.
853 /// Accessing adjacent `u8` as `u16`
856 /// # fn foo(n: usize) {
857 /// # use std::mem::align_of;
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);
866 /// // while the pointer can be aligned via `offset`, it would point
867 /// // outside the allocation
871 #[stable(feature = "align_offset", since = "1.36.0")]
872 pub fn align_offset(self, align: usize) -> usize
876 if !align.is_power_of_two() {
877 panic!("align_offset: align is not a power-of-two");
879 // SAFETY: `align` has been checked to be a power of 2 above
880 unsafe { align_offset(self, align) }
884 #[lang = "const_slice_ptr"]
886 /// Returns the length of a raw slice.
888 /// The returned value is the number of **elements**, not the number of bytes.
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.
896 /// #![feature(slice_ptr_len)]
900 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
901 /// assert_eq!(slice.len(), 3);
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
912 /// Returns a raw pointer to the slice's buffer.
914 /// This is equivalent to casting `self` to `*const T`, but more type-safe.
919 /// #![feature(slice_ptr_get)]
922 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
923 /// assert_eq!(slice.as_ptr(), 0 as *const i8);
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 {
932 /// Returns a raw pointer to an element or subslice, without doing bounds
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.
938 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
943 /// #![feature(slice_ptr_get)]
945 /// let x = &[1, 2, 4] as *const [i32];
948 /// assert_eq!(x.get_unchecked(1), x.as_ptr().add(1));
951 #[unstable(feature = "slice_ptr_get", issue = "74265")]
953 pub unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output
957 // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
958 unsafe { index.get_unchecked(self) }
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.
965 /// [`as_ref`]: #method.as_ref
969 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
970 /// all of the following is true:
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:
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.
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()`].
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`].
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`).
992 /// This applies even if the result of this method is unused!
994 /// See also [`slice::from_raw_parts`][].
996 /// [valid]: crate::ptr#safety
997 /// [`NonNull::dangling()`]: NonNull::dangling
998 /// [`pointer::offset`]: ../std/primitive.pointer.html#method.offset
1000 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1001 pub unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
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()) })
1011 // Equality for pointers
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 impl<T: ?Sized> PartialEq for *const T {
1015 fn eq(&self, other: &*const T) -> bool {
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<T: ?Sized> Eq for *const T {}
1023 // Comparison for pointers
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl<T: ?Sized> Ord for *const T {
1027 fn cmp(&self, other: &*const T) -> Ordering {
1030 } else if self == other {
1038 #[stable(feature = "rust1", since = "1.0.0")]
1039 impl<T: ?Sized> PartialOrd for *const T {
1041 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
1042 Some(self.cmp(other))
1046 fn lt(&self, other: &*const T) -> bool {
1051 fn le(&self, other: &*const T) -> bool {
1056 fn gt(&self, other: &*const T) -> bool {
1061 fn ge(&self, other: &*const T) -> bool {