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
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 reference to
51 /// the value wrapped in `Some`.
55 /// While this method and its mutable counterpart are useful for
56 /// null-safety, it is important to note that this is still an unsafe
57 /// operation because the returned value could be pointing to invalid
60 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
61 /// all of the following is true:
62 /// - it is properly aligned
63 /// - it must point to an initialized instance of T; in particular, the pointer must be
64 /// "dereferencable" in the sense defined [here].
66 /// This applies even if the result of this method is unused!
67 /// (The part about being initialized is not yet fully decided, but until
68 /// it is, the only safe approach is to ensure that they are indeed initialized.)
70 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
71 /// not necessarily reflect the actual lifetime of the data. *You* must enforce
72 /// Rust's aliasing rules. In particular, for the duration of this lifetime,
73 /// the memory the pointer points to must not get mutated (except inside `UnsafeCell`).
75 /// [here]: crate::ptr#safety
82 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
85 /// if let Some(val_back) = ptr.as_ref() {
86 /// println!("We got back the value: {}!", val_back);
91 /// # Null-unchecked version
93 /// If you are sure the pointer can never be null and are looking for some kind of
94 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
95 /// dereference the pointer directly.
98 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
101 /// let val_back = &*ptr;
102 /// println!("We got back the value: {}!", val_back);
105 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
107 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
108 // SAFETY: the caller must guarantee that `self` is valid for a
109 // reference if it isn't null.
110 if self.is_null() { None } else { unsafe { Some(&*self) } }
113 /// Calculates the offset from a pointer.
115 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
116 /// offset of `3 * size_of::<T>()` bytes.
120 /// If any of the following conditions are violated, the result is Undefined
123 /// * Both the starting and resulting pointer must be either in bounds or one
124 /// byte past the end of the same allocated object. Note that in Rust,
125 /// every (stack-allocated) variable is considered a separate allocated object.
127 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
129 /// * The offset being in bounds cannot rely on "wrapping around" the address
130 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
132 /// The compiler and standard library generally tries to ensure allocations
133 /// never reach a size where an offset is a concern. For instance, `Vec`
134 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
135 /// `vec.as_ptr().add(vec.len())` is always safe.
137 /// Most platforms fundamentally can't even construct such an allocation.
138 /// For instance, no known 64-bit platform can ever serve a request
139 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
140 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
141 /// more than `isize::MAX` bytes with things like Physical Address
142 /// Extension. As such, memory acquired directly from allocators or memory
143 /// mapped files *may* be too large to handle with this function.
145 /// Consider using [`wrapping_offset`] instead if these constraints are
146 /// difficult to satisfy. The only advantage of this method is that it
147 /// enables more aggressive compiler optimizations.
149 /// [`wrapping_offset`]: #method.wrapping_offset
156 /// let mut s = [1, 2, 3];
157 /// let ptr: *mut u32 = s.as_mut_ptr();
160 /// println!("{}", *ptr.offset(1));
161 /// println!("{}", *ptr.offset(2));
164 #[stable(feature = "rust1", since = "1.0.0")]
165 #[must_use = "returns a new pointer rather than modifying its argument"]
166 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
168 pub const unsafe fn offset(self, count: isize) -> *mut T
172 // SAFETY: the caller must uphold the safety contract for `offset`.
173 // The obtained pointer is valid for writes since the caller must
174 // guarantee that it points to the same allocated object as `self`.
175 unsafe { intrinsics::offset(self, count) as *mut T }
178 /// Calculates the offset from a pointer using wrapping arithmetic.
179 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
180 /// offset of `3 * size_of::<T>()` bytes.
184 /// The resulting pointer does not need to be in bounds, but it is
185 /// potentially hazardous to dereference (which requires `unsafe`).
187 /// In particular, the resulting pointer remains attached to the same allocated
188 /// object that `self` points to. It may *not* be used to access a
189 /// different allocated object. Note that in Rust,
190 /// every (stack-allocated) variable is considered a separate allocated object.
192 /// In other words, `x.wrapping_offset(y.wrapping_offset_from(x))` is
193 /// *not* the same as `y`, and dereferencing it is undefined behavior
194 /// unless `x` and `y` point into the same allocated object.
196 /// Compared to [`offset`], this method basically delays the requirement of staying
197 /// within the same allocated object: [`offset`] is immediate Undefined Behavior when
198 /// crossing object boundaries; `wrapping_offset` produces a pointer but still leads
199 /// to Undefined Behavior if that pointer is dereferenced. [`offset`] can be optimized
200 /// better and is thus preferable in performance-sensitive code.
202 /// If you need to cross object boundaries, cast the pointer to an integer and
203 /// do the arithmetic there.
205 /// [`offset`]: #method.offset
212 /// // Iterate using a raw pointer in increments of two elements
213 /// let mut data = [1u8, 2, 3, 4, 5];
214 /// let mut ptr: *mut u8 = data.as_mut_ptr();
216 /// let end_rounded_up = ptr.wrapping_offset(6);
218 /// while ptr != end_rounded_up {
222 /// ptr = ptr.wrapping_offset(step);
224 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
226 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
227 #[must_use = "returns a new pointer rather than modifying its argument"]
228 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
230 pub const fn wrapping_offset(self, count: isize) -> *mut T
234 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
235 unsafe { intrinsics::arith_offset(self, count) as *mut T }
238 /// Returns `None` if the pointer is null, or else returns a mutable
239 /// reference to the value wrapped in `Some`.
243 /// As with [`as_ref`], this is unsafe because it cannot verify the validity
244 /// of the returned pointer, nor can it ensure that the lifetime `'a`
245 /// returned is indeed a valid lifetime for the contained data.
247 /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
248 /// all of the following is true:
249 /// - it is properly aligned
250 /// - it must point to an initialized instance of T; in particular, the pointer must be
251 /// "dereferenceable" in the sense defined [here].
253 /// This applies even if the result of this method is unused!
254 /// (The part about being initialized is not yet fully decided, but until
255 /// it is the only safe approach is to ensure that they are indeed initialized.)
257 /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
258 /// not necessarily reflect the actual lifetime of the data. *You* must enforce
259 /// Rust's aliasing rules. In particular, for the duration of this lifetime,
260 /// the memory this pointer points to must not get accessed (read or written)
261 /// through any other pointer.
263 /// [here]: crate::ptr#safety
264 /// [`as_ref`]: #method.as_ref
271 /// let mut s = [1, 2, 3];
272 /// let ptr: *mut u32 = s.as_mut_ptr();
273 /// let first_value = unsafe { ptr.as_mut().unwrap() };
274 /// *first_value = 4;
275 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
278 /// # Null-unchecked version
280 /// If you are sure the pointer can never be null and are looking for some kind of
281 /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
282 /// you can dereference the pointer directly.
285 /// let mut s = [1, 2, 3];
286 /// let ptr: *mut u32 = s.as_mut_ptr();
287 /// let first_value = unsafe { &mut *ptr };
288 /// *first_value = 4;
289 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
291 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
293 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
294 // SAFETY: the caller must guarantee that `self` is be valid for
295 // a mutable reference if it isn't null.
296 if self.is_null() { None } else { unsafe { Some(&mut *self) } }
299 /// Returns whether two pointers are guaranteed to be equal.
301 /// At runtime this function behaves like `self == other`.
302 /// However, in some contexts (e.g., compile-time evaluation),
303 /// it is not always possible to determine equality of two pointers, so this function may
304 /// spuriously return `false` for pointers that later actually turn out to be equal.
305 /// But when it returns `true`, the pointers are guaranteed to be equal.
307 /// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
308 /// comparisons for which both functions return `false`.
310 /// [`guaranteed_ne`]: #method.guaranteed_ne
312 /// The return value may change depending on the compiler version and unsafe code may not
313 /// rely on the result of this function for soundness. It is suggested to only use this function
314 /// for performance optimizations where spurious `false` return values by this function do not
315 /// affect the outcome, but just the performance.
316 /// The consequences of using this method to make runtime and compile-time code behave
317 /// differently have not been explored. This method should not be used to introduce such
318 /// differences, and it should also not be stabilized before we have a better understanding
320 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
321 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
323 pub const fn guaranteed_eq(self, other: *mut T) -> bool
327 intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _)
330 /// Returns whether two pointers are guaranteed to be unequal.
332 /// At runtime this function behaves like `self != other`.
333 /// However, in some contexts (e.g., compile-time evaluation),
334 /// it is not always possible to determine the inequality of two pointers, so this function may
335 /// spuriously return `false` for pointers that later actually turn out to be unequal.
336 /// But when it returns `true`, the pointers are guaranteed to be unequal.
338 /// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
339 /// comparisons for which both functions return `false`.
341 /// [`guaranteed_eq`]: #method.guaranteed_eq
343 /// The return value may change depending on the compiler version and unsafe code may not
344 /// rely on the result of this function for soundness. It is suggested to only use this function
345 /// for performance optimizations where spurious `false` return values by this function do not
346 /// affect the outcome, but just the performance.
347 /// The consequences of using this method to make runtime and compile-time code behave
348 /// differently have not been explored. This method should not be used to introduce such
349 /// differences, and it should also not be stabilized before we have a better understanding
351 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
352 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
354 pub const unsafe fn guaranteed_ne(self, other: *mut T) -> bool
358 intrinsics::ptr_guaranteed_ne(self as *const _, other as *const _)
361 /// Calculates the distance between two pointers. The returned value is in
362 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
364 /// This function is the inverse of [`offset`].
366 /// [`offset`]: #method.offset-1
367 /// [`wrapping_offset_from`]: #method.wrapping_offset_from-1
371 /// If any of the following conditions are violated, the result is Undefined
374 /// * Both the starting and other pointer must be either in bounds or one
375 /// byte past the end of the same allocated object. Note that in Rust,
376 /// every (stack-allocated) variable is considered a separate allocated object.
378 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
380 /// * The distance between the pointers, in bytes, must be an exact multiple
381 /// of the size of `T`.
383 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
385 /// The compiler and standard library generally try to ensure allocations
386 /// never reach a size where an offset is a concern. For instance, `Vec`
387 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
388 /// `ptr_into_vec.offset_from(vec.as_ptr())` is always safe.
390 /// Most platforms fundamentally can't even construct such an allocation.
391 /// For instance, no known 64-bit platform can ever serve a request
392 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
393 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
394 /// more than `isize::MAX` bytes with things like Physical Address
395 /// Extension. As such, memory acquired directly from allocators or memory
396 /// mapped files *may* be too large to handle with this function.
398 /// Consider using [`wrapping_offset_from`] instead if these constraints are
399 /// difficult to satisfy. The only advantage of this method is that it
400 /// enables more aggressive compiler optimizations.
404 /// This function panics if `T` is a Zero-Sized Type ("ZST").
411 /// #![feature(ptr_offset_from)]
413 /// let mut a = [0; 5];
414 /// let ptr1: *mut i32 = &mut a[1];
415 /// let ptr2: *mut i32 = &mut a[3];
417 /// assert_eq!(ptr2.offset_from(ptr1), 2);
418 /// assert_eq!(ptr1.offset_from(ptr2), -2);
419 /// assert_eq!(ptr1.offset(2), ptr2);
420 /// assert_eq!(ptr2.offset(-2), ptr1);
423 #[unstable(feature = "ptr_offset_from", issue = "41079")]
424 #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")]
426 pub const unsafe fn offset_from(self, origin: *const T) -> isize
430 // SAFETY: the caller must uphold the safety contract for `offset_from`.
431 unsafe { (self as *const T).offset_from(origin) }
434 /// Calculates the distance between two pointers. The returned value is in
435 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
437 /// If the address different between the two pointers is not a multiple of
438 /// `mem::size_of::<T>()` then the result of the division is rounded towards
441 /// Though this method is safe for any two pointers, note that its result
442 /// will be mostly useless if the two pointers aren't into the same allocated
443 /// object, for example if they point to two different local variables.
447 /// This function panics if `T` is a zero-sized type.
454 /// #![feature(ptr_wrapping_offset_from)]
456 /// let mut a = [0; 5];
457 /// let ptr1: *mut i32 = &mut a[1];
458 /// let ptr2: *mut i32 = &mut a[3];
459 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
460 /// assert_eq!(ptr1.wrapping_offset_from(ptr2), -2);
461 /// assert_eq!(ptr1.wrapping_offset(2), ptr2);
462 /// assert_eq!(ptr2.wrapping_offset(-2), ptr1);
464 /// let ptr1: *mut i32 = 3 as _;
465 /// let ptr2: *mut i32 = 13 as _;
466 /// assert_eq!(ptr2.wrapping_offset_from(ptr1), 2);
468 #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")]
471 reason = "Pointer distances across allocation \
472 boundaries are not typically meaningful. \
473 Use integer subtraction if you really need this."
476 pub fn wrapping_offset_from(self, origin: *const T) -> isize
480 #[allow(deprecated_in_future, deprecated)]
481 (self as *const T).wrapping_offset_from(origin)
484 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
486 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
487 /// offset of `3 * size_of::<T>()` bytes.
491 /// If any of the following conditions are violated, the result is Undefined
494 /// * Both the starting and resulting pointer must be either in bounds or one
495 /// byte past the end of the same allocated object. Note that in Rust,
496 /// every (stack-allocated) variable is considered a separate allocated object.
498 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
500 /// * The offset being in bounds cannot rely on "wrapping around" the address
501 /// space. That is, the infinite-precision sum must fit in a `usize`.
503 /// The compiler and standard library generally tries to ensure allocations
504 /// never reach a size where an offset is a concern. For instance, `Vec`
505 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
506 /// `vec.as_ptr().add(vec.len())` is always safe.
508 /// Most platforms fundamentally can't even construct such an allocation.
509 /// For instance, no known 64-bit platform can ever serve a request
510 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
511 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
512 /// more than `isize::MAX` bytes with things like Physical Address
513 /// Extension. As such, memory acquired directly from allocators or memory
514 /// mapped files *may* be too large to handle with this function.
516 /// Consider using [`wrapping_add`] instead if these constraints are
517 /// difficult to satisfy. The only advantage of this method is that it
518 /// enables more aggressive compiler optimizations.
520 /// [`wrapping_add`]: #method.wrapping_add
527 /// let s: &str = "123";
528 /// let ptr: *const u8 = s.as_ptr();
531 /// println!("{}", *ptr.add(1) as char);
532 /// println!("{}", *ptr.add(2) as char);
535 #[stable(feature = "pointer_methods", since = "1.26.0")]
536 #[must_use = "returns a new pointer rather than modifying its argument"]
537 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
539 pub const unsafe fn add(self, count: usize) -> Self
543 // SAFETY: the caller must uphold the safety contract for `offset`.
544 unsafe { self.offset(count as isize) }
547 /// Calculates the offset from a pointer (convenience for
548 /// `.offset((count as isize).wrapping_neg())`).
550 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
551 /// offset of `3 * size_of::<T>()` bytes.
555 /// If any of the following conditions are violated, the result is Undefined
558 /// * Both the starting and resulting pointer must be either in bounds or one
559 /// byte past the end of the same allocated object. Note that in Rust,
560 /// every (stack-allocated) variable is considered a separate allocated object.
562 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
564 /// * The offset being in bounds cannot rely on "wrapping around" the address
565 /// space. That is, the infinite-precision sum must fit in a usize.
567 /// The compiler and standard library generally tries to ensure allocations
568 /// never reach a size where an offset is a concern. For instance, `Vec`
569 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
570 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
572 /// Most platforms fundamentally can't even construct such an allocation.
573 /// For instance, no known 64-bit platform can ever serve a request
574 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
575 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
576 /// more than `isize::MAX` bytes with things like Physical Address
577 /// Extension. As such, memory acquired directly from allocators or memory
578 /// mapped files *may* be too large to handle with this function.
580 /// Consider using [`wrapping_sub`] instead if these constraints are
581 /// difficult to satisfy. The only advantage of this method is that it
582 /// enables more aggressive compiler optimizations.
584 /// [`wrapping_sub`]: #method.wrapping_sub
591 /// let s: &str = "123";
594 /// let end: *const u8 = s.as_ptr().add(3);
595 /// println!("{}", *end.sub(1) as char);
596 /// println!("{}", *end.sub(2) as char);
599 #[stable(feature = "pointer_methods", since = "1.26.0")]
600 #[must_use = "returns a new pointer rather than modifying its argument"]
601 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
603 pub const unsafe fn sub(self, count: usize) -> Self
607 // SAFETY: the caller must uphold the safety contract for `offset`.
608 unsafe { self.offset((count as isize).wrapping_neg()) }
611 /// Calculates the offset from a pointer using wrapping arithmetic.
612 /// (convenience for `.wrapping_offset(count as isize)`)
614 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
615 /// offset of `3 * size_of::<T>()` bytes.
619 /// The resulting pointer does not need to be in bounds, but it is
620 /// potentially hazardous to dereference (which requires `unsafe`).
622 /// In particular, the resulting pointer remains attached to the same allocated
623 /// object that `self` points to. It may *not* be used to access a
624 /// different allocated object. Note that in Rust,
625 /// every (stack-allocated) variable is considered a separate allocated object.
627 /// Compared to [`add`], this method basically delays the requirement of staying
628 /// within the same allocated object: [`add`] is immediate Undefined Behavior when
629 /// crossing object boundaries; `wrapping_add` produces a pointer but still leads
630 /// to Undefined Behavior if that pointer is dereferenced. [`add`] can be optimized
631 /// better and is thus preferable in performance-sensitive code.
633 /// If you need to cross object boundaries, cast the pointer to an integer and
634 /// do the arithmetic there.
636 /// [`add`]: #method.add
643 /// // Iterate using a raw pointer in increments of two elements
644 /// let data = [1u8, 2, 3, 4, 5];
645 /// let mut ptr: *const u8 = data.as_ptr();
647 /// let end_rounded_up = ptr.wrapping_add(6);
649 /// // This loop prints "1, 3, 5, "
650 /// while ptr != end_rounded_up {
652 /// print!("{}, ", *ptr);
654 /// ptr = ptr.wrapping_add(step);
657 #[stable(feature = "pointer_methods", since = "1.26.0")]
658 #[must_use = "returns a new pointer rather than modifying its argument"]
659 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
661 pub const fn wrapping_add(self, count: usize) -> Self
665 self.wrapping_offset(count as isize)
668 /// Calculates the offset from a pointer using wrapping arithmetic.
669 /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
671 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
672 /// offset of `3 * size_of::<T>()` bytes.
676 /// The resulting pointer does not need to be in bounds, but it is
677 /// potentially hazardous to dereference (which requires `unsafe`).
679 /// In particular, the resulting pointer remains attached to the same allocated
680 /// object that `self` points to. It may *not* be used to access a
681 /// different allocated object. Note that in Rust,
682 /// every (stack-allocated) variable is considered a separate allocated object.
684 /// Compared to [`sub`], this method basically delays the requirement of staying
685 /// within the same allocated object: [`sub`] is immediate Undefined Behavior when
686 /// crossing object boundaries; `wrapping_sub` produces a pointer but still leads
687 /// to Undefined Behavior if that pointer is dereferenced. [`sub`] can be optimized
688 /// better and is thus preferable in performance-sensitive code.
690 /// If you need to cross object boundaries, cast the pointer to an integer and
691 /// do the arithmetic there.
693 /// [`sub`]: #method.sub
700 /// // Iterate using a raw pointer in increments of two elements (backwards)
701 /// let data = [1u8, 2, 3, 4, 5];
702 /// let mut ptr: *const u8 = data.as_ptr();
703 /// let start_rounded_down = ptr.wrapping_sub(2);
704 /// ptr = ptr.wrapping_add(4);
706 /// // This loop prints "5, 3, 1, "
707 /// while ptr != start_rounded_down {
709 /// print!("{}, ", *ptr);
711 /// ptr = ptr.wrapping_sub(step);
714 #[stable(feature = "pointer_methods", since = "1.26.0")]
715 #[must_use = "returns a new pointer rather than modifying its argument"]
716 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
718 pub const fn wrapping_sub(self, count: usize) -> Self
722 self.wrapping_offset((count as isize).wrapping_neg())
725 /// Sets the pointer value to `ptr`.
727 /// In case `self` is a (fat) pointer to an unsized type, this operation
728 /// will only affect the pointer part, whereas for (thin) pointers to
729 /// sized types, this has the same effect as a simple assignment.
731 /// The resulting pointer will have provenance of `val`, i.e., for a fat
732 /// pointer, this operation is semantically the same as creating a new
733 /// fat pointer with the data pointer value of `val` but the metadata of
738 /// This function is primarily useful for allowing byte-wise pointer
739 /// arithmetic on potentially fat pointers:
742 /// #![feature(set_ptr_value)]
743 /// # use core::fmt::Debug;
744 /// let mut arr: [i32; 3] = [1, 2, 3];
745 /// let mut ptr = &mut arr[0] as *mut dyn Debug;
746 /// let thin = ptr as *mut u8;
748 /// ptr = ptr.set_ptr_value(thin.add(8));
749 /// # assert_eq!(*(ptr as *mut i32), 3);
750 /// println!("{:?}", &*ptr); // will print "3"
753 #[unstable(feature = "set_ptr_value", issue = "75091")]
754 #[must_use = "returns a new pointer rather than modifying its argument"]
756 pub fn set_ptr_value(mut self, val: *mut u8) -> Self {
757 let thin = &mut self as *mut *mut T as *mut *mut u8;
758 // SAFETY: In case of a thin pointer, this operations is identical
759 // to a simple assignment. In case of a fat pointer, with the current
760 // fat pointer layout implementation, the first field of such a
761 // pointer is always the data pointer, which is likewise assigned.
762 unsafe { *thin = val };
766 /// Reads the value from `self` without moving it. This leaves the
767 /// memory in `self` unchanged.
769 /// See [`ptr::read`] for safety concerns and examples.
771 /// [`ptr::read`]: ./ptr/fn.read.html
772 #[stable(feature = "pointer_methods", since = "1.26.0")]
774 pub unsafe fn read(self) -> T
778 // SAFETY: the caller must uphold the safety contract for ``.
779 unsafe { read(self) }
782 /// Performs a volatile read of the value from `self` without moving it. This
783 /// leaves the memory in `self` unchanged.
785 /// Volatile operations are intended to act on I/O memory, and are guaranteed
786 /// to not be elided or reordered by the compiler across other volatile
789 /// See [`ptr::read_volatile`] for safety concerns and examples.
791 /// [`ptr::read_volatile`]: ./ptr/fn.read_volatile.html
792 #[stable(feature = "pointer_methods", since = "1.26.0")]
794 pub unsafe fn read_volatile(self) -> T
798 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
799 unsafe { read_volatile(self) }
802 /// Reads the value from `self` without moving it. This leaves the
803 /// memory in `self` unchanged.
805 /// Unlike `read`, the pointer may be unaligned.
807 /// See [`ptr::read_unaligned`] for safety concerns and examples.
809 /// [`ptr::read_unaligned`]: ./ptr/fn.read_unaligned.html
810 #[stable(feature = "pointer_methods", since = "1.26.0")]
812 pub unsafe fn read_unaligned(self) -> T
816 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
817 unsafe { read_unaligned(self) }
820 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
821 /// and destination may overlap.
823 /// NOTE: this has the *same* argument order as [`ptr::copy`].
825 /// See [`ptr::copy`] for safety concerns and examples.
827 /// [`ptr::copy`]: ./ptr/fn.copy.html
828 #[stable(feature = "pointer_methods", since = "1.26.0")]
830 pub unsafe fn copy_to(self, dest: *mut T, count: usize)
834 // SAFETY: the caller must uphold the safety contract for `copy`.
835 unsafe { copy(self, dest, count) }
838 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
839 /// and destination may *not* overlap.
841 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
843 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
845 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
846 #[stable(feature = "pointer_methods", since = "1.26.0")]
848 pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
852 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
853 unsafe { copy_nonoverlapping(self, dest, count) }
856 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
857 /// and destination may overlap.
859 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
861 /// See [`ptr::copy`] for safety concerns and examples.
863 /// [`ptr::copy`]: ./ptr/fn.copy.html
864 #[stable(feature = "pointer_methods", since = "1.26.0")]
866 pub unsafe fn copy_from(self, src: *const T, count: usize)
870 // SAFETY: the caller must uphold the safety contract for `copy`.
871 unsafe { copy(src, self, count) }
874 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
875 /// and destination may *not* overlap.
877 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
879 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
881 /// [`ptr::copy_nonoverlapping`]: ./ptr/fn.copy_nonoverlapping.html
882 #[stable(feature = "pointer_methods", since = "1.26.0")]
884 pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
888 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
889 unsafe { copy_nonoverlapping(src, self, count) }
892 /// Executes the destructor (if any) of the pointed-to value.
894 /// See [`ptr::drop_in_place`] for safety concerns and examples.
896 /// [`ptr::drop_in_place`]: ./ptr/fn.drop_in_place.html
897 #[stable(feature = "pointer_methods", since = "1.26.0")]
899 pub unsafe fn drop_in_place(self) {
900 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
901 unsafe { drop_in_place(self) }
904 /// Overwrites a memory location with the given value without reading or
905 /// dropping the old value.
907 /// See [`ptr::write`] for safety concerns and examples.
909 /// [`ptr::write`]: ./ptr/fn.write.html
910 #[stable(feature = "pointer_methods", since = "1.26.0")]
912 pub unsafe fn write(self, val: T)
916 // SAFETY: the caller must uphold the safety contract for `write`.
917 unsafe { write(self, val) }
920 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
921 /// bytes of memory starting at `self` to `val`.
923 /// See [`ptr::write_bytes`] for safety concerns and examples.
925 /// [`ptr::write_bytes`]: ./ptr/fn.write_bytes.html
926 #[stable(feature = "pointer_methods", since = "1.26.0")]
928 pub unsafe fn write_bytes(self, val: u8, count: usize)
932 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
933 unsafe { write_bytes(self, val, count) }
936 /// Performs a volatile write of a memory location with the given value without
937 /// reading or dropping the old value.
939 /// Volatile operations are intended to act on I/O memory, and are guaranteed
940 /// to not be elided or reordered by the compiler across other volatile
943 /// See [`ptr::write_volatile`] for safety concerns and examples.
945 /// [`ptr::write_volatile`]: ./ptr/fn.write_volatile.html
946 #[stable(feature = "pointer_methods", since = "1.26.0")]
948 pub unsafe fn write_volatile(self, val: T)
952 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
953 unsafe { write_volatile(self, val) }
956 /// Overwrites a memory location with the given value without reading or
957 /// dropping the old value.
959 /// Unlike `write`, the pointer may be unaligned.
961 /// See [`ptr::write_unaligned`] for safety concerns and examples.
963 /// [`ptr::write_unaligned`]: ./ptr/fn.write_unaligned.html
964 #[stable(feature = "pointer_methods", since = "1.26.0")]
966 pub unsafe fn write_unaligned(self, val: T)
970 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
971 unsafe { write_unaligned(self, val) }
974 /// Replaces the value at `self` with `src`, returning the old
975 /// value, without dropping either.
977 /// See [`ptr::replace`] for safety concerns and examples.
979 /// [`ptr::replace`]: ./ptr/fn.replace.html
980 #[stable(feature = "pointer_methods", since = "1.26.0")]
982 pub unsafe fn replace(self, src: T) -> T
986 // SAFETY: the caller must uphold the safety contract for `replace`.
987 unsafe { replace(self, src) }
990 /// Swaps the values at two mutable locations of the same type, without
991 /// deinitializing either. They may overlap, unlike `mem::swap` which is
992 /// otherwise equivalent.
994 /// See [`ptr::swap`] for safety concerns and examples.
996 /// [`ptr::swap`]: ./ptr/fn.swap.html
997 #[stable(feature = "pointer_methods", since = "1.26.0")]
999 pub unsafe fn swap(self, with: *mut T)
1003 // SAFETY: the caller must uphold the safety contract for `swap`.
1004 unsafe { swap(self, with) }
1007 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1010 /// If it is not possible to align the pointer, the implementation returns
1011 /// `usize::MAX`. It is permissible for the implementation to *always*
1012 /// return `usize::MAX`. Only your algorithm's performance can depend
1013 /// on getting a usable offset here, not its correctness.
1015 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1016 /// used with the `wrapping_add` method.
1018 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1019 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1020 /// the returned offset is correct in all terms other than alignment.
1024 /// The function panics if `align` is not a power-of-two.
1028 /// Accessing adjacent `u8` as `u16`
1031 /// # fn foo(n: usize) {
1032 /// # use std::mem::align_of;
1034 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1035 /// let ptr = &x[n] as *const u8;
1036 /// let offset = ptr.align_offset(align_of::<u16>());
1037 /// if offset < x.len() - n - 1 {
1038 /// let u16_ptr = ptr.add(offset) as *const u16;
1039 /// assert_ne!(*u16_ptr, 500);
1041 /// // while the pointer can be aligned via `offset`, it would point
1042 /// // outside the allocation
1046 #[stable(feature = "align_offset", since = "1.36.0")]
1047 pub fn align_offset(self, align: usize) -> usize
1051 if !align.is_power_of_two() {
1052 panic!("align_offset: align is not a power-of-two");
1054 // SAFETY: `align` has been checked to be a power of 2 above
1055 unsafe { align_offset(self, align) }
1059 #[lang = "mut_slice_ptr"]
1061 /// Returns the length of a raw slice.
1063 /// The returned value is the number of **elements**, not the number of bytes.
1065 /// This function is safe, even when the raw slice cannot be cast to a slice
1066 /// reference because the pointer is null or unaligned.
1071 /// #![feature(slice_ptr_len)]
1074 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1075 /// assert_eq!(slice.len(), 3);
1078 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1079 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1080 pub const fn len(self) -> usize {
1081 // SAFETY: this is safe because `*const [T]` and `FatPtr<T>` have the same layout.
1082 // Only `std` can make this guarantee.
1083 unsafe { Repr { rust_mut: self }.raw }.len
1086 /// Returns a raw pointer to the slice's buffer.
1088 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
1093 /// #![feature(slice_ptr_get)]
1096 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1097 /// assert_eq!(slice.as_mut_ptr(), 0 as *mut i8);
1100 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1101 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
1102 pub const fn as_mut_ptr(self) -> *mut T {
1106 /// Returns a raw pointer to an element or subslice, without doing bounds
1109 /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
1110 /// is *[undefined behavior]* even if the resulting pointer is not used.
1112 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1117 /// #![feature(slice_ptr_get)]
1119 /// let x = &mut [1, 2, 4] as *mut [i32];
1122 /// assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
1125 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1127 pub unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
1131 // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
1132 unsafe { index.get_unchecked_mut(self) }
1136 // Equality for pointers
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 impl<T: ?Sized> PartialEq for *mut T {
1140 fn eq(&self, other: &*mut T) -> bool {
1145 #[stable(feature = "rust1", since = "1.0.0")]
1146 impl<T: ?Sized> Eq for *mut T {}
1148 #[stable(feature = "rust1", since = "1.0.0")]
1149 impl<T: ?Sized> Ord for *mut T {
1151 fn cmp(&self, other: &*mut T) -> Ordering {
1154 } else if self == other {
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 impl<T: ?Sized> PartialOrd for *mut T {
1165 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
1166 Some(self.cmp(other))
1170 fn lt(&self, other: &*mut T) -> bool {
1175 fn le(&self, other: &*mut T) -> bool {
1180 fn gt(&self, other: &*mut T) -> bool {
1185 fn ge(&self, other: &*mut T) -> bool {