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 /// This operation itself is always safe, but using the resulting pointer is not.
243 /// The resulting pointer remains attached to the same allocated object that `self` points to.
244 /// It may *not* be used to access a different allocated object. Note that in Rust, every
245 /// (stack-allocated) variable is considered a separate allocated object.
247 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
248 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
249 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
250 /// `x` and `y` point into the same allocated object.
252 /// Compared to [`offset`], this method basically delays the requirement of staying within the
253 /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
254 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
255 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
256 /// can be optimized better and is thus preferable in performance-sensitive code.
258 /// The delayed check only considers the value of the pointer that was dereferenced, not the
259 /// intermediate values used during the computation of the final result. For example,
260 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
261 /// words, leaving the allocated object and then re-entering it later is permitted.
263 /// If you need to cross object boundaries, cast the pointer to an integer and
264 /// do the arithmetic there.
266 /// [`offset`]: #method.offset
273 /// // Iterate using a raw pointer in increments of two elements
274 /// let mut data = [1u8, 2, 3, 4, 5];
275 /// let mut ptr: *mut u8 = data.as_mut_ptr();
277 /// let end_rounded_up = ptr.wrapping_offset(6);
279 /// while ptr != end_rounded_up {
283 /// ptr = ptr.wrapping_offset(step);
285 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
287 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
288 #[must_use = "returns a new pointer rather than modifying its argument"]
289 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
291 pub const fn wrapping_offset(self, count: isize) -> *mut T
295 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
296 unsafe { intrinsics::arith_offset(self, count) as *mut T }
299 /// Returns `None` if the pointer is null, or else returns a unique reference to
300 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
301 /// must be used instead.
303 /// For the shared counterpart see [`as_ref`].
305 /// [`as_uninit_mut`]: #method.as_uninit_mut
306 /// [`as_ref`]: #method.as_ref-1
310 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
311 /// all of the following is true:
313 /// * The pointer must be properly aligned.
315 /// * It must be "dereferencable" in the sense defined in [the module documentation].
317 /// * The pointer must point to an initialized instance of `T`.
319 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
320 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
321 /// In particular, for the duration of this lifetime, the memory the pointer points to must
322 /// not get accessed (read or written) through any other pointer.
324 /// This applies even if the result of this method is unused!
325 /// (The part about being initialized is not yet fully decided, but until
326 /// it is, the only safe approach is to ensure that they are indeed initialized.)
328 /// [the module documentation]: crate::ptr#safety
335 /// let mut s = [1, 2, 3];
336 /// let ptr: *mut u32 = s.as_mut_ptr();
337 /// let first_value = unsafe { ptr.as_mut().unwrap() };
338 /// *first_value = 4;
339 /// # assert_eq!(s, [4, 2, 3]);
340 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
343 /// # Null-unchecked version
345 /// If you are sure the pointer can never be null and are looking for some kind of
346 /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
347 /// you can dereference the pointer directly.
350 /// let mut s = [1, 2, 3];
351 /// let ptr: *mut u32 = s.as_mut_ptr();
352 /// let first_value = unsafe { &mut *ptr };
353 /// *first_value = 4;
354 /// # assert_eq!(s, [4, 2, 3]);
355 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
357 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
359 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
360 // SAFETY: the caller must guarantee that `self` is be valid for
361 // a mutable reference if it isn't null.
362 if self.is_null() { None } else { unsafe { Some(&mut *self) } }
365 /// Returns `None` if the pointer is null, or else returns a unique reference to
366 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
367 /// that the value has to be initialized.
369 /// For the shared counterpart see [`as_uninit_ref`].
371 /// [`as_mut`]: #method.as_mut
372 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
376 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
377 /// all of the following is true:
379 /// * The pointer must be properly aligned.
381 /// * It must be "dereferencable" in the sense defined in [the module documentation].
383 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
384 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
385 /// In particular, for the duration of this lifetime, the memory the pointer points to must
386 /// not get accessed (read or written) through any other pointer.
388 /// This applies even if the result of this method is unused!
390 /// [the module documentation]: crate::ptr#safety
392 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
393 pub unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
397 // SAFETY: the caller must guarantee that `self` meets all the
398 // requirements for a reference.
399 if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
402 /// Returns whether two pointers are guaranteed to be equal.
404 /// At runtime this function behaves like `self == other`.
405 /// However, in some contexts (e.g., compile-time evaluation),
406 /// it is not always possible to determine equality of two pointers, so this function may
407 /// spuriously return `false` for pointers that later actually turn out to be equal.
408 /// But when it returns `true`, the pointers are guaranteed to be equal.
410 /// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
411 /// comparisons for which both functions return `false`.
413 /// [`guaranteed_ne`]: #method.guaranteed_ne
415 /// The return value may change depending on the compiler version and unsafe code may not
416 /// rely on the result of this function for soundness. It is suggested to only use this function
417 /// for performance optimizations where spurious `false` return values by this function do not
418 /// affect the outcome, but just the performance.
419 /// The consequences of using this method to make runtime and compile-time code behave
420 /// differently have not been explored. This method should not be used to introduce such
421 /// differences, and it should also not be stabilized before we have a better understanding
423 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
424 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
426 pub const fn guaranteed_eq(self, other: *mut T) -> bool
430 intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _)
433 /// Returns whether two pointers are guaranteed to be unequal.
435 /// At runtime this function behaves like `self != other`.
436 /// However, in some contexts (e.g., compile-time evaluation),
437 /// it is not always possible to determine the inequality of two pointers, so this function may
438 /// spuriously return `false` for pointers that later actually turn out to be unequal.
439 /// But when it returns `true`, the pointers are guaranteed to be unequal.
441 /// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
442 /// comparisons for which both functions return `false`.
444 /// [`guaranteed_eq`]: #method.guaranteed_eq
446 /// The return value may change depending on the compiler version and unsafe code may not
447 /// rely on the result of this function for soundness. It is suggested to only use this function
448 /// for performance optimizations where spurious `false` return values by this function do not
449 /// affect the outcome, but just the performance.
450 /// The consequences of using this method to make runtime and compile-time code behave
451 /// differently have not been explored. This method should not be used to introduce such
452 /// differences, and it should also not be stabilized before we have a better understanding
454 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
455 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
457 pub const unsafe fn guaranteed_ne(self, other: *mut T) -> bool
461 intrinsics::ptr_guaranteed_ne(self as *const _, other as *const _)
464 /// Calculates the distance between two pointers. The returned value is in
465 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
467 /// This function is the inverse of [`offset`].
469 /// [`offset`]: #method.offset-1
473 /// If any of the following conditions are violated, the result is Undefined
476 /// * Both the starting and other pointer must be either in bounds or one
477 /// byte past the end of the same allocated object. Note that in Rust,
478 /// every (stack-allocated) variable is considered a separate allocated object.
480 /// * Both pointers must be *derived from* a pointer to the same object.
481 /// (See below for an example.)
483 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
485 /// * The distance between the pointers, in bytes, must be an exact multiple
486 /// of the size of `T`.
488 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
490 /// The compiler and standard library generally try to ensure allocations
491 /// never reach a size where an offset is a concern. For instance, `Vec`
492 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
493 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
495 /// Most platforms fundamentally can't even construct such an allocation.
496 /// For instance, no known 64-bit platform can ever serve a request
497 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
498 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
499 /// more than `isize::MAX` bytes with things like Physical Address
500 /// Extension. As such, memory acquired directly from allocators or memory
501 /// mapped files *may* be too large to handle with this function.
505 /// This function panics if `T` is a Zero-Sized Type ("ZST").
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);
523 /// *Incorrect* usage:
526 /// let ptr1 = Box::into_raw(Box::new(0u8));
527 /// let ptr2 = Box::into_raw(Box::new(1u8));
528 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
529 /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
530 /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff);
531 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
532 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
533 /// // computing their offset is undefined behavior, even though
534 /// // they point to the same address!
536 /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
539 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
540 #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")]
542 pub const unsafe fn offset_from(self, origin: *const T) -> isize
546 // SAFETY: the caller must uphold the safety contract for `offset_from`.
547 unsafe { (self as *const T).offset_from(origin) }
550 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
552 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
553 /// offset of `3 * size_of::<T>()` bytes.
557 /// If any of the following conditions are violated, the result is Undefined
560 /// * Both the starting and resulting pointer must be either in bounds or one
561 /// byte past the end of the same allocated object. Note that in Rust,
562 /// every (stack-allocated) variable is considered a separate allocated object.
564 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
566 /// * The offset being in bounds cannot rely on "wrapping around" the address
567 /// space. That is, the infinite-precision sum must fit in a `usize`.
569 /// The compiler and standard library generally tries to ensure allocations
570 /// never reach a size where an offset is a concern. For instance, `Vec`
571 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
572 /// `vec.as_ptr().add(vec.len())` is always safe.
574 /// Most platforms fundamentally can't even construct such an allocation.
575 /// For instance, no known 64-bit platform can ever serve a request
576 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
577 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
578 /// more than `isize::MAX` bytes with things like Physical Address
579 /// Extension. As such, memory acquired directly from allocators or memory
580 /// mapped files *may* be too large to handle with this function.
582 /// Consider using [`wrapping_add`] instead if these constraints are
583 /// difficult to satisfy. The only advantage of this method is that it
584 /// enables more aggressive compiler optimizations.
586 /// [`wrapping_add`]: #method.wrapping_add
593 /// let s: &str = "123";
594 /// let ptr: *const u8 = s.as_ptr();
597 /// println!("{}", *ptr.add(1) as char);
598 /// println!("{}", *ptr.add(2) as char);
601 #[stable(feature = "pointer_methods", since = "1.26.0")]
602 #[must_use = "returns a new pointer rather than modifying its argument"]
603 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
605 pub const unsafe fn add(self, count: usize) -> Self
609 // SAFETY: the caller must uphold the safety contract for `offset`.
610 unsafe { self.offset(count as isize) }
613 /// Calculates the offset from a pointer (convenience for
614 /// `.offset((count as isize).wrapping_neg())`).
616 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
617 /// offset of `3 * size_of::<T>()` bytes.
621 /// If any of the following conditions are violated, the result is Undefined
624 /// * Both the starting and resulting pointer must be either in bounds or one
625 /// byte past the end of the same allocated object. Note that in Rust,
626 /// every (stack-allocated) variable is considered a separate allocated object.
628 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
630 /// * The offset being in bounds cannot rely on "wrapping around" the address
631 /// space. That is, the infinite-precision sum must fit in a usize.
633 /// The compiler and standard library generally tries to ensure allocations
634 /// never reach a size where an offset is a concern. For instance, `Vec`
635 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
636 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
638 /// Most platforms fundamentally can't even construct such an allocation.
639 /// For instance, no known 64-bit platform can ever serve a request
640 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
641 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
642 /// more than `isize::MAX` bytes with things like Physical Address
643 /// Extension. As such, memory acquired directly from allocators or memory
644 /// mapped files *may* be too large to handle with this function.
646 /// Consider using [`wrapping_sub`] instead if these constraints are
647 /// difficult to satisfy. The only advantage of this method is that it
648 /// enables more aggressive compiler optimizations.
650 /// [`wrapping_sub`]: #method.wrapping_sub
657 /// let s: &str = "123";
660 /// let end: *const u8 = s.as_ptr().add(3);
661 /// println!("{}", *end.sub(1) as char);
662 /// println!("{}", *end.sub(2) as char);
665 #[stable(feature = "pointer_methods", since = "1.26.0")]
666 #[must_use = "returns a new pointer rather than modifying its argument"]
667 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
669 pub const unsafe fn sub(self, count: usize) -> Self
673 // SAFETY: the caller must uphold the safety contract for `offset`.
674 unsafe { self.offset((count as isize).wrapping_neg()) }
677 /// Calculates the offset from a pointer using wrapping arithmetic.
678 /// (convenience for `.wrapping_offset(count as isize)`)
680 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
681 /// offset of `3 * size_of::<T>()` bytes.
685 /// This operation itself is always safe, but using the resulting pointer is not.
687 /// The resulting pointer remains attached to the same allocated object that `self` points to.
688 /// It may *not* be used to access a different allocated object. Note that in Rust, every
689 /// (stack-allocated) variable is considered a separate allocated object.
691 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
692 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
693 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
694 /// `x` and `y` point into the same allocated object.
696 /// Compared to [`add`], this method basically delays the requirement of staying within the
697 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
698 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
699 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
700 /// can be optimized better and is thus preferable in performance-sensitive code.
702 /// The delayed check only considers the value of the pointer that was dereferenced, not the
703 /// intermediate values used during the computation of the final result. For example,
704 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
705 /// allocated object and then re-entering it later is permitted.
707 /// If you need to cross object boundaries, cast the pointer to an integer and
708 /// do the arithmetic there.
710 /// [`add`]: #method.add
717 /// // Iterate using a raw pointer in increments of two elements
718 /// let data = [1u8, 2, 3, 4, 5];
719 /// let mut ptr: *const u8 = data.as_ptr();
721 /// let end_rounded_up = ptr.wrapping_add(6);
723 /// // This loop prints "1, 3, 5, "
724 /// while ptr != end_rounded_up {
726 /// print!("{}, ", *ptr);
728 /// ptr = ptr.wrapping_add(step);
731 #[stable(feature = "pointer_methods", since = "1.26.0")]
732 #[must_use = "returns a new pointer rather than modifying its argument"]
733 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
735 pub const fn wrapping_add(self, count: usize) -> Self
739 self.wrapping_offset(count as isize)
742 /// Calculates the offset from a pointer using wrapping arithmetic.
743 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
745 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
746 /// offset of `3 * size_of::<T>()` bytes.
750 /// This operation itself is always safe, but using the resulting pointer is not.
752 /// The resulting pointer remains attached to the same allocated object that `self` points to.
753 /// It may *not* be used to access a different allocated object. Note that in Rust, every
754 /// (stack-allocated) variable is considered a separate allocated object.
756 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
757 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
758 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
759 /// `x` and `y` point into the same allocated object.
761 /// Compared to [`sub`], this method basically delays the requirement of staying within the
762 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
763 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
764 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
765 /// can be optimized better and is thus preferable in performance-sensitive code.
767 /// The delayed check only considers the value of the pointer that was dereferenced, not the
768 /// intermediate values used during the computation of the final result. For example,
769 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
770 /// allocated object and then re-entering it later is permitted.
772 /// If you need to cross object boundaries, cast the pointer to an integer and
773 /// do the arithmetic there.
775 /// [`sub`]: #method.sub
782 /// // Iterate using a raw pointer in increments of two elements (backwards)
783 /// let data = [1u8, 2, 3, 4, 5];
784 /// let mut ptr: *const u8 = data.as_ptr();
785 /// let start_rounded_down = ptr.wrapping_sub(2);
786 /// ptr = ptr.wrapping_add(4);
788 /// // This loop prints "5, 3, 1, "
789 /// while ptr != start_rounded_down {
791 /// print!("{}, ", *ptr);
793 /// ptr = ptr.wrapping_sub(step);
796 #[stable(feature = "pointer_methods", since = "1.26.0")]
797 #[must_use = "returns a new pointer rather than modifying its argument"]
798 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
800 pub const fn wrapping_sub(self, count: usize) -> Self
804 self.wrapping_offset((count as isize).wrapping_neg())
807 /// Sets the pointer value to `ptr`.
809 /// In case `self` is a (fat) pointer to an unsized type, this operation
810 /// will only affect the pointer part, whereas for (thin) pointers to
811 /// sized types, this has the same effect as a simple assignment.
813 /// The resulting pointer will have provenance of `val`, i.e., for a fat
814 /// pointer, this operation is semantically the same as creating a new
815 /// fat pointer with the data pointer value of `val` but the metadata of
820 /// This function is primarily useful for allowing byte-wise pointer
821 /// arithmetic on potentially fat pointers:
824 /// #![feature(set_ptr_value)]
825 /// # use core::fmt::Debug;
826 /// let mut arr: [i32; 3] = [1, 2, 3];
827 /// let mut ptr = &mut arr[0] as *mut dyn Debug;
828 /// let thin = ptr as *mut u8;
830 /// ptr = ptr.set_ptr_value(thin.add(8));
831 /// # assert_eq!(*(ptr as *mut i32), 3);
832 /// println!("{:?}", &*ptr); // will print "3"
835 #[unstable(feature = "set_ptr_value", issue = "75091")]
836 #[must_use = "returns a new pointer rather than modifying its argument"]
838 pub fn set_ptr_value(mut self, val: *mut u8) -> Self {
839 let thin = &mut self as *mut *mut T as *mut *mut u8;
840 // SAFETY: In case of a thin pointer, this operations is identical
841 // to a simple assignment. In case of a fat pointer, with the current
842 // fat pointer layout implementation, the first field of such a
843 // pointer is always the data pointer, which is likewise assigned.
844 unsafe { *thin = val };
848 /// Reads the value from `self` without moving it. This leaves the
849 /// memory in `self` unchanged.
851 /// See [`ptr::read`] for safety concerns and examples.
853 /// [`ptr::read`]: crate::ptr::read()
854 #[stable(feature = "pointer_methods", since = "1.26.0")]
855 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
857 pub const unsafe fn read(self) -> T
861 // SAFETY: the caller must uphold the safety contract for ``.
862 unsafe { read(self) }
865 /// Performs a volatile read of the value from `self` without moving it. This
866 /// leaves the memory in `self` unchanged.
868 /// Volatile operations are intended to act on I/O memory, and are guaranteed
869 /// to not be elided or reordered by the compiler across other volatile
872 /// See [`ptr::read_volatile`] for safety concerns and examples.
874 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
875 #[stable(feature = "pointer_methods", since = "1.26.0")]
877 pub unsafe fn read_volatile(self) -> T
881 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
882 unsafe { read_volatile(self) }
885 /// Reads the value from `self` without moving it. This leaves the
886 /// memory in `self` unchanged.
888 /// Unlike `read`, the pointer may be unaligned.
890 /// See [`ptr::read_unaligned`] for safety concerns and examples.
892 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
893 #[stable(feature = "pointer_methods", since = "1.26.0")]
894 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
896 pub const unsafe fn read_unaligned(self) -> T
900 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
901 unsafe { read_unaligned(self) }
904 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
905 /// and destination may overlap.
907 /// NOTE: this has the *same* argument order as [`ptr::copy`].
909 /// See [`ptr::copy`] for safety concerns and examples.
911 /// [`ptr::copy`]: crate::ptr::copy()
912 #[stable(feature = "pointer_methods", since = "1.26.0")]
914 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
918 // SAFETY: the caller must uphold the safety contract for `copy`.
919 unsafe { copy(self, dest, count) }
922 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
923 /// and destination may *not* overlap.
925 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
927 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
929 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
930 #[stable(feature = "pointer_methods", since = "1.26.0")]
932 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
936 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
937 unsafe { copy_nonoverlapping(self, dest, count) }
940 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
941 /// and destination may overlap.
943 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
945 /// See [`ptr::copy`] for safety concerns and examples.
947 /// [`ptr::copy`]: crate::ptr::copy()
948 #[stable(feature = "pointer_methods", since = "1.26.0")]
950 pub unsafe fn copy_from(self, src: *const T, count: usize)
954 // SAFETY: the caller must uphold the safety contract for `copy`.
955 unsafe { copy(src, self, count) }
958 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
959 /// and destination may *not* overlap.
961 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
963 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
965 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
966 #[stable(feature = "pointer_methods", since = "1.26.0")]
968 pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
972 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
973 unsafe { copy_nonoverlapping(src, self, count) }
976 /// Executes the destructor (if any) of the pointed-to value.
978 /// See [`ptr::drop_in_place`] for safety concerns and examples.
980 /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
981 #[stable(feature = "pointer_methods", since = "1.26.0")]
983 pub unsafe fn drop_in_place(self) {
984 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
985 unsafe { drop_in_place(self) }
988 /// Overwrites a memory location with the given value without reading or
989 /// dropping the old value.
991 /// See [`ptr::write`] for safety concerns and examples.
993 /// [`ptr::write`]: crate::ptr::write()
994 #[stable(feature = "pointer_methods", since = "1.26.0")]
996 pub unsafe fn write(self, val: T)
1000 // SAFETY: the caller must uphold the safety contract for `write`.
1001 unsafe { write(self, val) }
1004 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1005 /// bytes of memory starting at `self` to `val`.
1007 /// See [`ptr::write_bytes`] for safety concerns and examples.
1009 /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1010 #[stable(feature = "pointer_methods", since = "1.26.0")]
1012 pub unsafe fn write_bytes(self, val: u8, count: usize)
1016 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1017 unsafe { write_bytes(self, val, count) }
1020 /// Performs a volatile write of a memory location with the given value without
1021 /// reading or dropping the old value.
1023 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1024 /// to not be elided or reordered by the compiler across other volatile
1027 /// See [`ptr::write_volatile`] for safety concerns and examples.
1029 /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1030 #[stable(feature = "pointer_methods", since = "1.26.0")]
1032 pub unsafe fn write_volatile(self, val: T)
1036 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1037 unsafe { write_volatile(self, val) }
1040 /// Overwrites a memory location with the given value without reading or
1041 /// dropping the old value.
1043 /// Unlike `write`, the pointer may be unaligned.
1045 /// See [`ptr::write_unaligned`] for safety concerns and examples.
1047 /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1048 #[stable(feature = "pointer_methods", since = "1.26.0")]
1050 pub unsafe fn write_unaligned(self, val: T)
1054 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1055 unsafe { write_unaligned(self, val) }
1058 /// Replaces the value at `self` with `src`, returning the old
1059 /// value, without dropping either.
1061 /// See [`ptr::replace`] for safety concerns and examples.
1063 /// [`ptr::replace`]: crate::ptr::replace()
1064 #[stable(feature = "pointer_methods", since = "1.26.0")]
1066 pub unsafe fn replace(self, src: T) -> T
1070 // SAFETY: the caller must uphold the safety contract for `replace`.
1071 unsafe { replace(self, src) }
1074 /// Swaps the values at two mutable locations of the same type, without
1075 /// deinitializing either. They may overlap, unlike `mem::swap` which is
1076 /// otherwise equivalent.
1078 /// See [`ptr::swap`] for safety concerns and examples.
1080 /// [`ptr::swap`]: crate::ptr::swap()
1081 #[stable(feature = "pointer_methods", since = "1.26.0")]
1083 pub unsafe fn swap(self, with: *mut T)
1087 // SAFETY: the caller must uphold the safety contract for `swap`.
1088 unsafe { swap(self, with) }
1091 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1094 /// If it is not possible to align the pointer, the implementation returns
1095 /// `usize::MAX`. It is permissible for the implementation to *always*
1096 /// return `usize::MAX`. Only your algorithm's performance can depend
1097 /// on getting a usable offset here, not its correctness.
1099 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1100 /// used with the `wrapping_add` method.
1102 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1103 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1104 /// the returned offset is correct in all terms other than alignment.
1108 /// The function panics if `align` is not a power-of-two.
1112 /// Accessing adjacent `u8` as `u16`
1115 /// # fn foo(n: usize) {
1116 /// # use std::mem::align_of;
1118 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1119 /// let ptr = x.as_ptr().add(n) as *const u8;
1120 /// let offset = ptr.align_offset(align_of::<u16>());
1121 /// if offset < x.len() - n - 1 {
1122 /// let u16_ptr = ptr.add(offset) as *const u16;
1123 /// assert_ne!(*u16_ptr, 500);
1125 /// // while the pointer can be aligned via `offset`, it would point
1126 /// // outside the allocation
1130 #[stable(feature = "align_offset", since = "1.36.0")]
1131 pub fn align_offset(self, align: usize) -> usize
1135 if !align.is_power_of_two() {
1136 panic!("align_offset: align is not a power-of-two");
1138 // SAFETY: `align` has been checked to be a power of 2 above
1139 unsafe { align_offset(self, align) }
1143 #[lang = "mut_slice_ptr"]
1145 /// Returns the length of a raw slice.
1147 /// The returned value is the number of **elements**, not the number of bytes.
1149 /// This function is safe, even when the raw slice cannot be cast to a slice
1150 /// reference because the pointer is null or unaligned.
1155 /// #![feature(slice_ptr_len)]
1158 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1159 /// assert_eq!(slice.len(), 3);
1162 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1163 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1164 pub const fn len(self) -> usize {
1165 // SAFETY: this is safe because `*const [T]` and `FatPtr<T>` have the same layout.
1166 // Only `std` can make this guarantee.
1167 unsafe { Repr { rust_mut: self }.raw }.len
1170 /// Returns a raw pointer to the slice's buffer.
1172 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
1177 /// #![feature(slice_ptr_get)]
1180 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1181 /// assert_eq!(slice.as_mut_ptr(), 0 as *mut i8);
1184 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1185 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
1186 pub const fn as_mut_ptr(self) -> *mut T {
1190 /// Returns a raw pointer to an element or subslice, without doing bounds
1193 /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
1194 /// is *[undefined behavior]* even if the resulting pointer is not used.
1196 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1201 /// #![feature(slice_ptr_get)]
1203 /// let x = &mut [1, 2, 4] as *mut [i32];
1206 /// assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
1209 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1211 pub unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
1215 // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
1216 unsafe { index.get_unchecked_mut(self) }
1219 /// Returns `None` if the pointer is null, or else returns a shared slice to
1220 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1221 /// that the value has to be initialized.
1223 /// For the mutable counterpart see [`as_uninit_slice_mut`].
1225 /// [`as_ref`]: #method.as_ref-1
1226 /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
1230 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
1231 /// all of the following is true:
1233 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1234 /// and it must be properly aligned. This means in particular:
1236 /// * The entire memory range of this slice must be contained within a single allocated object!
1237 /// Slices can never span across multiple allocated objects.
1239 /// * The pointer must be aligned even for zero-length slices. One
1240 /// reason for this is that enum layout optimizations may rely on references
1241 /// (including slices of any length) being aligned and non-null to distinguish
1242 /// them from other data. You can obtain a pointer that is usable as `data`
1243 /// for zero-length slices using [`NonNull::dangling()`].
1245 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1246 /// See the safety documentation of [`pointer::offset`].
1248 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1249 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1250 /// In particular, for the duration of this lifetime, the memory the pointer points to must
1251 /// not get mutated (except inside `UnsafeCell`).
1253 /// This applies even if the result of this method is unused!
1255 /// See also [`slice::from_raw_parts`][].
1257 /// [valid]: crate::ptr#safety
1258 /// [`NonNull::dangling()`]: NonNull::dangling
1259 /// [`pointer::offset`]: ../std/primitive.pointer.html#method.offset
1261 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1262 pub unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1266 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1267 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1271 /// Returns `None` if the pointer is null, or else returns a unique slice to
1272 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
1273 /// that the value has to be initialized.
1275 /// For the shared counterpart see [`as_uninit_slice`].
1277 /// [`as_mut`]: #method.as_mut
1278 /// [`as_uninit_slice`]: #method.as_uninit_slice-1
1282 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
1283 /// all of the following is true:
1285 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
1286 /// many bytes, and it must be properly aligned. This means in particular:
1288 /// * The entire memory range of this slice must be contained within a single allocated object!
1289 /// Slices can never span across multiple allocated objects.
1291 /// * The pointer must be aligned even for zero-length slices. One
1292 /// reason for this is that enum layout optimizations may rely on references
1293 /// (including slices of any length) being aligned and non-null to distinguish
1294 /// them from other data. You can obtain a pointer that is usable as `data`
1295 /// for zero-length slices using [`NonNull::dangling()`].
1297 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1298 /// See the safety documentation of [`pointer::offset`].
1300 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1301 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1302 /// In particular, for the duration of this lifetime, the memory the pointer points to must
1303 /// not get accessed (read or written) through any other pointer.
1305 /// This applies even if the result of this method is unused!
1307 /// See also [`slice::from_raw_parts_mut`][].
1309 /// [valid]: crate::ptr#safety
1310 /// [`NonNull::dangling()`]: NonNull::dangling
1311 /// [`pointer::offset`]: ../std/primitive.pointer.html#method.offset
1313 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1314 pub unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
1318 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
1319 Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
1324 // Equality for pointers
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 impl<T: ?Sized> PartialEq for *mut T {
1328 fn eq(&self, other: &*mut T) -> bool {
1333 #[stable(feature = "rust1", since = "1.0.0")]
1334 impl<T: ?Sized> Eq for *mut T {}
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 impl<T: ?Sized> Ord for *mut T {
1339 fn cmp(&self, other: &*mut T) -> Ordering {
1342 } else if self == other {
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 impl<T: ?Sized> PartialOrd for *mut T {
1353 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
1354 Some(self.cmp(other))
1358 fn lt(&self, other: &*mut T) -> bool {
1363 fn le(&self, other: &*mut T) -> bool {
1368 fn gt(&self, other: &*mut T) -> bool {
1373 fn ge(&self, other: &*mut T) -> bool {