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
16 /// ## Behavior during const evaluation
18 /// When this function is used during const evaluation, it may return `false` for pointers
19 /// that turn out to be null at runtime. Specifically, when a pointer to some memory
20 /// is offset beyond its bounds in such a way that the resulting pointer is null,
21 /// the function will still return `false`. There is no way for CTFE to know
22 /// the absolute position of that memory, so we cannot tell if the pointer is
30 /// let s: &str = "Follow the rabbit";
31 /// let ptr: *const u8 = s.as_ptr();
32 /// assert!(!ptr.is_null());
34 #[stable(feature = "rust1", since = "1.0.0")]
35 #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")]
37 pub const fn is_null(self) -> bool {
38 // Compare via a cast to a thin pointer, so fat pointers are only
39 // considering their "data" part for null-ness.
40 (self as *const u8).guaranteed_eq(null())
43 /// Casts to a pointer of another type.
44 #[stable(feature = "ptr_cast", since = "1.38.0")]
45 #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
47 pub const fn cast<U>(self) -> *const U {
51 /// Decompose a (possibly wide) pointer into is address and metadata components.
53 /// The pointer can be later reconstructed with [`from_raw_parts`].
54 #[cfg(not(bootstrap))]
55 #[unstable(feature = "ptr_metadata", issue = "81513")]
56 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
58 pub const fn to_raw_parts(self) -> (*const (), <T as super::Pointee>::Metadata) {
59 (self.cast(), super::metadata(self))
62 /// Returns `None` if the pointer is null, or else returns a shared reference to
63 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
64 /// must be used instead.
66 /// [`as_uninit_ref`]: #method.as_uninit_ref
70 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
71 /// all of the following is true:
73 /// * The pointer must be properly aligned.
75 /// * It must be "dereferencable" in the sense defined in [the module documentation].
77 /// * The pointer must point to an initialized instance of `T`.
79 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
80 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
81 /// In particular, for the duration of this lifetime, the memory the pointer points to must
82 /// not get mutated (except inside `UnsafeCell`).
84 /// This applies even if the result of this method is unused!
85 /// (The part about being initialized is not yet fully decided, but until
86 /// it is, the only safe approach is to ensure that they are indeed initialized.)
88 /// [the module documentation]: crate::ptr#safety
95 /// let ptr: *const u8 = &10u8 as *const u8;
98 /// if let Some(val_back) = ptr.as_ref() {
99 /// println!("We got back the value: {}!", val_back);
104 /// # Null-unchecked version
106 /// If you are sure the pointer can never be null and are looking for some kind of
107 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
108 /// dereference the pointer directly.
111 /// let ptr: *const u8 = &10u8 as *const u8;
114 /// let val_back = &*ptr;
115 /// println!("We got back the value: {}!", val_back);
118 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
120 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
121 // SAFETY: the caller must guarantee that `self` is valid
122 // for a reference if it isn't null.
123 if self.is_null() { None } else { unsafe { Some(&*self) } }
126 /// Returns `None` if the pointer is null, or else returns a shared reference to
127 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
128 /// that the value has to be initialized.
130 /// [`as_ref`]: #method.as_ref
134 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
135 /// all of the following is true:
137 /// * The pointer must be properly aligned.
139 /// * It must be "dereferencable" in the sense defined in [the module documentation].
141 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
142 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
143 /// In particular, for the duration of this lifetime, the memory the pointer points to must
144 /// not get mutated (except inside `UnsafeCell`).
146 /// This applies even if the result of this method is unused!
148 /// [the module documentation]: crate::ptr#safety
155 /// #![feature(ptr_as_uninit)]
157 /// let ptr: *const u8 = &10u8 as *const u8;
160 /// if let Some(val_back) = ptr.as_uninit_ref() {
161 /// println!("We got back the value: {}!", val_back.assume_init());
166 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
167 pub unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
171 // SAFETY: the caller must guarantee that `self` meets all the
172 // requirements for a reference.
173 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
176 /// Calculates the offset from a pointer.
178 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
179 /// offset of `3 * size_of::<T>()` bytes.
183 /// If any of the following conditions are violated, the result is Undefined
186 /// * Both the starting and resulting pointer must be either in bounds or one
187 /// byte past the end of the same allocated object. Note that in Rust,
188 /// every (stack-allocated) variable is considered a separate allocated object.
190 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
192 /// * The offset being in bounds cannot rely on "wrapping around" the address
193 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
195 /// The compiler and standard library generally tries to ensure allocations
196 /// never reach a size where an offset is a concern. For instance, `Vec`
197 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
198 /// `vec.as_ptr().add(vec.len())` is always safe.
200 /// Most platforms fundamentally can't even construct such an allocation.
201 /// For instance, no known 64-bit platform can ever serve a request
202 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
203 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
204 /// more than `isize::MAX` bytes with things like Physical Address
205 /// Extension. As such, memory acquired directly from allocators or memory
206 /// mapped files *may* be too large to handle with this function.
208 /// Consider using [`wrapping_offset`] instead if these constraints are
209 /// difficult to satisfy. The only advantage of this method is that it
210 /// enables more aggressive compiler optimizations.
212 /// [`wrapping_offset`]: #method.wrapping_offset
219 /// let s: &str = "123";
220 /// let ptr: *const u8 = s.as_ptr();
223 /// println!("{}", *ptr.offset(1) as char);
224 /// println!("{}", *ptr.offset(2) as char);
227 #[stable(feature = "rust1", since = "1.0.0")]
228 #[must_use = "returns a new pointer rather than modifying its argument"]
229 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
231 pub const unsafe fn offset(self, count: isize) -> *const T
235 // SAFETY: the caller must uphold the safety contract for `offset`.
236 unsafe { intrinsics::offset(self, count) }
239 /// Calculates the offset from a pointer using wrapping arithmetic.
241 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
242 /// offset of `3 * size_of::<T>()` bytes.
246 /// This operation itself is always safe, but using the resulting pointer is not.
248 /// The resulting pointer remains attached to the same allocated object that `self` points to.
249 /// It may *not* be used to access a different allocated object. Note that in Rust, every
250 /// (stack-allocated) variable is considered a separate allocated object.
252 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
253 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
254 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
255 /// `x` and `y` point into the same allocated object.
257 /// Compared to [`offset`], this method basically delays the requirement of staying within the
258 /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
259 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
260 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
261 /// can be optimized better and is thus preferable in performance-sensitive code.
263 /// The delayed check only considers the value of the pointer that was dereferenced, not the
264 /// intermediate values used during the computation of the final result. For example,
265 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
266 /// words, leaving the allocated object and then re-entering it later is permitted.
268 /// If you need to cross object boundaries, cast the pointer to an integer and
269 /// do the arithmetic there.
271 /// [`offset`]: #method.offset
278 /// // Iterate using a raw pointer in increments of two elements
279 /// let data = [1u8, 2, 3, 4, 5];
280 /// let mut ptr: *const u8 = data.as_ptr();
282 /// let end_rounded_up = ptr.wrapping_offset(6);
284 /// // This loop prints "1, 3, 5, "
285 /// while ptr != end_rounded_up {
287 /// print!("{}, ", *ptr);
289 /// ptr = ptr.wrapping_offset(step);
292 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
293 #[must_use = "returns a new pointer rather than modifying its argument"]
294 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
296 pub const fn wrapping_offset(self, count: isize) -> *const T
300 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
301 unsafe { intrinsics::arith_offset(self, count) }
304 /// Calculates the distance between two pointers. The returned value is in
305 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
307 /// This function is the inverse of [`offset`].
309 /// [`offset`]: #method.offset
313 /// If any of the following conditions are violated, the result is Undefined
316 /// * Both the starting and other pointer must be either in bounds or one
317 /// byte past the end of the same allocated object. Note that in Rust,
318 /// every (stack-allocated) variable is considered a separate allocated object.
320 /// * Both pointers must be *derived from* a pointer to the same object.
321 /// (See below for an example.)
323 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
325 /// * The distance between the pointers, in bytes, must be an exact multiple
326 /// of the size of `T`.
328 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
330 /// The compiler and standard library generally try to ensure allocations
331 /// never reach a size where an offset is a concern. For instance, `Vec`
332 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
333 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
335 /// Most platforms fundamentally can't even construct such an allocation.
336 /// For instance, no known 64-bit platform can ever serve a request
337 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
338 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
339 /// more than `isize::MAX` bytes with things like Physical Address
340 /// Extension. As such, memory acquired directly from allocators or memory
341 /// mapped files *may* be too large to handle with this function.
345 /// This function panics if `T` is a Zero-Sized Type ("ZST").
353 /// let ptr1: *const i32 = &a[1];
354 /// let ptr2: *const i32 = &a[3];
356 /// assert_eq!(ptr2.offset_from(ptr1), 2);
357 /// assert_eq!(ptr1.offset_from(ptr2), -2);
358 /// assert_eq!(ptr1.offset(2), ptr2);
359 /// assert_eq!(ptr2.offset(-2), ptr1);
363 /// *Incorrect* usage:
366 /// let ptr1 = Box::into_raw(Box::new(0u8)) as *const u8;
367 /// let ptr2 = Box::into_raw(Box::new(1u8)) as *const u8;
368 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
369 /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
370 /// let ptr2_other = (ptr1 as *const u8).wrapping_offset(diff);
371 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
372 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
373 /// // computing their offset is undefined behavior, even though
374 /// // they point to the same address!
376 /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
379 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
380 #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")]
382 pub const unsafe fn offset_from(self, origin: *const T) -> isize
386 let pointee_size = mem::size_of::<T>();
387 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
388 // SAFETY: the caller must uphold the safety contract for `ptr_offset_from`.
389 unsafe { intrinsics::ptr_offset_from(self, origin) }
392 /// Returns whether two pointers are guaranteed to be equal.
394 /// At runtime this function behaves like `self == other`.
395 /// However, in some contexts (e.g., compile-time evaluation),
396 /// it is not always possible to determine equality of two pointers, so this function may
397 /// spuriously return `false` for pointers that later actually turn out to be equal.
398 /// But when it returns `true`, the pointers are guaranteed to be equal.
400 /// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
401 /// comparisons for which both functions return `false`.
403 /// [`guaranteed_ne`]: #method.guaranteed_ne
405 /// The return value may change depending on the compiler version and unsafe code may not
406 /// rely on the result of this function for soundness. It is suggested to only use this function
407 /// for performance optimizations where spurious `false` return values by this function do not
408 /// affect the outcome, but just the performance.
409 /// The consequences of using this method to make runtime and compile-time code behave
410 /// differently have not been explored. This method should not be used to introduce such
411 /// differences, and it should also not be stabilized before we have a better understanding
413 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
414 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
416 pub const fn guaranteed_eq(self, other: *const T) -> bool
420 intrinsics::ptr_guaranteed_eq(self, other)
423 /// Returns whether two pointers are guaranteed to be unequal.
425 /// At runtime this function behaves like `self != other`.
426 /// However, in some contexts (e.g., compile-time evaluation),
427 /// it is not always possible to determine the inequality of two pointers, so this function may
428 /// spuriously return `false` for pointers that later actually turn out to be unequal.
429 /// But when it returns `true`, the pointers are guaranteed to be unequal.
431 /// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
432 /// comparisons for which both functions return `false`.
434 /// [`guaranteed_eq`]: #method.guaranteed_eq
436 /// The return value may change depending on the compiler version and unsafe code may not
437 /// rely on the result of this function for soundness. It is suggested to only use this function
438 /// for performance optimizations where spurious `false` return values by this function do not
439 /// affect the outcome, but just the performance.
440 /// The consequences of using this method to make runtime and compile-time code behave
441 /// differently have not been explored. This method should not be used to introduce such
442 /// differences, and it should also not be stabilized before we have a better understanding
444 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
445 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
447 pub const fn guaranteed_ne(self, other: *const T) -> bool
451 intrinsics::ptr_guaranteed_ne(self, other)
454 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
456 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
457 /// offset of `3 * size_of::<T>()` bytes.
461 /// If any of the following conditions are violated, the result is Undefined
464 /// * Both the starting and resulting pointer must be either in bounds or one
465 /// byte past the end of the same allocated object. Note that in Rust,
466 /// every (stack-allocated) variable is considered a separate allocated object.
468 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
470 /// * The offset being in bounds cannot rely on "wrapping around" the address
471 /// space. That is, the infinite-precision sum must fit in a `usize`.
473 /// The compiler and standard library generally tries to ensure allocations
474 /// never reach a size where an offset is a concern. For instance, `Vec`
475 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
476 /// `vec.as_ptr().add(vec.len())` is always safe.
478 /// Most platforms fundamentally can't even construct such an allocation.
479 /// For instance, no known 64-bit platform can ever serve a request
480 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
481 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
482 /// more than `isize::MAX` bytes with things like Physical Address
483 /// Extension. As such, memory acquired directly from allocators or memory
484 /// mapped files *may* be too large to handle with this function.
486 /// Consider using [`wrapping_add`] instead if these constraints are
487 /// difficult to satisfy. The only advantage of this method is that it
488 /// enables more aggressive compiler optimizations.
490 /// [`wrapping_add`]: #method.wrapping_add
497 /// let s: &str = "123";
498 /// let ptr: *const u8 = s.as_ptr();
501 /// println!("{}", *ptr.add(1) as char);
502 /// println!("{}", *ptr.add(2) as char);
505 #[stable(feature = "pointer_methods", since = "1.26.0")]
506 #[must_use = "returns a new pointer rather than modifying its argument"]
507 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
509 pub const unsafe fn add(self, count: usize) -> Self
513 // SAFETY: the caller must uphold the safety contract for `offset`.
514 unsafe { self.offset(count as isize) }
517 /// Calculates the offset from a pointer (convenience for
518 /// `.offset((count as isize).wrapping_neg())`).
520 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
521 /// offset of `3 * size_of::<T>()` bytes.
525 /// If any of the following conditions are violated, the result is Undefined
528 /// * Both the starting and resulting pointer must be either in bounds or one
529 /// byte past the end of the same allocated object. Note that in Rust,
530 /// every (stack-allocated) variable is considered a separate allocated object.
532 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
534 /// * The offset being in bounds cannot rely on "wrapping around" the address
535 /// space. That is, the infinite-precision sum must fit in a usize.
537 /// The compiler and standard library generally tries to ensure allocations
538 /// never reach a size where an offset is a concern. For instance, `Vec`
539 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
540 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
542 /// Most platforms fundamentally can't even construct such an allocation.
543 /// For instance, no known 64-bit platform can ever serve a request
544 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
545 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
546 /// more than `isize::MAX` bytes with things like Physical Address
547 /// Extension. As such, memory acquired directly from allocators or memory
548 /// mapped files *may* be too large to handle with this function.
550 /// Consider using [`wrapping_sub`] instead if these constraints are
551 /// difficult to satisfy. The only advantage of this method is that it
552 /// enables more aggressive compiler optimizations.
554 /// [`wrapping_sub`]: #method.wrapping_sub
561 /// let s: &str = "123";
564 /// let end: *const u8 = s.as_ptr().add(3);
565 /// println!("{}", *end.sub(1) as char);
566 /// println!("{}", *end.sub(2) as char);
569 #[stable(feature = "pointer_methods", since = "1.26.0")]
570 #[must_use = "returns a new pointer rather than modifying its argument"]
571 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
573 pub const unsafe fn sub(self, count: usize) -> Self
577 // SAFETY: the caller must uphold the safety contract for `offset`.
578 unsafe { self.offset((count as isize).wrapping_neg()) }
581 /// Calculates the offset from a pointer using wrapping arithmetic.
582 /// (convenience for `.wrapping_offset(count as isize)`)
584 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
585 /// offset of `3 * size_of::<T>()` bytes.
589 /// This operation itself is always safe, but using the resulting pointer is not.
591 /// The resulting pointer remains attached to the same allocated object that `self` points to.
592 /// It may *not* be used to access a different allocated object. Note that in Rust, every
593 /// (stack-allocated) variable is considered a separate allocated object.
595 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
596 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
597 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
598 /// `x` and `y` point into the same allocated object.
600 /// Compared to [`add`], this method basically delays the requirement of staying within the
601 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
602 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
603 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
604 /// can be optimized better and is thus preferable in performance-sensitive code.
606 /// The delayed check only considers the value of the pointer that was dereferenced, not the
607 /// intermediate values used during the computation of the final result. For example,
608 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
609 /// allocated object and then re-entering it later is permitted.
611 /// If you need to cross object boundaries, cast the pointer to an integer and
612 /// do the arithmetic there.
614 /// [`add`]: #method.add
621 /// // Iterate using a raw pointer in increments of two elements
622 /// let data = [1u8, 2, 3, 4, 5];
623 /// let mut ptr: *const u8 = data.as_ptr();
625 /// let end_rounded_up = ptr.wrapping_add(6);
627 /// // This loop prints "1, 3, 5, "
628 /// while ptr != end_rounded_up {
630 /// print!("{}, ", *ptr);
632 /// ptr = ptr.wrapping_add(step);
635 #[stable(feature = "pointer_methods", since = "1.26.0")]
636 #[must_use = "returns a new pointer rather than modifying its argument"]
637 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
639 pub const fn wrapping_add(self, count: usize) -> Self
643 self.wrapping_offset(count as isize)
646 /// Calculates the offset from a pointer using wrapping arithmetic.
647 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
649 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
650 /// offset of `3 * size_of::<T>()` bytes.
654 /// This operation itself is always safe, but using the resulting pointer is not.
656 /// The resulting pointer remains attached to the same allocated object that `self` points to.
657 /// It may *not* be used to access a different allocated object. Note that in Rust, every
658 /// (stack-allocated) variable is considered a separate allocated object.
660 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
661 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
662 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
663 /// `x` and `y` point into the same allocated object.
665 /// Compared to [`sub`], this method basically delays the requirement of staying within the
666 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
667 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
668 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
669 /// can be optimized better and is thus preferable in performance-sensitive code.
671 /// The delayed check only considers the value of the pointer that was dereferenced, not the
672 /// intermediate values used during the computation of the final result. For example,
673 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
674 /// allocated object and then re-entering it later is permitted.
676 /// If you need to cross object boundaries, cast the pointer to an integer and
677 /// do the arithmetic there.
679 /// [`sub`]: #method.sub
686 /// // Iterate using a raw pointer in increments of two elements (backwards)
687 /// let data = [1u8, 2, 3, 4, 5];
688 /// let mut ptr: *const u8 = data.as_ptr();
689 /// let start_rounded_down = ptr.wrapping_sub(2);
690 /// ptr = ptr.wrapping_add(4);
692 /// // This loop prints "5, 3, 1, "
693 /// while ptr != start_rounded_down {
695 /// print!("{}, ", *ptr);
697 /// ptr = ptr.wrapping_sub(step);
700 #[stable(feature = "pointer_methods", since = "1.26.0")]
701 #[must_use = "returns a new pointer rather than modifying its argument"]
702 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
704 pub const fn wrapping_sub(self, count: usize) -> Self
708 self.wrapping_offset((count as isize).wrapping_neg())
711 /// Sets the pointer value to `ptr`.
713 /// In case `self` is a (fat) pointer to an unsized type, this operation
714 /// will only affect the pointer part, whereas for (thin) pointers to
715 /// sized types, this has the same effect as a simple assignment.
717 /// The resulting pointer will have provenance of `val`, i.e., for a fat
718 /// pointer, this operation is semantically the same as creating a new
719 /// fat pointer with the data pointer value of `val` but the metadata of
724 /// This function is primarily useful for allowing byte-wise pointer
725 /// arithmetic on potentially fat pointers:
728 /// #![feature(set_ptr_value)]
729 /// # use core::fmt::Debug;
730 /// let arr: [i32; 3] = [1, 2, 3];
731 /// let mut ptr = &arr[0] as *const dyn Debug;
732 /// let thin = ptr as *const u8;
734 /// ptr = ptr.set_ptr_value(thin.add(8));
735 /// # assert_eq!(*(ptr as *const i32), 3);
736 /// println!("{:?}", &*ptr); // will print "3"
739 #[unstable(feature = "set_ptr_value", issue = "75091")]
740 #[must_use = "returns a new pointer rather than modifying its argument"]
742 pub fn set_ptr_value(mut self, val: *const u8) -> Self {
743 let thin = &mut self as *mut *const T as *mut *const u8;
744 // SAFETY: In case of a thin pointer, this operations is identical
745 // to a simple assignment. In case of a fat pointer, with the current
746 // fat pointer layout implementation, the first field of such a
747 // pointer is always the data pointer, which is likewise assigned.
748 unsafe { *thin = val };
752 /// Reads the value from `self` without moving it. This leaves the
753 /// memory in `self` unchanged.
755 /// See [`ptr::read`] for safety concerns and examples.
757 /// [`ptr::read`]: crate::ptr::read()
758 #[stable(feature = "pointer_methods", since = "1.26.0")]
759 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
761 pub const unsafe fn read(self) -> T
765 // SAFETY: the caller must uphold the safety contract for `read`.
766 unsafe { read(self) }
769 /// Performs a volatile read of the value from `self` without moving it. This
770 /// leaves the memory in `self` unchanged.
772 /// Volatile operations are intended to act on I/O memory, and are guaranteed
773 /// to not be elided or reordered by the compiler across other volatile
776 /// See [`ptr::read_volatile`] for safety concerns and examples.
778 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
779 #[stable(feature = "pointer_methods", since = "1.26.0")]
781 pub unsafe fn read_volatile(self) -> T
785 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
786 unsafe { read_volatile(self) }
789 /// Reads the value from `self` without moving it. This leaves the
790 /// memory in `self` unchanged.
792 /// Unlike `read`, the pointer may be unaligned.
794 /// See [`ptr::read_unaligned`] for safety concerns and examples.
796 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
797 #[stable(feature = "pointer_methods", since = "1.26.0")]
798 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
800 pub const unsafe fn read_unaligned(self) -> T
804 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
805 unsafe { read_unaligned(self) }
808 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
809 /// and destination may overlap.
811 /// NOTE: this has the *same* argument order as [`ptr::copy`].
813 /// See [`ptr::copy`] for safety concerns and examples.
815 /// [`ptr::copy`]: crate::ptr::copy()
816 #[stable(feature = "pointer_methods", since = "1.26.0")]
818 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
822 // SAFETY: the caller must uphold the safety contract for `copy`.
823 unsafe { copy(self, dest, count) }
826 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
827 /// and destination may *not* overlap.
829 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
831 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
833 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
834 #[stable(feature = "pointer_methods", since = "1.26.0")]
836 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
840 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
841 unsafe { copy_nonoverlapping(self, dest, count) }
844 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
847 /// If it is not possible to align the pointer, the implementation returns
848 /// `usize::MAX`. It is permissible for the implementation to *always*
849 /// return `usize::MAX`. Only your algorithm's performance can depend
850 /// on getting a usable offset here, not its correctness.
852 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
853 /// used with the `wrapping_add` method.
855 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
856 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
857 /// the returned offset is correct in all terms other than alignment.
861 /// The function panics if `align` is not a power-of-two.
865 /// Accessing adjacent `u8` as `u16`
868 /// # fn foo(n: usize) {
869 /// # use std::mem::align_of;
871 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
872 /// let ptr = x.as_ptr().add(n) as *const u8;
873 /// let offset = ptr.align_offset(align_of::<u16>());
874 /// if offset < x.len() - n - 1 {
875 /// let u16_ptr = ptr.add(offset) as *const u16;
876 /// assert_ne!(*u16_ptr, 500);
878 /// // while the pointer can be aligned via `offset`, it would point
879 /// // outside the allocation
883 #[stable(feature = "align_offset", since = "1.36.0")]
884 pub fn align_offset(self, align: usize) -> usize
888 if !align.is_power_of_two() {
889 panic!("align_offset: align is not a power-of-two");
891 // SAFETY: `align` has been checked to be a power of 2 above
892 unsafe { align_offset(self, align) }
896 #[lang = "const_slice_ptr"]
898 /// Returns the length of a raw slice.
900 /// The returned value is the number of **elements**, not the number of bytes.
902 /// This function is safe, even when the raw slice cannot be cast to a slice
903 /// reference because the pointer is null or unaligned.
908 /// #![feature(slice_ptr_len)]
912 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
913 /// assert_eq!(slice.len(), 3);
916 #[unstable(feature = "slice_ptr_len", issue = "71146")]
917 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
918 pub const fn len(self) -> usize {
921 // SAFETY: this is safe because `*const [T]` and `FatPtr<T>` have the same layout.
922 // Only `std` can make this guarantee.
923 unsafe { Repr { rust: self }.raw }.len
925 #[cfg(not(bootstrap))]
929 /// Returns a raw pointer to the slice's buffer.
931 /// This is equivalent to casting `self` to `*const T`, but more type-safe.
936 /// #![feature(slice_ptr_get)]
939 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
940 /// assert_eq!(slice.as_ptr(), 0 as *const i8);
943 #[unstable(feature = "slice_ptr_get", issue = "74265")]
944 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
945 pub const fn as_ptr(self) -> *const T {
949 /// Returns a raw pointer to an element or subslice, without doing bounds
952 /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
953 /// is *[undefined behavior]* even if the resulting pointer is not used.
955 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
960 /// #![feature(slice_ptr_get)]
962 /// let x = &[1, 2, 4] as *const [i32];
965 /// assert_eq!(x.get_unchecked(1), x.as_ptr().add(1));
968 #[unstable(feature = "slice_ptr_get", issue = "74265")]
970 pub unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output
974 // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
975 unsafe { index.get_unchecked(self) }
978 /// Returns `None` if the pointer is null, or else returns a shared slice to
979 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
980 /// that the value has to be initialized.
982 /// [`as_ref`]: #method.as_ref
986 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
987 /// all of the following is true:
989 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
990 /// and it must be properly aligned. This means in particular:
992 /// * The entire memory range of this slice must be contained within a single allocated object!
993 /// Slices can never span across multiple allocated objects.
995 /// * The pointer must be aligned even for zero-length slices. One
996 /// reason for this is that enum layout optimizations may rely on references
997 /// (including slices of any length) being aligned and non-null to distinguish
998 /// them from other data. You can obtain a pointer that is usable as `data`
999 /// for zero-length slices using [`NonNull::dangling()`].
1001 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1002 /// See the safety documentation of [`pointer::offset`].
1004 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1005 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1006 /// In particular, for the duration of this lifetime, the memory the pointer points to must
1007 /// not get mutated (except inside `UnsafeCell`).
1009 /// This applies even if the result of this method is unused!
1011 /// See also [`slice::from_raw_parts`][].
1013 /// [valid]: crate::ptr#safety
1014 /// [`NonNull::dangling()`]: NonNull::dangling
1015 /// [`pointer::offset`]: ../std/primitive.pointer.html#method.offset
1017 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1018 pub unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1022 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1023 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1028 // Equality for pointers
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 impl<T: ?Sized> PartialEq for *const T {
1032 fn eq(&self, other: &*const T) -> bool {
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 impl<T: ?Sized> Eq for *const T {}
1040 // Comparison for pointers
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl<T: ?Sized> Ord for *const T {
1044 fn cmp(&self, other: &*const T) -> Ordering {
1047 } else if self == other {
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 impl<T: ?Sized> PartialOrd for *const T {
1058 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
1059 Some(self.cmp(other))
1063 fn lt(&self, other: &*const T) -> bool {
1068 fn le(&self, other: &*const T) -> bool {
1073 fn gt(&self, other: &*const T) -> bool {
1078 fn ge(&self, other: &*const T) -> bool {