2 use crate::cmp::Ordering::{self, Equal, Greater, Less};
4 use crate::slice::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
20 /// let mut s = [1, 2, 3];
21 /// let ptr: *mut u32 = s.as_mut_ptr();
22 /// assert!(!ptr.is_null());
24 #[stable(feature = "rust1", since = "1.0.0")]
26 pub fn is_null(self) -> bool {
27 // Compare via a cast to a thin pointer, so fat pointers are only
28 // considering their "data" part for null-ness.
29 (self as *mut u8) == null_mut()
32 /// Casts to a pointer of another type.
33 #[stable(feature = "ptr_cast", since = "1.38.0")]
34 #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
36 pub const fn cast<U>(self) -> *mut U {
40 /// Returns `None` if the pointer is null, or else returns a reference to
41 /// the value wrapped in `Some`.
45 /// While this method and its mutable counterpart are useful for
46 /// null-safety, it is important to note that this is still an unsafe
47 /// operation because the returned value could be pointing to invalid
50 /// When calling this method, you have to ensure that if the pointer is
51 /// non-NULL, then it is properly aligned, dereferenceable (for the whole
52 /// size of `T`) and points to an initialized instance of `T`. This applies
53 /// even if the result of this method is unused!
54 /// (The part about being initialized is not yet fully decided, but until
55 /// it is, the only safe approach is to ensure that they are indeed initialized.)
57 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
58 /// not necessarily reflect the actual lifetime of the data. It is up to the
59 /// caller to ensure that for the duration of this lifetime, the memory this
60 /// pointer points to does not get written to outside of `UnsafeCell<U>`.
67 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
70 /// if let Some(val_back) = ptr.as_ref() {
71 /// println!("We got back the value: {}!", val_back);
76 /// # Null-unchecked version
78 /// If you are sure the pointer can never be null and are looking for some kind of
79 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
80 /// dereference the pointer directly.
83 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
86 /// let val_back = &*ptr;
87 /// println!("We got back the value: {}!", val_back);
90 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
92 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
93 // SAFETY: the caller must guarantee that `self` is valid for a
94 // reference if it isn't null.
95 if self.is_null() { None } else { unsafe { Some(&*self) } }
98 /// Calculates the offset from a pointer.
100 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
101 /// offset of `3 * size_of::<T>()` bytes.
105 /// If any of the following conditions are violated, the result is Undefined
108 /// * Both the starting and resulting pointer must be either in bounds or one
109 /// byte past the end of the same allocated object. Note that in Rust,
110 /// every (stack-allocated) variable is considered a separate allocated object.
112 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
114 /// * The offset being in bounds cannot rely on "wrapping around" the address
115 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
117 /// The compiler and standard library generally tries to ensure allocations
118 /// never reach a size where an offset is a concern. For instance, `Vec`
119 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
120 /// `vec.as_ptr().add(vec.len())` is always safe.
122 /// Most platforms fundamentally can't even construct such an allocation.
123 /// For instance, no known 64-bit platform can ever serve a request
124 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
125 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
126 /// more than `isize::MAX` bytes with things like Physical Address
127 /// Extension. As such, memory acquired directly from allocators or memory
128 /// mapped files *may* be too large to handle with this function.
130 /// Consider using [`wrapping_offset`] instead if these constraints are
131 /// difficult to satisfy. The only advantage of this method is that it
132 /// enables more aggressive compiler optimizations.
134 /// [`wrapping_offset`]: #method.wrapping_offset
141 /// let mut s = [1, 2, 3];
142 /// let ptr: *mut u32 = s.as_mut_ptr();
145 /// println!("{}", *ptr.offset(1));
146 /// println!("{}", *ptr.offset(2));
149 #[stable(feature = "rust1", since = "1.0.0")]
150 #[must_use = "returns a new pointer rather than modifying its argument"]
151 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
153 pub const unsafe fn offset(self, count: isize) -> *mut T
157 // SAFETY: the caller must uphold the safety contract for `offset`.
158 // The obtained pointer is valid for writes since the caller must
159 // guarantee that it points to the same allocated object as `self`.
160 unsafe { intrinsics::offset(self, count) as *mut T }
163 /// Calculates the offset from a pointer using wrapping arithmetic.
164 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
165 /// offset of `3 * size_of::<T>()` bytes.
169 /// The resulting pointer does not need to be in bounds, but it is
170 /// potentially hazardous to dereference (which requires `unsafe`).
172 /// In particular, the resulting pointer remains attached to the same allocated
173 /// object that `self` points to. It may *not* be used to access a
174 /// different allocated object. Note that in Rust,
175 /// every (stack-allocated) variable is considered a separate allocated object.
177 /// In other words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
178 /// *not* the same as `y`, and dereferencing it is undefined behavior
179 /// unless `x` and `y` point into the same allocated object.
181 /// Compared to [`offset`], this method basically delays the requirement of staying
182 /// within the same allocated object: [`offset`] is immediate Undefined Behavior when
183 /// crossing object boundaries; `wrapping_offset` produces a pointer but still leads
184 /// to Undefined Behavior if that pointer is dereferenced. [`offset`] can be optimized
185 /// better and is thus preferable in performance-sensitive code.
187 /// If you need to cross object boundaries, cast the pointer to an integer and
188 /// do the arithmetic there.
190 /// [`offset`]: #method.offset
197 /// // Iterate using a raw pointer in increments of two elements
198 /// let mut data = [1u8, 2, 3, 4, 5];
199 /// let mut ptr: *mut u8 = data.as_mut_ptr();
201 /// let end_rounded_up = ptr.wrapping_offset(6);
203 /// while ptr != end_rounded_up {
207 /// ptr = ptr.wrapping_offset(step);
209 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
211 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
212 #[must_use = "returns a new pointer rather than modifying its argument"]
213 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
215 pub const fn wrapping_offset(self, count: isize) -> *mut T
219 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
220 unsafe { intrinsics::arith_offset(self, count) as *mut T }
223 /// Returns `None` if the pointer is null, or else returns a mutable
224 /// reference to the value wrapped in `Some`.
228 /// As with [`as_ref`], this is unsafe because it cannot verify the validity
229 /// of the returned pointer, nor can it ensure that the lifetime `'a`
230 /// returned is indeed a valid lifetime for the contained data.
232 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
233 /// all of the following is true:
234 /// - it is properly aligned
235 /// - it must point to an initialized instance of T; in particular, the pointer must be
236 /// "dereferenceable" in the sense defined [here].
238 /// This applies even if the result of this method is unused!
239 /// (The part about being initialized is not yet fully decided, but until
240 /// it is the only safe approach is to ensure that they are indeed initialized.)
242 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
243 /// not necessarily reflect the actual lifetime of the data. *You* must enforce
244 /// Rust's aliasing rules. In particular, for the duration of this lifetime,
245 /// the memory this pointer points to must not get accessed (read or written)
246 /// through any other pointer.
248 /// [here]: crate::ptr#safety
249 /// [`as_ref`]: #method.as_ref
256 /// let mut s = [1, 2, 3];
257 /// let ptr: *mut u32 = s.as_mut_ptr();
258 /// let first_value = unsafe { ptr.as_mut().unwrap() };
259 /// *first_value = 4;
260 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
263 /// # Null-unchecked version
265 /// If you are sure the pointer can never be null and are looking for some kind of
266 /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
267 /// you can dereference the pointer directly.
270 /// let mut s = [1, 2, 3];
271 /// let ptr: *mut u32 = s.as_mut_ptr();
272 /// let first_value = unsafe { &mut *ptr };
273 /// *first_value = 4;
274 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
276 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
278 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
279 // SAFETY: the caller must guarantee that `self` is be valid for
280 // a mutable reference if it isn't null.
281 if self.is_null() { None } else { unsafe { Some(&mut *self) } }
284 /// Returns whether two pointers are guaranteed to be equal.
286 /// At runtime this function behaves like `self == other`.
287 /// However, in some contexts (e.g., compile-time evaluation),
288 /// it is not always possible to determine equality of two pointers, so this function may
289 /// spuriously return `false` for pointers that later actually turn out to be equal.
290 /// But when it returns `true`, the pointers are guaranteed to be equal.
292 /// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
293 /// comparisons for which both functions return `false`.
295 /// [`guaranteed_ne`]: #method.guaranteed_ne
297 /// The return value may change depending on the compiler version and unsafe code may not
298 /// rely on the result of this function for soundness. It is suggested to only use this function
299 /// for performance optimizations where spurious `false` return values by this function do not
300 /// affect the outcome, but just the performance.
301 /// The consequences of using this method to make runtime and compile-time code behave
302 /// differently have not been explored. This method should not be used to introduce such
303 /// differences, and it should also not be stabilized before we have a better understanding
305 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
306 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
308 #[cfg(not(bootstrap))]
309 pub const fn guaranteed_eq(self, other: *mut T) -> bool
313 intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _)
316 /// Returns whether two pointers are guaranteed to be inequal.
318 /// At runtime this function behaves like `self != other`.
319 /// However, in some contexts (e.g., compile-time evaluation),
320 /// it is not always possible to determine the inequality of two pointers, so this function may
321 /// spuriously return `false` for pointers that later actually turn out to be inequal.
322 /// But when it returns `true`, the pointers are guaranteed to be inequal.
324 /// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
325 /// comparisons for which both functions return `false`.
327 /// [`guaranteed_eq`]: #method.guaranteed_eq
329 /// The return value may change depending on the compiler version and unsafe code may not
330 /// rely on the result of this function for soundness. It is suggested to only use this function
331 /// for performance optimizations where spurious `false` return values by this function do not
332 /// affect the outcome, but just the performance.
333 /// The consequences of using this method to make runtime and compile-time code behave
334 /// differently have not been explored. This method should not be used to introduce such
335 /// differences, and it should also not be stabilized before we have a better understanding
337 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
338 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
340 #[cfg(not(bootstrap))]
341 pub const unsafe fn guaranteed_ne(self, other: *mut T) -> bool
345 intrinsics::ptr_guaranteed_ne(self as *const _, other as *const _)
348 /// Calculates the distance between two pointers. The returned value is in
349 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
351 /// This function is the inverse of [`offset`].
353 /// [`offset`]: #method.offset-1
354 /// [`wrapping_offset_from`]: #method.wrapping_offset_from-1
358 /// If any of the following conditions are violated, the result is Undefined
361 /// * Both the starting and other pointer must be either in bounds or one
362 /// byte past the end of the same allocated object. Note that in Rust,
363 /// every (stack-allocated) variable is considered a separate allocated object.
365 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
367 /// * The distance between the pointers, in bytes, must be an exact multiple
368 /// of the size of `T`.
370 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
372 /// The compiler and standard library generally try to ensure allocations
373 /// never reach a size where an offset is a concern. For instance, `Vec`
374 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
375 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
377 /// Most platforms fundamentally can't even construct such an allocation.
378 /// For instance, no known 64-bit platform can ever serve a request
379 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
380 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
381 /// more than `isize::MAX` bytes with things like Physical Address
382 /// Extension. As such, memory acquired directly from allocators or memory
383 /// mapped files *may* be too large to handle with this function.
385 /// Consider using [`wrapping_offset_from`] instead if these constraints are
386 /// difficult to satisfy. The only advantage of this method is that it
387 /// enables more aggressive compiler optimizations.
391 /// This function panics if `T` is a Zero-Sized Type ("ZST").
398 /// #![feature(ptr_offset_from)]
400 /// let mut a = [0; 5];
401 /// let ptr1: *mut i32 = &mut a[1];
402 /// let ptr2: *mut i32 = &mut a[3];
404 /// assert_eq!(ptr2.offset_from(ptr1), 2);
405 /// assert_eq!(ptr1.offset_from(ptr2), -2);
406 /// assert_eq!(ptr1.offset(2), ptr2);
407 /// assert_eq!(ptr2.offset(-2), ptr1);
410 #[unstable(feature = "ptr_offset_from", issue = "41079")]
411 #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")]
413 pub const unsafe fn offset_from(self, origin: *const T) -> isize
417 // SAFETY: the caller must uphold the safety contract for `offset_from`.
418 unsafe { (self as *const T).offset_from(origin) }
421 /// Calculates the distance between two pointers. The returned value is in
422 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
424 /// If the address different between the two pointers is not a multiple of
425 /// `mem::size_of::<T>()` then the result of the division is rounded towards
428 /// Though this method is safe for any two pointers, note that its result
429 /// will be mostly useless if the two pointers aren't into the same allocated
430 /// object, for example if they point to two different local variables.
434 /// This function panics if `T` is a zero-sized type.
441 /// #![feature(ptr_wrapping_offset_from)]
443 /// let mut a = [0; 5];
444 /// let ptr1: *mut i32 = &mut a[1];
445 /// let ptr2: *mut i32 = &mut a[3];
446 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
447 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
448 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
449 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
451 /// let ptr1: *mut i32 = 3 as _;
452 /// let ptr2: *mut i32 = 13 as _;
453 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
455 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
458 reason = "Pointer distances across allocation \
459 boundaries are not typically meaningful. \
460 Use integer subtraction if you really need this."
463 pub fn wrapping_offset_from(self, origin: *const T) -> isize
467 #[allow(deprecated_in_future, deprecated)]
468 (self as *const T).wrapping_offset_from(origin)
471 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
473 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
474 /// offset of `3 * size_of::<T>()` bytes.
478 /// If any of the following conditions are violated, the result is Undefined
481 /// * Both the starting and resulting pointer must be either in bounds or one
482 /// byte past the end of the same allocated object. Note that in Rust,
483 /// every (stack-allocated) variable is considered a separate allocated object.
485 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
487 /// * The offset being in bounds cannot rely on "wrapping around" the address
488 /// space. That is, the infinite-precision sum must fit in a `usize`.
490 /// The compiler and standard library generally tries 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 /// `vec.as_ptr().add(vec.len())` 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.
503 /// Consider using [`wrapping_add`] instead if these constraints are
504 /// difficult to satisfy. The only advantage of this method is that it
505 /// enables more aggressive compiler optimizations.
507 /// [`wrapping_add`]: #method.wrapping_add
514 /// let s: &str = "123";
515 /// let ptr: *const u8 = s.as_ptr();
518 /// println!("{}", *ptr.add(1) as char);
519 /// println!("{}", *ptr.add(2) as char);
522 #[stable(feature = "pointer_methods", since = "1.26.0")]
523 #[must_use = "returns a new pointer rather than modifying its argument"]
524 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
526 pub const unsafe fn add(self, count: usize) -> Self
530 // SAFETY: the caller must uphold the safety contract for `offset`.
531 unsafe { self.offset(count as isize) }
534 /// Calculates the offset from a pointer (convenience for
535 /// `.offset((count as isize).wrapping_neg())`).
537 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
538 /// offset of `3 * size_of::<T>()` bytes.
542 /// If any of the following conditions are violated, the result is Undefined
545 /// * Both the starting and resulting pointer must be either in bounds or one
546 /// byte past the end of the same allocated object. Note that in Rust,
547 /// every (stack-allocated) variable is considered a separate allocated object.
549 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
551 /// * The offset being in bounds cannot rely on "wrapping around" the address
552 /// space. That is, the infinite-precision sum must fit in a usize.
554 /// The compiler and standard library generally tries to ensure allocations
555 /// never reach a size where an offset is a concern. For instance, `Vec`
556 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
557 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
559 /// Most platforms fundamentally can't even construct such an allocation.
560 /// For instance, no known 64-bit platform can ever serve a request
561 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
562 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
563 /// more than `isize::MAX` bytes with things like Physical Address
564 /// Extension. As such, memory acquired directly from allocators or memory
565 /// mapped files *may* be too large to handle with this function.
567 /// Consider using [`wrapping_sub`] instead if these constraints are
568 /// difficult to satisfy. The only advantage of this method is that it
569 /// enables more aggressive compiler optimizations.
571 /// [`wrapping_sub`]: #method.wrapping_sub
578 /// let s: &str = "123";
581 /// let end: *const u8 = s.as_ptr().add(3);
582 /// println!("{}", *end.sub(1) as char);
583 /// println!("{}", *end.sub(2) as char);
586 #[stable(feature = "pointer_methods", since = "1.26.0")]
587 #[must_use = "returns a new pointer rather than modifying its argument"]
588 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
590 pub const unsafe fn sub(self, count: usize) -> Self
594 // SAFETY: the caller must uphold the safety contract for `offset`.
595 unsafe { self.offset((count as isize).wrapping_neg()) }
598 /// Calculates the offset from a pointer using wrapping arithmetic.
599 /// (convenience for `.wrapping_offset(count as isize)`)
601 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
602 /// offset of `3 * size_of::<T>()` bytes.
606 /// The resulting pointer does not need to be in bounds, but it is
607 /// potentially hazardous to dereference (which requires `unsafe`).
609 /// In particular, the resulting pointer remains attached to the same allocated
610 /// object that `self` points to. It may *not* be used to access a
611 /// different allocated object. Note that in Rust,
612 /// every (stack-allocated) variable is considered a separate allocated object.
614 /// Compared to [`add`], this method basically delays the requirement of staying
615 /// within the same allocated object: [`add`] is immediate Undefined Behavior when
616 /// crossing object boundaries; `wrapping_add` produces a pointer but still leads
617 /// to Undefined Behavior if that pointer is dereferenced. [`add`] can be optimized
618 /// better and is thus preferable in performance-sensitive code.
620 /// If you need to cross object boundaries, cast the pointer to an integer and
621 /// do the arithmetic there.
623 /// [`add`]: #method.add
630 /// // Iterate using a raw pointer in increments of two elements
631 /// let data = [1u8, 2, 3, 4, 5];
632 /// let mut ptr: *const u8 = data.as_ptr();
634 /// let end_rounded_up = ptr.wrapping_add(6);
636 /// // This loop prints "1, 3, 5, "
637 /// while ptr != end_rounded_up {
639 /// print!("{}, ", *ptr);
641 /// ptr = ptr.wrapping_add(step);
644 #[stable(feature = "pointer_methods", since = "1.26.0")]
645 #[must_use = "returns a new pointer rather than modifying its argument"]
646 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
648 pub const fn wrapping_add(self, count: usize) -> Self
652 self.wrapping_offset(count as isize)
655 /// Calculates the offset from a pointer using wrapping arithmetic.
656 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
658 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
659 /// offset of `3 * size_of::<T>()` bytes.
663 /// The resulting pointer does not need to be in bounds, but it is
664 /// potentially hazardous to dereference (which requires `unsafe`).
666 /// In particular, the resulting pointer remains attached to the same allocated
667 /// object that `self` points to. It may *not* be used to access a
668 /// different allocated object. Note that in Rust,
669 /// every (stack-allocated) variable is considered a separate allocated object.
671 /// Compared to [`sub`], this method basically delays the requirement of staying
672 /// within the same allocated object: [`sub`] is immediate Undefined Behavior when
673 /// crossing object boundaries; `wrapping_sub` produces a pointer but still leads
674 /// to Undefined Behavior if that pointer is dereferenced. [`sub`] can be optimized
675 /// better and is thus preferable in performance-sensitive code.
677 /// If you need to cross object boundaries, cast the pointer to an integer and
678 /// do the arithmetic there.
680 /// [`sub`]: #method.sub
687 /// // Iterate using a raw pointer in increments of two elements (backwards)
688 /// let data = [1u8, 2, 3, 4, 5];
689 /// let mut ptr: *const u8 = data.as_ptr();
690 /// let start_rounded_down = ptr.wrapping_sub(2);
691 /// ptr = ptr.wrapping_add(4);
693 /// // This loop prints "5, 3, 1, "
694 /// while ptr != start_rounded_down {
696 /// print!("{}, ", *ptr);
698 /// ptr = ptr.wrapping_sub(step);
701 #[stable(feature = "pointer_methods", since = "1.26.0")]
702 #[must_use = "returns a new pointer rather than modifying its argument"]
703 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
705 pub const fn wrapping_sub(self, count: usize) -> Self
709 self.wrapping_offset((count as isize).wrapping_neg())
712 /// Reads the value from `self` without moving it. This leaves the
713 /// memory in `self` unchanged.
715 /// See [`ptr::read`] for safety concerns and examples.
717 /// [`ptr::read`]: ./ptr/fn.read.html
718 #[stable(feature = "pointer_methods", since = "1.26.0")]
720 pub unsafe fn read(self) -> T
724 // SAFETY: the caller must uphold the safety contract for ``.
725 unsafe { read(self) }
728 /// Performs a volatile read of the value from `self` without moving it. This
729 /// leaves the memory in `self` unchanged.
731 /// Volatile operations are intended to act on I/O memory, and are guaranteed
732 /// to not be elided or reordered by the compiler across other volatile
735 /// See [`ptr::read_volatile`] for safety concerns and examples.
737 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
738 #[stable(feature = "pointer_methods", since = "1.26.0")]
740 pub unsafe fn read_volatile(self) -> T
744 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
745 unsafe { read_volatile(self) }
748 /// Reads the value from `self` without moving it. This leaves the
749 /// memory in `self` unchanged.
751 /// Unlike `read`, the pointer may be unaligned.
753 /// See [`ptr::read_unaligned`] for safety concerns and examples.
755 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
756 #[stable(feature = "pointer_methods", since = "1.26.0")]
758 pub unsafe fn read_unaligned(self) -> T
762 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
763 unsafe { read_unaligned(self) }
766 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
767 /// and destination may overlap.
769 /// NOTE: this has the *same* argument order as [`ptr::copy`].
771 /// See [`ptr::copy`] for safety concerns and examples.
773 /// [`ptr::copy`]: ./ptr/fn.copy.html
774 #[stable(feature = "pointer_methods", since = "1.26.0")]
776 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
780 // SAFETY: the caller must uphold the safety contract for `copy`.
781 unsafe { copy(self, dest, count) }
784 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
785 /// and destination may *not* overlap.
787 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
789 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
791 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
792 #[stable(feature = "pointer_methods", since = "1.26.0")]
794 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
798 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
799 unsafe { copy_nonoverlapping(self, dest, count) }
802 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
803 /// and destination may overlap.
805 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
807 /// See [`ptr::copy`] for safety concerns and examples.
809 /// [`ptr::copy`]: ./ptr/fn.copy.html
810 #[stable(feature = "pointer_methods", since = "1.26.0")]
812 pub unsafe fn copy_from(self, src: *const T, count: usize)
816 // SAFETY: the caller must uphold the safety contract for `copy`.
817 unsafe { copy(src, self, count) }
820 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
821 /// and destination may *not* overlap.
823 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
825 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
827 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
828 #[stable(feature = "pointer_methods", since = "1.26.0")]
830 pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
834 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
835 unsafe { copy_nonoverlapping(src, self, count) }
838 /// Executes the destructor (if any) of the pointed-to value.
840 /// See [`ptr::drop_in_place`] for safety concerns and examples.
842 /// [`ptr::drop_in_place`]: ./ptr/fn.drop_in_place.html
843 #[stable(feature = "pointer_methods", since = "1.26.0")]
845 pub unsafe fn drop_in_place(self) {
846 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
847 unsafe { drop_in_place(self) }
850 /// Overwrites a memory location with the given value without reading or
851 /// dropping the old value.
853 /// See [`ptr::write`] for safety concerns and examples.
855 /// [`ptr::write`]: ./ptr/fn.write.html
856 #[stable(feature = "pointer_methods", since = "1.26.0")]
858 pub unsafe fn write(self, val: T)
862 // SAFETY: the caller must uphold the safety contract for `write`.
863 unsafe { write(self, val) }
866 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
867 /// bytes of memory starting at `self` to `val`.
869 /// See [`ptr::write_bytes`] for safety concerns and examples.
871 /// [`ptr::write_bytes`]: ./ptr/fn.write_bytes.html
872 #[stable(feature = "pointer_methods", since = "1.26.0")]
874 pub unsafe fn write_bytes(self, val: u8, count: usize)
878 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
879 unsafe { write_bytes(self, val, count) }
882 /// Performs a volatile write of a memory location with the given value without
883 /// reading or dropping the old value.
885 /// Volatile operations are intended to act on I/O memory, and are guaranteed
886 /// to not be elided or reordered by the compiler across other volatile
889 /// See [`ptr::write_volatile`] for safety concerns and examples.
891 /// [`ptr::write_volatile`]: ./ptr/fn.write_volatile.html
892 #[stable(feature = "pointer_methods", since = "1.26.0")]
894 pub unsafe fn write_volatile(self, val: T)
898 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
899 unsafe { write_volatile(self, val) }
902 /// Overwrites a memory location with the given value without reading or
903 /// dropping the old value.
905 /// Unlike `write`, the pointer may be unaligned.
907 /// See [`ptr::write_unaligned`] for safety concerns and examples.
909 /// [`ptr::write_unaligned`]: ./ptr/fn.write_unaligned.html
910 #[stable(feature = "pointer_methods", since = "1.26.0")]
912 pub unsafe fn write_unaligned(self, val: T)
916 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
917 unsafe { write_unaligned(self, val) }
920 /// Replaces the value at `self` with `src`, returning the old
921 /// value, without dropping either.
923 /// See [`ptr::replace`] for safety concerns and examples.
925 /// [`ptr::replace`]: ./ptr/fn.replace.html
926 #[stable(feature = "pointer_methods", since = "1.26.0")]
928 pub unsafe fn replace(self, src: T) -> T
932 // SAFETY: the caller must uphold the safety contract for `replace`.
933 unsafe { replace(self, src) }
936 /// Swaps the values at two mutable locations of the same type, without
937 /// deinitializing either. They may overlap, unlike `mem::swap` which is
938 /// otherwise equivalent.
940 /// See [`ptr::swap`] for safety concerns and examples.
942 /// [`ptr::swap`]: ./ptr/fn.swap.html
943 #[stable(feature = "pointer_methods", since = "1.26.0")]
945 pub unsafe fn swap(self, with: *mut T)
949 // SAFETY: the caller must uphold the safety contract for `swap`.
950 unsafe { swap(self, with) }
953 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
956 /// If it is not possible to align the pointer, the implementation returns
957 /// `usize::MAX`. It is permissible for the implementation to *always*
958 /// return `usize::MAX`. Only your algorithm's performance can depend
959 /// on getting a usable offset here, not its correctness.
961 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
962 /// used with the `wrapping_add` method.
964 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
965 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
966 /// the returned offset is correct in all terms other than alignment.
970 /// The function panics if `align` is not a power-of-two.
974 /// Accessing adjacent `u8` as `u16`
977 /// # fn foo(n: usize) {
978 /// # use std::mem::align_of;
980 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
981 /// let ptr = &x[n] as *const u8;
982 /// let offset = ptr.align_offset(align_of::<u16>());
983 /// if offset < x.len() - n - 1 {
984 /// let u16_ptr = ptr.add(offset) as *const u16;
985 /// assert_ne!(*u16_ptr, 500);
987 /// // while the pointer can be aligned via `offset`, it would point
988 /// // outside the allocation
992 #[stable(feature = "align_offset", since = "1.36.0")]
993 pub fn align_offset(self, align: usize) -> usize
997 if !align.is_power_of_two() {
998 panic!("align_offset: align is not a power-of-two");
1000 // SAFETY: `align` has been checked to be a power of 2 above
1001 unsafe { align_offset(self, align) }
1005 #[lang = "mut_slice_ptr"]
1007 /// Returns the length of a raw slice.
1009 /// The returned value is the number of **elements**, not the number of bytes.
1011 /// This function is safe, even when the raw slice cannot be cast to a slice
1012 /// reference because the pointer is null or unaligned.
1017 /// #![feature(slice_ptr_len)]
1020 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1021 /// assert_eq!(slice.len(), 3);
1024 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1025 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1026 pub const fn len(self) -> usize {
1027 // SAFETY: this is safe because `*const [T]` and `FatPtr<T>` have the same layout.
1028 // Only `std` can make this guarantee.
1029 unsafe { Repr { rust_mut: self }.raw }.len
1032 /// Returns a raw pointer to the slice's buffer.
1034 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
1039 /// #![feature(slice_ptr_get)]
1042 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1043 /// assert_eq!(slice.as_mut_ptr(), 0 as *mut i8);
1046 #[unstable(feature = "slice_ptr_get", issue = "none")]
1047 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "none")]
1048 pub const fn as_mut_ptr(self) -> *mut T {
1052 /// Returns a raw pointer to an element or subslice, without doing bounds
1055 /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
1056 /// is *[undefined behavior]* even if the resulting pointer is not used.
1058 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1063 /// #![feature(slice_ptr_get)]
1065 /// let x = &mut [1, 2, 4] as *mut [i32];
1068 /// assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
1071 #[unstable(feature = "slice_ptr_get", issue = "none")]
1073 pub unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
1077 // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
1078 unsafe { index.get_unchecked_mut(self) }
1082 // Equality for pointers
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 impl<T: ?Sized> PartialEq for *mut T {
1086 fn eq(&self, other: &*mut T) -> bool {
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 impl<T: ?Sized> Eq for *mut T {}
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 impl<T: ?Sized> Ord for *mut T {
1097 fn cmp(&self, other: &*mut T) -> Ordering {
1100 } else if self == other {
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 impl<T: ?Sized> PartialOrd for *mut T {
1111 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
1112 Some(self.cmp(other))
1116 fn lt(&self, other: &*mut T) -> bool {
1121 fn le(&self, other: &*mut T) -> bool {
1126 fn gt(&self, other: &*mut T) -> bool {
1131 fn ge(&self, other: &*mut T) -> bool {