2 use crate::cmp::Ordering::{self, Equal, Greater, Less};
4 use crate::slice::{self, SliceIndex};
7 impl<T: ?Sized> *mut T {
8 /// Returns `true` if the pointer is null.
10 /// Note that unsized types have many possible null pointers, as only the
11 /// raw data pointer is considered, not their length, vtable, etc.
12 /// Therefore, two pointers that are null may still not compare equal to
15 /// ## Behavior during const evaluation
17 /// When this function is used during const evaluation, it may return `false` for pointers
18 /// that turn out to be null at runtime. Specifically, when a pointer to some memory
19 /// is offset beyond its bounds in such a way that the resulting pointer is null,
20 /// the function will still return `false`. There is no way for CTFE to know
21 /// the absolute position of that memory, so we cannot tell if the pointer is
29 /// let mut s = [1, 2, 3];
30 /// let ptr: *mut u32 = s.as_mut_ptr();
31 /// assert!(!ptr.is_null());
33 #[stable(feature = "rust1", since = "1.0.0")]
34 #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")]
36 pub const fn is_null(self) -> bool {
37 // Compare via a cast to a thin pointer, so fat pointers are only
38 // considering their "data" part for null-ness.
39 (self as *mut u8).guaranteed_eq(null_mut())
42 /// Casts to a pointer of another type.
43 #[stable(feature = "ptr_cast", since = "1.38.0")]
44 #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
46 pub const fn cast<U>(self) -> *mut U {
50 /// Returns `None` if the pointer is null, or else returns a shared reference to
51 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
52 /// must be used instead.
54 /// For the mutable counterpart see [`as_mut`].
56 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
57 /// [`as_mut`]: #method.as_mut
61 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
62 /// all of the following is true:
64 /// * The pointer must be properly aligned.
66 /// * It must be "dereferencable" in the sense defined in [the module documentation].
68 /// * The pointer must point to an initialized instance of `T`.
70 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
71 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
72 /// In particular, for the duration of this lifetime, the memory the pointer points to must
73 /// not get mutated (except inside `UnsafeCell`).
75 /// This applies even if the result of this method is unused!
76 /// (The part about being initialized is not yet fully decided, but until
77 /// it is, the only safe approach is to ensure that they are indeed initialized.)
79 /// [the module documentation]: crate::ptr#safety
86 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
89 /// if let Some(val_back) = ptr.as_ref() {
90 /// println!("We got back the value: {}!", val_back);
95 /// # Null-unchecked version
97 /// If you are sure the pointer can never be null and are looking for some kind of
98 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
99 /// dereference the pointer directly.
102 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
105 /// let val_back = &*ptr;
106 /// println!("We got back the value: {}!", val_back);
109 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
111 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
112 // SAFETY: the caller must guarantee that `self` is valid for a
113 // reference if it isn't null.
114 if self.is_null() { None } else { unsafe { Some(&*self) } }
117 /// Returns `None` if the pointer is null, or else returns a shared reference to
118 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
119 /// that the value has to be initialized.
121 /// For the mutable counterpart see [`as_uninit_mut`].
123 /// [`as_ref`]: #method.as_ref-1
124 /// [`as_uninit_mut`]: #method.as_uninit_mut
128 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
129 /// all of the following is true:
131 /// * The pointer must be properly aligned.
133 /// * It must be "dereferencable" in the sense defined in [the module documentation].
135 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
136 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
137 /// In particular, for the duration of this lifetime, the memory the pointer points to must
138 /// not get mutated (except inside `UnsafeCell`).
140 /// This applies even if the result of this method is unused!
142 /// [the module documentation]: crate::ptr#safety
149 /// #![feature(ptr_as_uninit)]
151 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
154 /// if let Some(val_back) = ptr.as_uninit_ref() {
155 /// println!("We got back the value: {}!", val_back.assume_init());
160 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
161 pub unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
165 // SAFETY: the caller must guarantee that `self` meets all the
166 // requirements for a reference.
167 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
170 /// Calculates the offset from a pointer.
172 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
173 /// offset of `3 * size_of::<T>()` bytes.
177 /// If any of the following conditions are violated, the result is Undefined
180 /// * Both the starting and resulting pointer must be either in bounds or one
181 /// byte past the end of the same allocated object. Note that in Rust,
182 /// every (stack-allocated) variable is considered a separate allocated object.
184 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
186 /// * The offset being in bounds cannot rely on "wrapping around" the address
187 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
189 /// The compiler and standard library generally tries to ensure allocations
190 /// never reach a size where an offset is a concern. For instance, `Vec`
191 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
192 /// `vec.as_ptr().add(vec.len())` is always safe.
194 /// Most platforms fundamentally can't even construct such an allocation.
195 /// For instance, no known 64-bit platform can ever serve a request
196 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
197 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
198 /// more than `isize::MAX` bytes with things like Physical Address
199 /// Extension. As such, memory acquired directly from allocators or memory
200 /// mapped files *may* be too large to handle with this function.
202 /// Consider using [`wrapping_offset`] instead if these constraints are
203 /// difficult to satisfy. The only advantage of this method is that it
204 /// enables more aggressive compiler optimizations.
206 /// [`wrapping_offset`]: #method.wrapping_offset
213 /// let mut s = [1, 2, 3];
214 /// let ptr: *mut u32 = s.as_mut_ptr();
217 /// println!("{}", *ptr.offset(1));
218 /// println!("{}", *ptr.offset(2));
221 #[stable(feature = "rust1", since = "1.0.0")]
222 #[must_use = "returns a new pointer rather than modifying its argument"]
223 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
225 pub const unsafe fn offset(self, count: isize) -> *mut T
229 // SAFETY: the caller must uphold the safety contract for `offset`.
230 // The obtained pointer is valid for writes since the caller must
231 // guarantee that it points to the same allocated object as `self`.
232 unsafe { intrinsics::offset(self, count) as *mut T }
235 /// Calculates the offset from a pointer using wrapping arithmetic.
236 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
237 /// offset of `3 * size_of::<T>()` bytes.
241 /// The resulting pointer does not need to be in bounds, but it is
242 /// potentially hazardous to dereference (which requires `unsafe`).
244 /// In particular, the resulting pointer remains attached to the same allocated
245 /// object that `self` points to. It may *not* be used to access a
246 /// different allocated object. Note that in Rust,
247 /// every (stack-allocated) variable is considered a separate allocated object.
249 /// In other words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
250 /// *not* the same as `y`, and dereferencing it is undefined behavior
251 /// unless `x` and `y` point into the same allocated object.
253 /// Compared to [`offset`], this method basically delays the requirement of staying
254 /// within the same allocated object: [`offset`] is immediate Undefined Behavior when
255 /// crossing object boundaries; `wrapping_offset` produces a pointer but still leads
256 /// to Undefined Behavior if that pointer is dereferenced. [`offset`] can be optimized
257 /// better and is thus preferable in performance-sensitive code.
259 /// If you need to cross object boundaries, cast the pointer to an integer and
260 /// do the arithmetic there.
262 /// [`offset`]: #method.offset
269 /// // Iterate using a raw pointer in increments of two elements
270 /// let mut data = [1u8, 2, 3, 4, 5];
271 /// let mut ptr: *mut u8 = data.as_mut_ptr();
273 /// let end_rounded_up = ptr.wrapping_offset(6);
275 /// while ptr != end_rounded_up {
279 /// ptr = ptr.wrapping_offset(step);
281 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
283 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
284 #[must_use = "returns a new pointer rather than modifying its argument"]
285 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
287 pub const fn wrapping_offset(self, count: isize) -> *mut T
291 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
292 unsafe { intrinsics::arith_offset(self, count) as *mut T }
295 /// Returns `None` if the pointer is null, or else returns a unique reference to
296 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
297 /// must be used instead.
299 /// For the shared counterpart see [`as_ref`].
301 /// [`as_uninit_mut`]: #method.as_uninit_mut
302 /// [`as_ref`]: #method.as_ref-1
306 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
307 /// all of the following is true:
309 /// * The pointer must be properly aligned.
311 /// * It must be "dereferencable" in the sense defined in [the module documentation].
313 /// * The pointer must point to an initialized instance of `T`.
315 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
316 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
317 /// In particular, for the duration of this lifetime, the memory the pointer points to must
318 /// not get accessed (read or written) through any other pointer.
320 /// This applies even if the result of this method is unused!
321 /// (The part about being initialized is not yet fully decided, but until
322 /// it is, the only safe approach is to ensure that they are indeed initialized.)
324 /// [the module documentation]: crate::ptr#safety
331 /// let mut s = [1, 2, 3];
332 /// let ptr: *mut u32 = s.as_mut_ptr();
333 /// let first_value = unsafe { ptr.as_mut().unwrap() };
334 /// *first_value = 4;
335 /// # assert_eq!(s, [4, 2, 3]);
336 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
339 /// # Null-unchecked version
341 /// If you are sure the pointer can never be null and are looking for some kind of
342 /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
343 /// you can dereference the pointer directly.
346 /// let mut s = [1, 2, 3];
347 /// let ptr: *mut u32 = s.as_mut_ptr();
348 /// let first_value = unsafe { &mut *ptr };
349 /// *first_value = 4;
350 /// # assert_eq!(s, [4, 2, 3]);
351 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
353 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
355 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
356 // SAFETY: the caller must guarantee that `self` is be valid for
357 // a mutable reference if it isn't null.
358 if self.is_null() { None } else { unsafe { Some(&mut *self) } }
361 /// Returns `None` if the pointer is null, or else returns a unique reference to
362 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
363 /// that the value has to be initialized.
365 /// For the shared counterpart see [`as_uninit_ref`].
367 /// [`as_mut`]: #method.as_mut
368 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
372 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
373 /// all of the following is true:
375 /// * The pointer must be properly aligned.
377 /// * It must be "dereferencable" in the sense defined in [the module documentation].
379 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
380 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
381 /// In particular, for the duration of this lifetime, the memory the pointer points to must
382 /// not get accessed (read or written) through any other pointer.
384 /// This applies even if the result of this method is unused!
386 /// [the module documentation]: crate::ptr#safety
388 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
389 pub unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
393 // SAFETY: the caller must guarantee that `self` meets all the
394 // requirements for a reference.
395 if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
398 /// Returns whether two pointers are guaranteed to be equal.
400 /// At runtime this function behaves like `self == other`.
401 /// However, in some contexts (e.g., compile-time evaluation),
402 /// it is not always possible to determine equality of two pointers, so this function may
403 /// spuriously return `false` for pointers that later actually turn out to be equal.
404 /// But when it returns `true`, the pointers are guaranteed to be equal.
406 /// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
407 /// comparisons for which both functions return `false`.
409 /// [`guaranteed_ne`]: #method.guaranteed_ne
411 /// The return value may change depending on the compiler version and unsafe code may not
412 /// rely on the result of this function for soundness. It is suggested to only use this function
413 /// for performance optimizations where spurious `false` return values by this function do not
414 /// affect the outcome, but just the performance.
415 /// The consequences of using this method to make runtime and compile-time code behave
416 /// differently have not been explored. This method should not be used to introduce such
417 /// differences, and it should also not be stabilized before we have a better understanding
419 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
420 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
422 pub const fn guaranteed_eq(self, other: *mut T) -> bool
426 intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _)
429 /// Returns whether two pointers are guaranteed to be unequal.
431 /// At runtime this function behaves like `self != other`.
432 /// However, in some contexts (e.g., compile-time evaluation),
433 /// it is not always possible to determine the inequality of two pointers, so this function may
434 /// spuriously return `false` for pointers that later actually turn out to be unequal.
435 /// But when it returns `true`, the pointers are guaranteed to be unequal.
437 /// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
438 /// comparisons for which both functions return `false`.
440 /// [`guaranteed_eq`]: #method.guaranteed_eq
442 /// The return value may change depending on the compiler version and unsafe code may not
443 /// rely on the result of this function for soundness. It is suggested to only use this function
444 /// for performance optimizations where spurious `false` return values by this function do not
445 /// affect the outcome, but just the performance.
446 /// The consequences of using this method to make runtime and compile-time code behave
447 /// differently have not been explored. This method should not be used to introduce such
448 /// differences, and it should also not be stabilized before we have a better understanding
450 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
451 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
453 pub const unsafe fn guaranteed_ne(self, other: *mut T) -> bool
457 intrinsics::ptr_guaranteed_ne(self as *const _, other as *const _)
460 /// Calculates the distance between two pointers. The returned value is in
461 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
463 /// This function is the inverse of [`offset`].
465 /// [`offset`]: #method.offset-1
466 /// [`wrapping_offset_from`]: #method.wrapping_offset_from-1
470 /// If any of the following conditions are violated, the result is Undefined
473 /// * Both the starting and other pointer must be either in bounds or one
474 /// byte past the end of the same allocated object. Note that in Rust,
475 /// every (stack-allocated) variable is considered a separate allocated object.
477 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
479 /// * The distance between the pointers, in bytes, must be an exact multiple
480 /// of the size of `T`.
482 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
484 /// The compiler and standard library generally try to ensure allocations
485 /// never reach a size where an offset is a concern. For instance, `Vec`
486 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
487 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
489 /// Most platforms fundamentally can't even construct such an allocation.
490 /// For instance, no known 64-bit platform can ever serve a request
491 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
492 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
493 /// more than `isize::MAX` bytes with things like Physical Address
494 /// Extension. As such, memory acquired directly from allocators or memory
495 /// mapped files *may* be too large to handle with this function.
497 /// Consider using [`wrapping_offset_from`] instead if these constraints are
498 /// difficult to satisfy. The only advantage of this method is that it
499 /// enables more aggressive compiler optimizations.
503 /// This function panics if `T` is a Zero-Sized Type ("ZST").
510 /// #![feature(ptr_offset_from)]
512 /// let mut a = [0; 5];
513 /// let ptr1: *mut i32 = &mut a[1];
514 /// let ptr2: *mut i32 = &mut a[3];
516 /// assert_eq!(ptr2.offset_from(ptr1), 2);
517 /// assert_eq!(ptr1.offset_from(ptr2), -2);
518 /// assert_eq!(ptr1.offset(2), ptr2);
519 /// assert_eq!(ptr2.offset(-2), ptr1);
522 #[unstable(feature = "ptr_offset_from", issue = "41079")]
523 #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")]
525 pub const unsafe fn offset_from(self, origin: *const T) -> isize
529 // SAFETY: the caller must uphold the safety contract for `offset_from`.
530 unsafe { (self as *const T).offset_from(origin) }
533 /// Calculates the distance between two pointers. The returned value is in
534 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
536 /// If the address different between the two pointers is not a multiple of
537 /// `mem::size_of::<T>()` then the result of the division is rounded towards
540 /// Though this method is safe for any two pointers, note that its result
541 /// will be mostly useless if the two pointers aren't into the same allocated
542 /// object, for example if they point to two different local variables.
546 /// This function panics if `T` is a zero-sized type.
553 /// #![feature(ptr_wrapping_offset_from)]
555 /// let mut a = [0; 5];
556 /// let ptr1: *mut i32 = &mut a[1];
557 /// let ptr2: *mut i32 = &mut a[3];
558 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
559 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
560 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
561 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
563 /// let ptr1: *mut i32 = 3 as _;
564 /// let ptr2: *mut i32 = 13 as _;
565 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
567 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
570 reason = "Pointer distances across allocation \
571 boundaries are not typically meaningful. \
572 Use integer subtraction if you really need this."
575 pub fn wrapping_offset_from(self, origin: *const T) -> isize
579 #[allow(deprecated_in_future, deprecated)]
580 (self as *const T).wrapping_offset_from(origin)
583 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
585 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
586 /// offset of `3 * size_of::<T>()` bytes.
590 /// If any of the following conditions are violated, the result is Undefined
593 /// * Both the starting and resulting pointer must be either in bounds or one
594 /// byte past the end of the same allocated object. Note that in Rust,
595 /// every (stack-allocated) variable is considered a separate allocated object.
597 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
599 /// * The offset being in bounds cannot rely on "wrapping around" the address
600 /// space. That is, the infinite-precision sum must fit in a `usize`.
602 /// The compiler and standard library generally tries to ensure allocations
603 /// never reach a size where an offset is a concern. For instance, `Vec`
604 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
605 /// `vec.as_ptr().add(vec.len())` is always safe.
607 /// Most platforms fundamentally can't even construct such an allocation.
608 /// For instance, no known 64-bit platform can ever serve a request
609 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
610 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
611 /// more than `isize::MAX` bytes with things like Physical Address
612 /// Extension. As such, memory acquired directly from allocators or memory
613 /// mapped files *may* be too large to handle with this function.
615 /// Consider using [`wrapping_add`] instead if these constraints are
616 /// difficult to satisfy. The only advantage of this method is that it
617 /// enables more aggressive compiler optimizations.
619 /// [`wrapping_add`]: #method.wrapping_add
626 /// let s: &str = "123";
627 /// let ptr: *const u8 = s.as_ptr();
630 /// println!("{}", *ptr.add(1) as char);
631 /// println!("{}", *ptr.add(2) as char);
634 #[stable(feature = "pointer_methods", since = "1.26.0")]
635 #[must_use = "returns a new pointer rather than modifying its argument"]
636 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
638 pub const unsafe fn add(self, count: usize) -> Self
642 // SAFETY: the caller must uphold the safety contract for `offset`.
643 unsafe { self.offset(count as isize) }
646 /// Calculates the offset from a pointer (convenience for
647 /// `.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 /// If any of the following conditions are violated, the result is Undefined
657 /// * Both the starting and resulting pointer must be either in bounds or one
658 /// byte past the end of the same allocated object. Note that in Rust,
659 /// every (stack-allocated) variable is considered a separate allocated object.
661 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
663 /// * The offset being in bounds cannot rely on "wrapping around" the address
664 /// space. That is, the infinite-precision sum must fit in a usize.
666 /// The compiler and standard library generally tries to ensure allocations
667 /// never reach a size where an offset is a concern. For instance, `Vec`
668 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
669 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
671 /// Most platforms fundamentally can't even construct such an allocation.
672 /// For instance, no known 64-bit platform can ever serve a request
673 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
674 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
675 /// more than `isize::MAX` bytes with things like Physical Address
676 /// Extension. As such, memory acquired directly from allocators or memory
677 /// mapped files *may* be too large to handle with this function.
679 /// Consider using [`wrapping_sub`] instead if these constraints are
680 /// difficult to satisfy. The only advantage of this method is that it
681 /// enables more aggressive compiler optimizations.
683 /// [`wrapping_sub`]: #method.wrapping_sub
690 /// let s: &str = "123";
693 /// let end: *const u8 = s.as_ptr().add(3);
694 /// println!("{}", *end.sub(1) as char);
695 /// println!("{}", *end.sub(2) as char);
698 #[stable(feature = "pointer_methods", since = "1.26.0")]
699 #[must_use = "returns a new pointer rather than modifying its argument"]
700 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
702 pub const unsafe fn sub(self, count: usize) -> Self
706 // SAFETY: the caller must uphold the safety contract for `offset`.
707 unsafe { self.offset((count as isize).wrapping_neg()) }
710 /// Calculates the offset from a pointer using wrapping arithmetic.
711 /// (convenience for `.wrapping_offset(count as isize)`)
713 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
714 /// offset of `3 * size_of::<T>()` bytes.
718 /// The resulting pointer does not need to be in bounds, but it is
719 /// potentially hazardous to dereference (which requires `unsafe`).
721 /// In particular, the resulting pointer remains attached to the same allocated
722 /// object that `self` points to. It may *not* be used to access a
723 /// different allocated object. Note that in Rust,
724 /// every (stack-allocated) variable is considered a separate allocated object.
726 /// Compared to [`add`], this method basically delays the requirement of staying
727 /// within the same allocated object: [`add`] is immediate Undefined Behavior when
728 /// crossing object boundaries; `wrapping_add` produces a pointer but still leads
729 /// to Undefined Behavior if that pointer is dereferenced. [`add`] can be optimized
730 /// better and is thus preferable in performance-sensitive code.
732 /// If you need to cross object boundaries, cast the pointer to an integer and
733 /// do the arithmetic there.
735 /// [`add`]: #method.add
742 /// // Iterate using a raw pointer in increments of two elements
743 /// let data = [1u8, 2, 3, 4, 5];
744 /// let mut ptr: *const u8 = data.as_ptr();
746 /// let end_rounded_up = ptr.wrapping_add(6);
748 /// // This loop prints "1, 3, 5, "
749 /// while ptr != end_rounded_up {
751 /// print!("{}, ", *ptr);
753 /// ptr = ptr.wrapping_add(step);
756 #[stable(feature = "pointer_methods", since = "1.26.0")]
757 #[must_use = "returns a new pointer rather than modifying its argument"]
758 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
760 pub const fn wrapping_add(self, count: usize) -> Self
764 self.wrapping_offset(count as isize)
767 /// Calculates the offset from a pointer using wrapping arithmetic.
768 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
770 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
771 /// offset of `3 * size_of::<T>()` bytes.
775 /// The resulting pointer does not need to be in bounds, but it is
776 /// potentially hazardous to dereference (which requires `unsafe`).
778 /// In particular, the resulting pointer remains attached to the same allocated
779 /// object that `self` points to. It may *not* be used to access a
780 /// different allocated object. Note that in Rust,
781 /// every (stack-allocated) variable is considered a separate allocated object.
783 /// Compared to [`sub`], this method basically delays the requirement of staying
784 /// within the same allocated object: [`sub`] is immediate Undefined Behavior when
785 /// crossing object boundaries; `wrapping_sub` produces a pointer but still leads
786 /// to Undefined Behavior if that pointer is dereferenced. [`sub`] can be optimized
787 /// better and is thus preferable in performance-sensitive code.
789 /// If you need to cross object boundaries, cast the pointer to an integer and
790 /// do the arithmetic there.
792 /// [`sub`]: #method.sub
799 /// // Iterate using a raw pointer in increments of two elements (backwards)
800 /// let data = [1u8, 2, 3, 4, 5];
801 /// let mut ptr: *const u8 = data.as_ptr();
802 /// let start_rounded_down = ptr.wrapping_sub(2);
803 /// ptr = ptr.wrapping_add(4);
805 /// // This loop prints "5, 3, 1, "
806 /// while ptr != start_rounded_down {
808 /// print!("{}, ", *ptr);
810 /// ptr = ptr.wrapping_sub(step);
813 #[stable(feature = "pointer_methods", since = "1.26.0")]
814 #[must_use = "returns a new pointer rather than modifying its argument"]
815 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
817 pub const fn wrapping_sub(self, count: usize) -> Self
821 self.wrapping_offset((count as isize).wrapping_neg())
824 /// Sets the pointer value to `ptr`.
826 /// In case `self` is a (fat) pointer to an unsized type, this operation
827 /// will only affect the pointer part, whereas for (thin) pointers to
828 /// sized types, this has the same effect as a simple assignment.
830 /// The resulting pointer will have provenance of `val`, i.e., for a fat
831 /// pointer, this operation is semantically the same as creating a new
832 /// fat pointer with the data pointer value of `val` but the metadata of
837 /// This function is primarily useful for allowing byte-wise pointer
838 /// arithmetic on potentially fat pointers:
841 /// #![feature(set_ptr_value)]
842 /// # use core::fmt::Debug;
843 /// let mut arr: [i32; 3] = [1, 2, 3];
844 /// let mut ptr = &mut arr[0] as *mut dyn Debug;
845 /// let thin = ptr as *mut u8;
847 /// ptr = ptr.set_ptr_value(thin.add(8));
848 /// # assert_eq!(*(ptr as *mut i32), 3);
849 /// println!("{:?}", &*ptr); // will print "3"
852 #[unstable(feature = "set_ptr_value", issue = "75091")]
853 #[must_use = "returns a new pointer rather than modifying its argument"]
855 pub fn set_ptr_value(mut self, val: *mut u8) -> Self {
856 let thin = &mut self as *mut *mut T as *mut *mut u8;
857 // SAFETY: In case of a thin pointer, this operations is identical
858 // to a simple assignment. In case of a fat pointer, with the current
859 // fat pointer layout implementation, the first field of such a
860 // pointer is always the data pointer, which is likewise assigned.
861 unsafe { *thin = val };
865 /// Reads the value from `self` without moving it. This leaves the
866 /// memory in `self` unchanged.
868 /// See [`ptr::read`] for safety concerns and examples.
870 /// [`ptr::read`]: ./ptr/fn.read.html
871 #[stable(feature = "pointer_methods", since = "1.26.0")]
873 pub unsafe fn read(self) -> T
877 // SAFETY: the caller must uphold the safety contract for ``.
878 unsafe { read(self) }
881 /// Performs a volatile read of the value from `self` without moving it. This
882 /// leaves the memory in `self` unchanged.
884 /// Volatile operations are intended to act on I/O memory, and are guaranteed
885 /// to not be elided or reordered by the compiler across other volatile
888 /// See [`ptr::read_volatile`] for safety concerns and examples.
890 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
891 #[stable(feature = "pointer_methods", since = "1.26.0")]
893 pub unsafe fn read_volatile(self) -> T
897 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
898 unsafe { read_volatile(self) }
901 /// Reads the value from `self` without moving it. This leaves the
902 /// memory in `self` unchanged.
904 /// Unlike `read`, the pointer may be unaligned.
906 /// See [`ptr::read_unaligned`] for safety concerns and examples.
908 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
909 #[stable(feature = "pointer_methods", since = "1.26.0")]
911 pub unsafe fn read_unaligned(self) -> T
915 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
916 unsafe { read_unaligned(self) }
919 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
920 /// and destination may overlap.
922 /// NOTE: this has the *same* argument order as [`ptr::copy`].
924 /// See [`ptr::copy`] for safety concerns and examples.
926 /// [`ptr::copy`]: ./ptr/fn.copy.html
927 #[stable(feature = "pointer_methods", since = "1.26.0")]
929 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
933 // SAFETY: the caller must uphold the safety contract for `copy`.
934 unsafe { copy(self, dest, count) }
937 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
938 /// and destination may *not* overlap.
940 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
942 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
944 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
945 #[stable(feature = "pointer_methods", since = "1.26.0")]
947 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
951 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
952 unsafe { copy_nonoverlapping(self, dest, count) }
955 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
956 /// and destination may overlap.
958 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
960 /// See [`ptr::copy`] for safety concerns and examples.
962 /// [`ptr::copy`]: ./ptr/fn.copy.html
963 #[stable(feature = "pointer_methods", since = "1.26.0")]
965 pub unsafe fn copy_from(self, src: *const T, count: usize)
969 // SAFETY: the caller must uphold the safety contract for `copy`.
970 unsafe { copy(src, self, count) }
973 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
974 /// and destination may *not* overlap.
976 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
978 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
980 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
981 #[stable(feature = "pointer_methods", since = "1.26.0")]
983 pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
987 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
988 unsafe { copy_nonoverlapping(src, self, count) }
991 /// Executes the destructor (if any) of the pointed-to value.
993 /// See [`ptr::drop_in_place`] for safety concerns and examples.
995 /// [`ptr::drop_in_place`]: ./ptr/fn.drop_in_place.html
996 #[stable(feature = "pointer_methods", since = "1.26.0")]
998 pub unsafe fn drop_in_place(self) {
999 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1000 unsafe { drop_in_place(self) }
1003 /// Overwrites a memory location with the given value without reading or
1004 /// dropping the old value.
1006 /// See [`ptr::write`] for safety concerns and examples.
1008 /// [`ptr::write`]: ./ptr/fn.write.html
1009 #[stable(feature = "pointer_methods", since = "1.26.0")]
1011 pub unsafe fn write(self, val: T)
1015 // SAFETY: the caller must uphold the safety contract for `write`.
1016 unsafe { write(self, val) }
1019 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1020 /// bytes of memory starting at `self` to `val`.
1022 /// See [`ptr::write_bytes`] for safety concerns and examples.
1024 /// [`ptr::write_bytes`]: ./ptr/fn.write_bytes.html
1025 #[stable(feature = "pointer_methods", since = "1.26.0")]
1027 pub unsafe fn write_bytes(self, val: u8, count: usize)
1031 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1032 unsafe { write_bytes(self, val, count) }
1035 /// Performs a volatile write of a memory location with the given value without
1036 /// reading or dropping the old value.
1038 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1039 /// to not be elided or reordered by the compiler across other volatile
1042 /// See [`ptr::write_volatile`] for safety concerns and examples.
1044 /// [`ptr::write_volatile`]: ./ptr/fn.write_volatile.html
1045 #[stable(feature = "pointer_methods", since = "1.26.0")]
1047 pub unsafe fn write_volatile(self, val: T)
1051 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1052 unsafe { write_volatile(self, val) }
1055 /// Overwrites a memory location with the given value without reading or
1056 /// dropping the old value.
1058 /// Unlike `write`, the pointer may be unaligned.
1060 /// See [`ptr::write_unaligned`] for safety concerns and examples.
1062 /// [`ptr::write_unaligned`]: ./ptr/fn.write_unaligned.html
1063 #[stable(feature = "pointer_methods", since = "1.26.0")]
1065 pub unsafe fn write_unaligned(self, val: T)
1069 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1070 unsafe { write_unaligned(self, val) }
1073 /// Replaces the value at `self` with `src`, returning the old
1074 /// value, without dropping either.
1076 /// See [`ptr::replace`] for safety concerns and examples.
1078 /// [`ptr::replace`]: ./ptr/fn.replace.html
1079 #[stable(feature = "pointer_methods", since = "1.26.0")]
1081 pub unsafe fn replace(self, src: T) -> T
1085 // SAFETY: the caller must uphold the safety contract for `replace`.
1086 unsafe { replace(self, src) }
1089 /// Swaps the values at two mutable locations of the same type, without
1090 /// deinitializing either. They may overlap, unlike `mem::swap` which is
1091 /// otherwise equivalent.
1093 /// See [`ptr::swap`] for safety concerns and examples.
1095 /// [`ptr::swap`]: ./ptr/fn.swap.html
1096 #[stable(feature = "pointer_methods", since = "1.26.0")]
1098 pub unsafe fn swap(self, with: *mut T)
1102 // SAFETY: the caller must uphold the safety contract for `swap`.
1103 unsafe { swap(self, with) }
1106 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1109 /// If it is not possible to align the pointer, the implementation returns
1110 /// `usize::MAX`. It is permissible for the implementation to *always*
1111 /// return `usize::MAX`. Only your algorithm's performance can depend
1112 /// on getting a usable offset here, not its correctness.
1114 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1115 /// used with the `wrapping_add` method.
1117 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1118 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1119 /// the returned offset is correct in all terms other than alignment.
1123 /// The function panics if `align` is not a power-of-two.
1127 /// Accessing adjacent `u8` as `u16`
1130 /// # fn foo(n: usize) {
1131 /// # use std::mem::align_of;
1133 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1134 /// let ptr = &x[n] as *const u8;
1135 /// let offset = ptr.align_offset(align_of::<u16>());
1136 /// if offset < x.len() - n - 1 {
1137 /// let u16_ptr = ptr.add(offset) as *const u16;
1138 /// assert_ne!(*u16_ptr, 500);
1140 /// // while the pointer can be aligned via `offset`, it would point
1141 /// // outside the allocation
1145 #[stable(feature = "align_offset", since = "1.36.0")]
1146 pub fn align_offset(self, align: usize) -> usize
1150 if !align.is_power_of_two() {
1151 panic!("align_offset: align is not a power-of-two");
1153 // SAFETY: `align` has been checked to be a power of 2 above
1154 unsafe { align_offset(self, align) }
1158 #[lang = "mut_slice_ptr"]
1160 /// Returns the length of a raw slice.
1162 /// The returned value is the number of **elements**, not the number of bytes.
1164 /// This function is safe, even when the raw slice cannot be cast to a slice
1165 /// reference because the pointer is null or unaligned.
1170 /// #![feature(slice_ptr_len)]
1173 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1174 /// assert_eq!(slice.len(), 3);
1177 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1178 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1179 pub const fn len(self) -> usize {
1180 // SAFETY: this is safe because `*const [T]` and `FatPtr<T>` have the same layout.
1181 // Only `std` can make this guarantee.
1182 unsafe { Repr { rust_mut: self }.raw }.len
1185 /// Returns a raw pointer to the slice's buffer.
1187 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
1192 /// #![feature(slice_ptr_get)]
1195 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1196 /// assert_eq!(slice.as_mut_ptr(), 0 as *mut i8);
1199 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1200 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
1201 pub const fn as_mut_ptr(self) -> *mut T {
1205 /// Returns a raw pointer to an element or subslice, without doing bounds
1208 /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
1209 /// is *[undefined behavior]* even if the resulting pointer is not used.
1211 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1216 /// #![feature(slice_ptr_get)]
1218 /// let x = &mut [1, 2, 4] as *mut [i32];
1221 /// assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
1224 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1226 pub unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
1230 // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
1231 unsafe { index.get_unchecked_mut(self) }
1234 /// Returns `None` if the pointer is null, or else returns a shared slice to
1235 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1236 /// that the value has to be initialized.
1238 /// For the mutable counterpart see [`as_uninit_slice_mut`].
1240 /// [`as_ref`]: #method.as_ref-1
1241 /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
1245 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
1246 /// all of the following is true:
1248 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1249 /// and it must be properly aligned. This means in particular:
1251 /// * The entire memory range of this slice must be contained within a single allocated object!
1252 /// Slices can never span across multiple allocated objects.
1254 /// * The pointer must be aligned even for zero-length slices. One
1255 /// reason for this is that enum layout optimizations may rely on references
1256 /// (including slices of any length) being aligned and non-null to distinguish
1257 /// them from other data. You can obtain a pointer that is usable as `data`
1258 /// for zero-length slices using [`NonNull::dangling()`].
1260 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1261 /// See the safety documentation of [`pointer::offset`].
1263 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1264 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1265 /// In particular, for the duration of this lifetime, the memory the pointer points to must
1266 /// not get mutated (except inside `UnsafeCell`).
1268 /// This applies even if the result of this method is unused!
1270 /// See also [`slice::from_raw_parts`][].
1272 /// [valid]: crate::ptr#safety
1273 /// [`NonNull::dangling()`]: NonNull::dangling
1274 /// [`pointer::offset`]: ../std/primitive.pointer.html#method.offset
1276 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1277 pub unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1281 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1282 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1286 /// Returns `None` if the pointer is null, or else returns a unique slice to
1287 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
1288 /// that the value has to be initialized.
1290 /// For the shared counterpart see [`as_uninit_slice`].
1292 /// [`as_mut`]: #method.as_mut
1293 /// [`as_uninit_slice`]: #method.as_uninit_slice-1
1297 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
1298 /// all of the following is true:
1300 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
1301 /// many bytes, and it must be properly aligned. This means in particular:
1303 /// * The entire memory range of this slice must be contained within a single allocated object!
1304 /// Slices can never span across multiple allocated objects.
1306 /// * The pointer must be aligned even for zero-length slices. One
1307 /// reason for this is that enum layout optimizations may rely on references
1308 /// (including slices of any length) being aligned and non-null to distinguish
1309 /// them from other data. You can obtain a pointer that is usable as `data`
1310 /// for zero-length slices using [`NonNull::dangling()`].
1312 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1313 /// See the safety documentation of [`pointer::offset`].
1315 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1316 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1317 /// In particular, for the duration of this lifetime, the memory the pointer points to must
1318 /// not get accessed (read or written) through any other pointer.
1320 /// This applies even if the result of this method is unused!
1322 /// See also [`slice::from_raw_parts_mut`][].
1324 /// [valid]: crate::ptr#safety
1325 /// [`NonNull::dangling()`]: NonNull::dangling
1326 /// [`pointer::offset`]: ../std/primitive.pointer.html#method.offset
1328 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1329 pub unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
1333 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
1334 Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
1339 // Equality for pointers
1340 #[stable(feature = "rust1", since = "1.0.0")]
1341 impl<T: ?Sized> PartialEq for *mut T {
1343 fn eq(&self, other: &*mut T) -> bool {
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 impl<T: ?Sized> Eq for *mut T {}
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 impl<T: ?Sized> Ord for *mut T {
1354 fn cmp(&self, other: &*mut T) -> Ordering {
1357 } else if self == other {
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 impl<T: ?Sized> PartialOrd for *mut T {
1368 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
1369 Some(self.cmp(other))
1373 fn lt(&self, other: &*mut T) -> bool {
1378 fn le(&self, other: &*mut T) -> bool {
1383 fn gt(&self, other: &*mut T) -> bool {
1388 fn ge(&self, other: &*mut T) -> bool {