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 /// Casts a pointer to its raw bits.
52 /// This is equivalent to `as usize`, but is more specific to enhance readability.
53 /// The inverse method is [`from_bits`](#method.from_bits-1).
55 /// In particular, `*p as usize` and `p as usize` will both compile for
56 /// pointers to numeric types but do very different things, so using this
57 /// helps emphasize that reading the bits was intentional.
62 /// #![feature(ptr_to_from_bits)]
63 /// let mut array = [13, 42];
64 /// let mut it = array.iter_mut();
65 /// let p0: *mut i32 = it.next().unwrap();
66 /// assert_eq!(<*mut _>::from_bits(p0.to_bits()), p0);
67 /// let p1: *mut i32 = it.next().unwrap();
68 /// assert_eq!(p1.to_bits() - p0.to_bits(), 4);
70 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
71 pub fn to_bits(self) -> usize
78 /// Creates a pointer from its raw bits.
80 /// This is equivalent to `as *mut T`, but is more specific to enhance readability.
81 /// The inverse method is [`to_bits`](#method.to_bits-1).
86 /// #![feature(ptr_to_from_bits)]
87 /// use std::ptr::NonNull;
88 /// let dangling: *mut u8 = NonNull::dangling().as_ptr();
89 /// assert_eq!(<*mut u8>::from_bits(1), dangling);
91 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
92 pub fn from_bits(bits: usize) -> Self
99 /// Decompose a (possibly wide) pointer into its address and metadata components.
101 /// The pointer can be later reconstructed with [`from_raw_parts_mut`].
102 #[unstable(feature = "ptr_metadata", issue = "81513")]
103 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
105 pub const fn to_raw_parts(self) -> (*mut (), <T as super::Pointee>::Metadata) {
106 (self.cast(), super::metadata(self))
109 /// Returns `None` if the pointer is null, or else returns a shared reference to
110 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
111 /// must be used instead.
113 /// For the mutable counterpart see [`as_mut`].
115 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
116 /// [`as_mut`]: #method.as_mut
120 /// When calling this method, you have to ensure that *either* the pointer is null *or*
121 /// all of the following is true:
123 /// * The pointer must be properly aligned.
125 /// * It must be "dereferencable" in the sense defined in [the module documentation].
127 /// * The pointer must point to an initialized instance of `T`.
129 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
130 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
131 /// In particular, for the duration of this lifetime, the memory the pointer points to must
132 /// not get mutated (except inside `UnsafeCell`).
134 /// This applies even if the result of this method is unused!
135 /// (The part about being initialized is not yet fully decided, but until
136 /// it is, the only safe approach is to ensure that they are indeed initialized.)
138 /// [the module documentation]: crate::ptr#safety
145 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
148 /// if let Some(val_back) = ptr.as_ref() {
149 /// println!("We got back the value: {}!", val_back);
154 /// # Null-unchecked version
156 /// If you are sure the pointer can never be null and are looking for some kind of
157 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
158 /// dereference the pointer directly.
161 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
164 /// let val_back = &*ptr;
165 /// println!("We got back the value: {}!", val_back);
168 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
170 pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
171 // SAFETY: the caller must guarantee that `self` is valid for a
172 // reference if it isn't null.
173 if self.is_null() { None } else { unsafe { Some(&*self) } }
176 /// Returns `None` if the pointer is null, or else returns a shared reference to
177 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
178 /// that the value has to be initialized.
180 /// For the mutable counterpart see [`as_uninit_mut`].
182 /// [`as_ref`]: #method.as_ref-1
183 /// [`as_uninit_mut`]: #method.as_uninit_mut
187 /// When calling this method, you have to ensure that *either* the pointer is null *or*
188 /// all of the following is true:
190 /// * The pointer must be properly aligned.
192 /// * It must be "dereferencable" in the sense defined in [the module documentation].
194 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
195 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
196 /// In particular, for the duration of this lifetime, the memory the pointer points to must
197 /// not get mutated (except inside `UnsafeCell`).
199 /// This applies even if the result of this method is unused!
201 /// [the module documentation]: crate::ptr#safety
208 /// #![feature(ptr_as_uninit)]
210 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
213 /// if let Some(val_back) = ptr.as_uninit_ref() {
214 /// println!("We got back the value: {}!", val_back.assume_init());
219 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
220 pub unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
224 // SAFETY: the caller must guarantee that `self` meets all the
225 // requirements for a reference.
226 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
229 /// Calculates the offset from a pointer.
231 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
232 /// offset of `3 * size_of::<T>()` bytes.
236 /// If any of the following conditions are violated, the result is Undefined
239 /// * Both the starting and resulting pointer must be either in bounds or one
240 /// byte past the end of the same [allocated object].
242 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
244 /// * The offset being in bounds cannot rely on "wrapping around" the address
245 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
247 /// The compiler and standard library generally tries to ensure allocations
248 /// never reach a size where an offset is a concern. For instance, `Vec`
249 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
250 /// `vec.as_ptr().add(vec.len())` is always safe.
252 /// Most platforms fundamentally can't even construct such an allocation.
253 /// For instance, no known 64-bit platform can ever serve a request
254 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
255 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
256 /// more than `isize::MAX` bytes with things like Physical Address
257 /// Extension. As such, memory acquired directly from allocators or memory
258 /// mapped files *may* be too large to handle with this function.
260 /// Consider using [`wrapping_offset`] instead if these constraints are
261 /// difficult to satisfy. The only advantage of this method is that it
262 /// enables more aggressive compiler optimizations.
264 /// [`wrapping_offset`]: #method.wrapping_offset
265 /// [allocated object]: crate::ptr#allocated-object
272 /// let mut s = [1, 2, 3];
273 /// let ptr: *mut u32 = s.as_mut_ptr();
276 /// println!("{}", *ptr.offset(1));
277 /// println!("{}", *ptr.offset(2));
280 #[stable(feature = "rust1", since = "1.0.0")]
281 #[must_use = "returns a new pointer rather than modifying its argument"]
282 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
284 pub const unsafe fn offset(self, count: isize) -> *mut T
288 // SAFETY: the caller must uphold the safety contract for `offset`.
289 // The obtained pointer is valid for writes since the caller must
290 // guarantee that it points to the same allocated object as `self`.
291 unsafe { intrinsics::offset(self, count) as *mut T }
294 /// Calculates the offset from a pointer using wrapping arithmetic.
295 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
296 /// offset of `3 * size_of::<T>()` bytes.
300 /// This operation itself is always safe, but using the resulting pointer is not.
302 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
303 /// be used to read or write other allocated objects.
305 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
306 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
307 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
308 /// `x` and `y` point into the same allocated object.
310 /// Compared to [`offset`], this method basically delays the requirement of staying within the
311 /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
312 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
313 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
314 /// can be optimized better and is thus preferable in performance-sensitive code.
316 /// The delayed check only considers the value of the pointer that was dereferenced, not the
317 /// intermediate values used during the computation of the final result. For example,
318 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
319 /// words, leaving the allocated object and then re-entering it later is permitted.
321 /// [`offset`]: #method.offset
322 /// [allocated object]: crate::ptr#allocated-object
329 /// // Iterate using a raw pointer in increments of two elements
330 /// let mut data = [1u8, 2, 3, 4, 5];
331 /// let mut ptr: *mut u8 = data.as_mut_ptr();
333 /// let end_rounded_up = ptr.wrapping_offset(6);
335 /// while ptr != end_rounded_up {
339 /// ptr = ptr.wrapping_offset(step);
341 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
343 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
344 #[must_use = "returns a new pointer rather than modifying its argument"]
345 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
347 pub const fn wrapping_offset(self, count: isize) -> *mut T
351 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
352 unsafe { intrinsics::arith_offset(self, count) as *mut T }
355 /// Returns `None` if the pointer is null, or else returns a unique reference to
356 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
357 /// must be used instead.
359 /// For the shared counterpart see [`as_ref`].
361 /// [`as_uninit_mut`]: #method.as_uninit_mut
362 /// [`as_ref`]: #method.as_ref-1
366 /// When calling this method, you have to ensure that *either* the pointer is null *or*
367 /// all of the following is true:
369 /// * The pointer must be properly aligned.
371 /// * It must be "dereferencable" in the sense defined in [the module documentation].
373 /// * The pointer must point to an initialized instance of `T`.
375 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
376 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
377 /// In particular, for the duration of this lifetime, the memory the pointer points to must
378 /// not get accessed (read or written) through any other pointer.
380 /// This applies even if the result of this method is unused!
381 /// (The part about being initialized is not yet fully decided, but until
382 /// it is, the only safe approach is to ensure that they are indeed initialized.)
384 /// [the module documentation]: crate::ptr#safety
391 /// let mut s = [1, 2, 3];
392 /// let ptr: *mut u32 = s.as_mut_ptr();
393 /// let first_value = unsafe { ptr.as_mut().unwrap() };
394 /// *first_value = 4;
395 /// # assert_eq!(s, [4, 2, 3]);
396 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
399 /// # Null-unchecked version
401 /// If you are sure the pointer can never be null and are looking for some kind of
402 /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
403 /// you can dereference the pointer directly.
406 /// let mut s = [1, 2, 3];
407 /// let ptr: *mut u32 = s.as_mut_ptr();
408 /// let first_value = unsafe { &mut *ptr };
409 /// *first_value = 4;
410 /// # assert_eq!(s, [4, 2, 3]);
411 /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
413 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
415 pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
416 // SAFETY: the caller must guarantee that `self` is be valid for
417 // a mutable reference if it isn't null.
418 if self.is_null() { None } else { unsafe { Some(&mut *self) } }
421 /// Returns `None` if the pointer is null, or else returns a unique reference to
422 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
423 /// that the value has to be initialized.
425 /// For the shared counterpart see [`as_uninit_ref`].
427 /// [`as_mut`]: #method.as_mut
428 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
432 /// When calling this method, you have to ensure that *either* the pointer is null *or*
433 /// all of the following is true:
435 /// * The pointer must be properly aligned.
437 /// * It must be "dereferencable" in the sense defined in [the module documentation].
439 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
440 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
441 /// In particular, for the duration of this lifetime, the memory the pointer points to must
442 /// not get accessed (read or written) through any other pointer.
444 /// This applies even if the result of this method is unused!
446 /// [the module documentation]: crate::ptr#safety
448 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
449 pub unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
453 // SAFETY: the caller must guarantee that `self` meets all the
454 // requirements for a reference.
455 if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
458 /// Returns whether two pointers are guaranteed to be equal.
460 /// At runtime this function behaves like `self == other`.
461 /// However, in some contexts (e.g., compile-time evaluation),
462 /// it is not always possible to determine equality of two pointers, so this function may
463 /// spuriously return `false` for pointers that later actually turn out to be equal.
464 /// But when it returns `true`, the pointers are guaranteed to be equal.
466 /// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
467 /// comparisons for which both functions return `false`.
469 /// [`guaranteed_ne`]: #method.guaranteed_ne
471 /// The return value may change depending on the compiler version and unsafe code might not
472 /// rely on the result of this function for soundness. It is suggested to only use this function
473 /// for performance optimizations where spurious `false` return values by this function do not
474 /// affect the outcome, but just the performance.
475 /// The consequences of using this method to make runtime and compile-time code behave
476 /// differently have not been explored. This method should not be used to introduce such
477 /// differences, and it should also not be stabilized before we have a better understanding
479 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
480 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
482 pub const fn guaranteed_eq(self, other: *mut T) -> bool
486 intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _)
489 /// Returns whether two pointers are guaranteed to be unequal.
491 /// At runtime this function behaves like `self != other`.
492 /// However, in some contexts (e.g., compile-time evaluation),
493 /// it is not always possible to determine the inequality of two pointers, so this function may
494 /// spuriously return `false` for pointers that later actually turn out to be unequal.
495 /// But when it returns `true`, the pointers are guaranteed to be unequal.
497 /// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
498 /// comparisons for which both functions return `false`.
500 /// [`guaranteed_eq`]: #method.guaranteed_eq
502 /// The return value may change depending on the compiler version and unsafe code might not
503 /// rely on the result of this function for soundness. It is suggested to only use this function
504 /// for performance optimizations where spurious `false` return values by this function do not
505 /// affect the outcome, but just the performance.
506 /// The consequences of using this method to make runtime and compile-time code behave
507 /// differently have not been explored. This method should not be used to introduce such
508 /// differences, and it should also not be stabilized before we have a better understanding
510 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
511 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
513 pub const unsafe fn guaranteed_ne(self, other: *mut T) -> bool
517 intrinsics::ptr_guaranteed_ne(self as *const _, other as *const _)
520 /// Calculates the distance between two pointers. The returned value is in
521 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
523 /// This function is the inverse of [`offset`].
525 /// [`offset`]: #method.offset-1
529 /// If any of the following conditions are violated, the result is Undefined
532 /// * Both the starting and other pointer must be either in bounds or one
533 /// byte past the end of the same [allocated object].
535 /// * Both pointers must be *derived from* a pointer to the same object.
536 /// (See below for an example.)
538 /// * The distance between the pointers, in bytes, must be an exact multiple
539 /// of the size of `T`.
541 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
543 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
545 /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
546 /// address space, so two pointers within some value of any Rust type `T` will always satisfy
547 /// the last two conditions. The standard library also generally ensures that allocations
548 /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
549 /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
550 /// always satisfies the last two conditions.
552 /// Most platforms fundamentally can't even construct such a large allocation.
553 /// For instance, no known 64-bit platform can ever serve a request
554 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
555 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
556 /// more than `isize::MAX` bytes with things like Physical Address
557 /// Extension. As such, memory acquired directly from allocators or memory
558 /// mapped files *may* be too large to handle with this function.
559 /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
560 /// such large allocations either.)
562 /// [`add`]: #method.add
563 /// [allocated object]: crate::ptr#allocated-object
567 /// This function panics if `T` is a Zero-Sized Type ("ZST").
574 /// let mut a = [0; 5];
575 /// let ptr1: *mut i32 = &mut a[1];
576 /// let ptr2: *mut i32 = &mut a[3];
578 /// assert_eq!(ptr2.offset_from(ptr1), 2);
579 /// assert_eq!(ptr1.offset_from(ptr2), -2);
580 /// assert_eq!(ptr1.offset(2), ptr2);
581 /// assert_eq!(ptr2.offset(-2), ptr1);
585 /// *Incorrect* usage:
588 /// let ptr1 = Box::into_raw(Box::new(0u8));
589 /// let ptr2 = Box::into_raw(Box::new(1u8));
590 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
591 /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
592 /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff);
593 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
594 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
595 /// // computing their offset is undefined behavior, even though
596 /// // they point to the same address!
598 /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
601 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
602 #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")]
604 pub const unsafe fn offset_from(self, origin: *const T) -> isize
608 // SAFETY: the caller must uphold the safety contract for `offset_from`.
609 unsafe { (self as *const T).offset_from(origin) }
612 /// Calculates the offset from a pointer (convenience for `.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 /// If any of the following conditions are violated, the result is Undefined
622 /// * Both the starting and resulting pointer must be either in bounds or one
623 /// byte past the end of the same [allocated object].
625 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
627 /// * The offset being in bounds cannot rely on "wrapping around" the address
628 /// space. That is, the infinite-precision sum must fit in a `usize`.
630 /// The compiler and standard library generally tries to ensure allocations
631 /// never reach a size where an offset is a concern. For instance, `Vec`
632 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
633 /// `vec.as_ptr().add(vec.len())` is always safe.
635 /// Most platforms fundamentally can't even construct such an allocation.
636 /// For instance, no known 64-bit platform can ever serve a request
637 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
638 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
639 /// more than `isize::MAX` bytes with things like Physical Address
640 /// Extension. As such, memory acquired directly from allocators or memory
641 /// mapped files *may* be too large to handle with this function.
643 /// Consider using [`wrapping_add`] instead if these constraints are
644 /// difficult to satisfy. The only advantage of this method is that it
645 /// enables more aggressive compiler optimizations.
647 /// [`wrapping_add`]: #method.wrapping_add
648 /// [allocated object]: crate::ptr#allocated-object
655 /// let s: &str = "123";
656 /// let ptr: *const u8 = s.as_ptr();
659 /// println!("{}", *ptr.add(1) as char);
660 /// println!("{}", *ptr.add(2) as char);
663 #[stable(feature = "pointer_methods", since = "1.26.0")]
664 #[must_use = "returns a new pointer rather than modifying its argument"]
665 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
667 pub const unsafe fn add(self, count: usize) -> Self
671 // SAFETY: the caller must uphold the safety contract for `offset`.
672 unsafe { self.offset(count as isize) }
675 /// Calculates the offset from a pointer (convenience for
676 /// `.offset((count as isize).wrapping_neg())`).
678 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
679 /// offset of `3 * size_of::<T>()` bytes.
683 /// If any of the following conditions are violated, the result is Undefined
686 /// * Both the starting and resulting pointer must be either in bounds or one
687 /// byte past the end of the same [allocated object].
689 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
691 /// * The offset being in bounds cannot rely on "wrapping around" the address
692 /// space. That is, the infinite-precision sum must fit in a usize.
694 /// The compiler and standard library generally tries to ensure allocations
695 /// never reach a size where an offset is a concern. For instance, `Vec`
696 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
697 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
699 /// Most platforms fundamentally can't even construct such an allocation.
700 /// For instance, no known 64-bit platform can ever serve a request
701 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
702 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
703 /// more than `isize::MAX` bytes with things like Physical Address
704 /// Extension. As such, memory acquired directly from allocators or memory
705 /// mapped files *may* be too large to handle with this function.
707 /// Consider using [`wrapping_sub`] instead if these constraints are
708 /// difficult to satisfy. The only advantage of this method is that it
709 /// enables more aggressive compiler optimizations.
711 /// [`wrapping_sub`]: #method.wrapping_sub
712 /// [allocated object]: crate::ptr#allocated-object
719 /// let s: &str = "123";
722 /// let end: *const u8 = s.as_ptr().add(3);
723 /// println!("{}", *end.sub(1) as char);
724 /// println!("{}", *end.sub(2) as char);
727 #[stable(feature = "pointer_methods", since = "1.26.0")]
728 #[must_use = "returns a new pointer rather than modifying its argument"]
729 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
731 pub const unsafe fn sub(self, count: usize) -> Self
735 // SAFETY: the caller must uphold the safety contract for `offset`.
736 unsafe { self.offset((count as isize).wrapping_neg()) }
739 /// Calculates the offset from a pointer using wrapping arithmetic.
740 /// (convenience for `.wrapping_offset(count as isize)`)
742 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
743 /// offset of `3 * size_of::<T>()` bytes.
747 /// This operation itself is always safe, but using the resulting pointer is not.
749 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
750 /// be used to read or write other allocated objects.
752 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
753 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
754 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
755 /// `x` and `y` point into the same allocated object.
757 /// Compared to [`add`], this method basically delays the requirement of staying within the
758 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
759 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
760 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
761 /// can be optimized better and is thus preferable in performance-sensitive code.
763 /// The delayed check only considers the value of the pointer that was dereferenced, not the
764 /// intermediate values used during the computation of the final result. For example,
765 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
766 /// allocated object and then re-entering it later is permitted.
768 /// [`add`]: #method.add
769 /// [allocated object]: crate::ptr#allocated-object
776 /// // Iterate using a raw pointer in increments of two elements
777 /// let data = [1u8, 2, 3, 4, 5];
778 /// let mut ptr: *const u8 = data.as_ptr();
780 /// let end_rounded_up = ptr.wrapping_add(6);
782 /// // This loop prints "1, 3, 5, "
783 /// while ptr != end_rounded_up {
785 /// print!("{}, ", *ptr);
787 /// ptr = ptr.wrapping_add(step);
790 #[stable(feature = "pointer_methods", since = "1.26.0")]
791 #[must_use = "returns a new pointer rather than modifying its argument"]
792 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
794 pub const fn wrapping_add(self, count: usize) -> Self
798 self.wrapping_offset(count as isize)
801 /// Calculates the offset from a pointer using wrapping arithmetic.
802 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
804 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
805 /// offset of `3 * size_of::<T>()` bytes.
809 /// This operation itself is always safe, but using the resulting pointer is not.
811 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
812 /// be used to read or write other allocated objects.
814 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
815 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
816 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
817 /// `x` and `y` point into the same allocated object.
819 /// Compared to [`sub`], this method basically delays the requirement of staying within the
820 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
821 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
822 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
823 /// can be optimized better and is thus preferable in performance-sensitive code.
825 /// The delayed check only considers the value of the pointer that was dereferenced, not the
826 /// intermediate values used during the computation of the final result. For example,
827 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
828 /// allocated object and then re-entering it later is permitted.
830 /// [`sub`]: #method.sub
831 /// [allocated object]: crate::ptr#allocated-object
838 /// // Iterate using a raw pointer in increments of two elements (backwards)
839 /// let data = [1u8, 2, 3, 4, 5];
840 /// let mut ptr: *const u8 = data.as_ptr();
841 /// let start_rounded_down = ptr.wrapping_sub(2);
842 /// ptr = ptr.wrapping_add(4);
844 /// // This loop prints "5, 3, 1, "
845 /// while ptr != start_rounded_down {
847 /// print!("{}, ", *ptr);
849 /// ptr = ptr.wrapping_sub(step);
852 #[stable(feature = "pointer_methods", since = "1.26.0")]
853 #[must_use = "returns a new pointer rather than modifying its argument"]
854 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
856 pub const fn wrapping_sub(self, count: usize) -> Self
860 self.wrapping_offset((count as isize).wrapping_neg())
863 /// Sets the pointer value to `ptr`.
865 /// In case `self` is a (fat) pointer to an unsized type, this operation
866 /// will only affect the pointer part, whereas for (thin) pointers to
867 /// sized types, this has the same effect as a simple assignment.
869 /// The resulting pointer will have provenance of `val`, i.e., for a fat
870 /// pointer, this operation is semantically the same as creating a new
871 /// fat pointer with the data pointer value of `val` but the metadata of
876 /// This function is primarily useful for allowing byte-wise pointer
877 /// arithmetic on potentially fat pointers:
880 /// #![feature(set_ptr_value)]
881 /// # use core::fmt::Debug;
882 /// let mut arr: [i32; 3] = [1, 2, 3];
883 /// let mut ptr = arr.as_mut_ptr() as *mut dyn Debug;
884 /// let thin = ptr as *mut u8;
886 /// ptr = ptr.set_ptr_value(thin.add(8));
887 /// # assert_eq!(*(ptr as *mut i32), 3);
888 /// println!("{:?}", &*ptr); // will print "3"
891 #[unstable(feature = "set_ptr_value", issue = "75091")]
892 #[must_use = "returns a new pointer rather than modifying its argument"]
894 pub fn set_ptr_value(mut self, val: *mut u8) -> Self {
895 let thin = &mut self as *mut *mut T as *mut *mut u8;
896 // SAFETY: In case of a thin pointer, this operations is identical
897 // to a simple assignment. In case of a fat pointer, with the current
898 // fat pointer layout implementation, the first field of such a
899 // pointer is always the data pointer, which is likewise assigned.
900 unsafe { *thin = val };
904 /// Reads the value from `self` without moving it. This leaves the
905 /// memory in `self` unchanged.
907 /// See [`ptr::read`] for safety concerns and examples.
909 /// [`ptr::read`]: crate::ptr::read()
910 #[stable(feature = "pointer_methods", since = "1.26.0")]
911 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
913 pub const unsafe fn read(self) -> T
917 // SAFETY: the caller must uphold the safety contract for ``.
918 unsafe { read(self) }
921 /// Performs a volatile read of the value from `self` without moving it. This
922 /// leaves the memory in `self` unchanged.
924 /// Volatile operations are intended to act on I/O memory, and are guaranteed
925 /// to not be elided or reordered by the compiler across other volatile
928 /// See [`ptr::read_volatile`] for safety concerns and examples.
930 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
931 #[stable(feature = "pointer_methods", since = "1.26.0")]
933 pub unsafe fn read_volatile(self) -> T
937 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
938 unsafe { read_volatile(self) }
941 /// Reads the value from `self` without moving it. This leaves the
942 /// memory in `self` unchanged.
944 /// Unlike `read`, the pointer may be unaligned.
946 /// See [`ptr::read_unaligned`] for safety concerns and examples.
948 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
949 #[stable(feature = "pointer_methods", since = "1.26.0")]
950 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
952 pub const unsafe fn read_unaligned(self) -> T
956 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
957 unsafe { read_unaligned(self) }
960 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
961 /// and destination may overlap.
963 /// NOTE: this has the *same* argument order as [`ptr::copy`].
965 /// See [`ptr::copy`] for safety concerns and examples.
967 /// [`ptr::copy`]: crate::ptr::copy()
968 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
969 #[stable(feature = "pointer_methods", since = "1.26.0")]
971 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
975 // SAFETY: the caller must uphold the safety contract for `copy`.
976 unsafe { copy(self, dest, count) }
979 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
980 /// and destination may *not* overlap.
982 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
984 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
986 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
987 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
988 #[stable(feature = "pointer_methods", since = "1.26.0")]
990 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
994 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
995 unsafe { copy_nonoverlapping(self, dest, count) }
998 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
999 /// and destination may overlap.
1001 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1003 /// See [`ptr::copy`] for safety concerns and examples.
1005 /// [`ptr::copy`]: crate::ptr::copy()
1006 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
1007 #[stable(feature = "pointer_methods", since = "1.26.0")]
1009 pub const unsafe fn copy_from(self, src: *const T, count: usize)
1013 // SAFETY: the caller must uphold the safety contract for `copy`.
1014 unsafe { copy(src, self, count) }
1017 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1018 /// and destination may *not* overlap.
1020 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1022 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1024 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1025 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
1026 #[stable(feature = "pointer_methods", since = "1.26.0")]
1028 pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1032 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1033 unsafe { copy_nonoverlapping(src, self, count) }
1036 /// Executes the destructor (if any) of the pointed-to value.
1038 /// See [`ptr::drop_in_place`] for safety concerns and examples.
1040 /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1041 #[stable(feature = "pointer_methods", since = "1.26.0")]
1043 pub unsafe fn drop_in_place(self) {
1044 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1045 unsafe { drop_in_place(self) }
1048 /// Overwrites a memory location with the given value without reading or
1049 /// dropping the old value.
1051 /// See [`ptr::write`] for safety concerns and examples.
1053 /// [`ptr::write`]: crate::ptr::write()
1054 #[stable(feature = "pointer_methods", since = "1.26.0")]
1055 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1057 pub const unsafe fn write(self, val: T)
1061 // SAFETY: the caller must uphold the safety contract for `write`.
1062 unsafe { write(self, val) }
1065 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1066 /// bytes of memory starting at `self` to `val`.
1068 /// See [`ptr::write_bytes`] for safety concerns and examples.
1070 /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1071 #[stable(feature = "pointer_methods", since = "1.26.0")]
1073 pub unsafe fn write_bytes(self, val: u8, count: usize)
1077 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1078 unsafe { write_bytes(self, val, count) }
1081 /// Performs a volatile write of a memory location with the given value without
1082 /// reading or dropping the old value.
1084 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1085 /// to not be elided or reordered by the compiler across other volatile
1088 /// See [`ptr::write_volatile`] for safety concerns and examples.
1090 /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1091 #[stable(feature = "pointer_methods", since = "1.26.0")]
1093 pub unsafe fn write_volatile(self, val: T)
1097 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1098 unsafe { write_volatile(self, val) }
1101 /// Overwrites a memory location with the given value without reading or
1102 /// dropping the old value.
1104 /// Unlike `write`, the pointer may be unaligned.
1106 /// See [`ptr::write_unaligned`] for safety concerns and examples.
1108 /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1109 #[stable(feature = "pointer_methods", since = "1.26.0")]
1110 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1112 pub const unsafe fn write_unaligned(self, val: T)
1116 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1117 unsafe { write_unaligned(self, val) }
1120 /// Replaces the value at `self` with `src`, returning the old
1121 /// value, without dropping either.
1123 /// See [`ptr::replace`] for safety concerns and examples.
1125 /// [`ptr::replace`]: crate::ptr::replace()
1126 #[stable(feature = "pointer_methods", since = "1.26.0")]
1128 pub unsafe fn replace(self, src: T) -> T
1132 // SAFETY: the caller must uphold the safety contract for `replace`.
1133 unsafe { replace(self, src) }
1136 /// Swaps the values at two mutable locations of the same type, without
1137 /// deinitializing either. They may overlap, unlike `mem::swap` which is
1138 /// otherwise equivalent.
1140 /// See [`ptr::swap`] for safety concerns and examples.
1142 /// [`ptr::swap`]: crate::ptr::swap()
1143 #[stable(feature = "pointer_methods", since = "1.26.0")]
1144 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
1146 pub const unsafe fn swap(self, with: *mut T)
1150 // SAFETY: the caller must uphold the safety contract for `swap`.
1151 unsafe { swap(self, with) }
1154 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1157 /// If it is not possible to align the pointer, the implementation returns
1158 /// `usize::MAX`. It is permissible for the implementation to *always*
1159 /// return `usize::MAX`. Only your algorithm's performance can depend
1160 /// on getting a usable offset here, not its correctness.
1162 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1163 /// used with the `wrapping_add` method.
1165 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1166 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1167 /// the returned offset is correct in all terms other than alignment.
1171 /// The function panics if `align` is not a power-of-two.
1175 /// Accessing adjacent `u8` as `u16`
1178 /// # fn foo(n: usize) {
1179 /// # use std::mem::align_of;
1181 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1182 /// let ptr = x.as_ptr().add(n) as *const u8;
1183 /// let offset = ptr.align_offset(align_of::<u16>());
1184 /// if offset < x.len() - n - 1 {
1185 /// let u16_ptr = ptr.add(offset) as *const u16;
1186 /// assert_ne!(*u16_ptr, 500);
1188 /// // while the pointer can be aligned via `offset`, it would point
1189 /// // outside the allocation
1193 #[stable(feature = "align_offset", since = "1.36.0")]
1194 #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1195 pub const fn align_offset(self, align: usize) -> usize
1199 if !align.is_power_of_two() {
1200 panic!("align_offset: align is not a power-of-two");
1203 fn rt_impl<T>(p: *mut T, align: usize) -> usize {
1204 // SAFETY: `align` has been checked to be a power of 2 above
1205 unsafe { align_offset(p, align) }
1208 const fn ctfe_impl<T>(_: *mut T, _: usize) -> usize {
1213 // It is permisseble for `align_offset` to always return `usize::MAX`,
1214 // algorithm correctness can not depend on `align_offset` returning non-max values.
1216 // As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
1217 unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
1221 #[lang = "mut_slice_ptr"]
1223 /// Returns the length of a raw slice.
1225 /// The returned value is the number of **elements**, not the number of bytes.
1227 /// This function is safe, even when the raw slice cannot be cast to a slice
1228 /// reference because the pointer is null or unaligned.
1233 /// #![feature(slice_ptr_len)]
1236 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1237 /// assert_eq!(slice.len(), 3);
1240 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1241 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1242 pub const fn len(self) -> usize {
1246 /// Returns a raw pointer to the slice's buffer.
1248 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
1253 /// #![feature(slice_ptr_get)]
1256 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1257 /// assert_eq!(slice.as_mut_ptr(), 0 as *mut i8);
1260 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1261 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
1262 pub const fn as_mut_ptr(self) -> *mut T {
1266 /// Returns a raw pointer to an element or subslice, without doing bounds
1269 /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
1270 /// is *[undefined behavior]* even if the resulting pointer is not used.
1272 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1277 /// #![feature(slice_ptr_get)]
1279 /// let x = &mut [1, 2, 4] as *mut [i32];
1282 /// assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
1285 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1287 pub unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
1291 // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
1292 unsafe { index.get_unchecked_mut(self) }
1295 /// Returns `None` if the pointer is null, or else returns a shared slice to
1296 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1297 /// that the value has to be initialized.
1299 /// For the mutable counterpart see [`as_uninit_slice_mut`].
1301 /// [`as_ref`]: #method.as_ref-1
1302 /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
1306 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1307 /// all of the following is true:
1309 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1310 /// and it must be properly aligned. This means in particular:
1312 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1313 /// Slices can never span across multiple allocated objects.
1315 /// * The pointer must be aligned even for zero-length slices. One
1316 /// reason for this is that enum layout optimizations may rely on references
1317 /// (including slices of any length) being aligned and non-null to distinguish
1318 /// them from other data. You can obtain a pointer that is usable as `data`
1319 /// for zero-length slices using [`NonNull::dangling()`].
1321 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1322 /// See the safety documentation of [`pointer::offset`].
1324 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1325 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1326 /// In particular, for the duration of this lifetime, the memory the pointer points to must
1327 /// not get mutated (except inside `UnsafeCell`).
1329 /// This applies even if the result of this method is unused!
1331 /// See also [`slice::from_raw_parts`][].
1333 /// [valid]: crate::ptr#safety
1334 /// [allocated object]: crate::ptr#allocated-object
1336 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1337 pub unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1341 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1342 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1346 /// Returns `None` if the pointer is null, or else returns a unique slice to
1347 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
1348 /// that the value has to be initialized.
1350 /// For the shared counterpart see [`as_uninit_slice`].
1352 /// [`as_mut`]: #method.as_mut
1353 /// [`as_uninit_slice`]: #method.as_uninit_slice-1
1357 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1358 /// all of the following is true:
1360 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
1361 /// many bytes, and it must be properly aligned. This means in particular:
1363 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1364 /// Slices can never span across multiple allocated objects.
1366 /// * The pointer must be aligned even for zero-length slices. One
1367 /// reason for this is that enum layout optimizations may rely on references
1368 /// (including slices of any length) being aligned and non-null to distinguish
1369 /// them from other data. You can obtain a pointer that is usable as `data`
1370 /// for zero-length slices using [`NonNull::dangling()`].
1372 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1373 /// See the safety documentation of [`pointer::offset`].
1375 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1376 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1377 /// In particular, for the duration of this lifetime, the memory the pointer points to must
1378 /// not get accessed (read or written) through any other pointer.
1380 /// This applies even if the result of this method is unused!
1382 /// See also [`slice::from_raw_parts_mut`][].
1384 /// [valid]: crate::ptr#safety
1385 /// [allocated object]: crate::ptr#allocated-object
1387 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1388 pub unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
1392 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
1393 Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
1398 // Equality for pointers
1399 #[stable(feature = "rust1", since = "1.0.0")]
1400 impl<T: ?Sized> PartialEq for *mut T {
1402 fn eq(&self, other: &*mut T) -> bool {
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 impl<T: ?Sized> Eq for *mut T {}
1410 #[stable(feature = "rust1", since = "1.0.0")]
1411 impl<T: ?Sized> Ord for *mut T {
1413 fn cmp(&self, other: &*mut T) -> Ordering {
1416 } else if self == other {
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 impl<T: ?Sized> PartialOrd for *mut T {
1427 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
1428 Some(self.cmp(other))
1432 fn lt(&self, other: &*mut T) -> bool {
1437 fn le(&self, other: &*mut T) -> bool {
1442 fn gt(&self, other: &*mut T) -> bool {
1447 fn ge(&self, other: &*mut T) -> bool {