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 /// Changes constness without changing the type.
52 /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
55 /// While not strictly required (`*mut T` coerces to `*const T`), this is provided for symmetry
56 /// with `as_mut()` on `*const T` and may have documentation value if used instead of implicit
58 #[unstable(feature = "ptr_const_cast", issue = "92675")]
59 #[rustc_const_unstable(feature = "ptr_const_cast", issue = "92675")]
60 pub const fn as_const(self) -> *const T {
64 /// Casts a pointer to its raw bits.
66 /// This is equivalent to `as usize`, but is more specific to enhance readability.
67 /// The inverse method is [`from_bits`](#method.from_bits-1).
69 /// In particular, `*p as usize` and `p as usize` will both compile for
70 /// pointers to numeric types but do very different things, so using this
71 /// helps emphasize that reading the bits was intentional.
76 /// #![feature(ptr_to_from_bits)]
77 /// let mut array = [13, 42];
78 /// let mut it = array.iter_mut();
79 /// let p0: *mut i32 = it.next().unwrap();
80 /// assert_eq!(<*mut _>::from_bits(p0.to_bits()), p0);
81 /// let p1: *mut i32 = it.next().unwrap();
82 /// assert_eq!(p1.to_bits() - p0.to_bits(), 4);
84 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
85 pub fn to_bits(self) -> usize
92 /// Creates a pointer from its raw bits.
94 /// This is equivalent to `as *mut T`, but is more specific to enhance readability.
95 /// The inverse method is [`to_bits`](#method.to_bits-1).
100 /// #![feature(ptr_to_from_bits)]
101 /// use std::ptr::NonNull;
102 /// let dangling: *mut u8 = NonNull::dangling().as_ptr();
103 /// assert_eq!(<*mut u8>::from_bits(1), dangling);
105 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
106 pub fn from_bits(bits: usize) -> Self
113 /// Decompose a (possibly wide) pointer into its address and metadata components.
115 /// The pointer can be later reconstructed with [`from_raw_parts_mut`].
116 #[unstable(feature = "ptr_metadata", issue = "81513")]
117 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
119 pub const fn to_raw_parts(self) -> (*mut (), <T as super::Pointee>::Metadata) {
120 (self.cast(), super::metadata(self))
123 /// Returns `None` if the pointer is null, or else returns a shared reference to
124 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
125 /// must be used instead.
127 /// For the mutable counterpart see [`as_mut`].
129 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
130 /// [`as_mut`]: #method.as_mut
134 /// When calling this method, you have to ensure that *either* the pointer is null *or*
135 /// all of the following is true:
137 /// * The pointer must be properly aligned.
139 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
141 /// * The pointer must point to an initialized instance of `T`.
143 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
144 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
145 /// In particular, for the duration of this lifetime, the memory the pointer points to must
146 /// not get mutated (except inside `UnsafeCell`).
148 /// This applies even if the result of this method is unused!
149 /// (The part about being initialized is not yet fully decided, but until
150 /// it is, the only safe approach is to ensure that they are indeed initialized.)
152 /// [the module documentation]: crate::ptr#safety
159 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
162 /// if let Some(val_back) = ptr.as_ref() {
163 /// println!("We got back the value: {val_back}!");
168 /// # Null-unchecked version
170 /// If you are sure the pointer can never be null and are looking for some kind of
171 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
172 /// dereference the pointer directly.
175 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
178 /// let val_back = &*ptr;
179 /// println!("We got back the value: {val_back}!");
182 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
183 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
185 pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
186 // SAFETY: the caller must guarantee that `self` is valid for a
187 // reference if it isn't null.
188 if self.is_null() { None } else { unsafe { Some(&*self) } }
191 /// Returns `None` if the pointer is null, or else returns a shared reference to
192 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
193 /// that the value has to be initialized.
195 /// For the mutable counterpart see [`as_uninit_mut`].
197 /// [`as_ref`]: #method.as_ref-1
198 /// [`as_uninit_mut`]: #method.as_uninit_mut
202 /// When calling this method, you have to ensure that *either* the pointer is null *or*
203 /// all of the following is true:
205 /// * The pointer must be properly aligned.
207 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
209 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
210 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
211 /// In particular, for the duration of this lifetime, the memory the pointer points to must
212 /// not get mutated (except inside `UnsafeCell`).
214 /// This applies even if the result of this method is unused!
216 /// [the module documentation]: crate::ptr#safety
223 /// #![feature(ptr_as_uninit)]
225 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
228 /// if let Some(val_back) = ptr.as_uninit_ref() {
229 /// println!("We got back the value: {}!", val_back.assume_init());
234 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
235 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
236 pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
240 // SAFETY: the caller must guarantee that `self` meets all the
241 // requirements for a reference.
242 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
245 /// Calculates the offset from a pointer.
247 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
248 /// offset of `3 * size_of::<T>()` bytes.
252 /// If any of the following conditions are violated, the result is Undefined
255 /// * Both the starting and resulting pointer must be either in bounds or one
256 /// byte past the end of the same [allocated object].
258 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
260 /// * The offset being in bounds cannot rely on "wrapping around" the address
261 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
263 /// The compiler and standard library generally tries to ensure allocations
264 /// never reach a size where an offset is a concern. For instance, `Vec`
265 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
266 /// `vec.as_ptr().add(vec.len())` is always safe.
268 /// Most platforms fundamentally can't even construct such an allocation.
269 /// For instance, no known 64-bit platform can ever serve a request
270 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
271 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
272 /// more than `isize::MAX` bytes with things like Physical Address
273 /// Extension. As such, memory acquired directly from allocators or memory
274 /// mapped files *may* be too large to handle with this function.
276 /// Consider using [`wrapping_offset`] instead if these constraints are
277 /// difficult to satisfy. The only advantage of this method is that it
278 /// enables more aggressive compiler optimizations.
280 /// [`wrapping_offset`]: #method.wrapping_offset
281 /// [allocated object]: crate::ptr#allocated-object
288 /// let mut s = [1, 2, 3];
289 /// let ptr: *mut u32 = s.as_mut_ptr();
292 /// println!("{}", *ptr.offset(1));
293 /// println!("{}", *ptr.offset(2));
296 #[stable(feature = "rust1", since = "1.0.0")]
297 #[must_use = "returns a new pointer rather than modifying its argument"]
298 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
300 pub const unsafe fn offset(self, count: isize) -> *mut T
304 // SAFETY: the caller must uphold the safety contract for `offset`.
305 // The obtained pointer is valid for writes since the caller must
306 // guarantee that it points to the same allocated object as `self`.
307 unsafe { intrinsics::offset(self, count) as *mut T }
310 /// Calculates the offset from a pointer using wrapping arithmetic.
311 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
312 /// offset of `3 * size_of::<T>()` bytes.
316 /// This operation itself is always safe, but using the resulting pointer is not.
318 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
319 /// be used to read or write other allocated objects.
321 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
322 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
323 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
324 /// `x` and `y` point into the same allocated object.
326 /// Compared to [`offset`], this method basically delays the requirement of staying within the
327 /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
328 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
329 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
330 /// can be optimized better and is thus preferable in performance-sensitive code.
332 /// The delayed check only considers the value of the pointer that was dereferenced, not the
333 /// intermediate values used during the computation of the final result. For example,
334 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
335 /// words, leaving the allocated object and then re-entering it later is permitted.
337 /// [`offset`]: #method.offset
338 /// [allocated object]: crate::ptr#allocated-object
345 /// // Iterate using a raw pointer in increments of two elements
346 /// let mut data = [1u8, 2, 3, 4, 5];
347 /// let mut ptr: *mut u8 = data.as_mut_ptr();
349 /// let end_rounded_up = ptr.wrapping_offset(6);
351 /// while ptr != end_rounded_up {
355 /// ptr = ptr.wrapping_offset(step);
357 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
359 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
360 #[must_use = "returns a new pointer rather than modifying its argument"]
361 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
363 pub const fn wrapping_offset(self, count: isize) -> *mut T
367 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
368 unsafe { intrinsics::arith_offset(self, count) as *mut T }
371 /// Returns `None` if the pointer is null, or else returns a unique reference to
372 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
373 /// must be used instead.
375 /// For the shared counterpart see [`as_ref`].
377 /// [`as_uninit_mut`]: #method.as_uninit_mut
378 /// [`as_ref`]: #method.as_ref-1
382 /// When calling this method, you have to ensure that *either* the pointer is null *or*
383 /// all of the following is true:
385 /// * The pointer must be properly aligned.
387 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
389 /// * The pointer must point to an initialized instance of `T`.
391 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
392 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
393 /// In particular, for the duration of this lifetime, the memory the pointer points to must
394 /// not get accessed (read or written) through any other pointer.
396 /// This applies even if the result of this method is unused!
397 /// (The part about being initialized is not yet fully decided, but until
398 /// it is, the only safe approach is to ensure that they are indeed initialized.)
400 /// [the module documentation]: crate::ptr#safety
407 /// let mut s = [1, 2, 3];
408 /// let ptr: *mut u32 = s.as_mut_ptr();
409 /// let first_value = unsafe { ptr.as_mut().unwrap() };
410 /// *first_value = 4;
411 /// # assert_eq!(s, [4, 2, 3]);
412 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
415 /// # Null-unchecked version
417 /// If you are sure the pointer can never be null and are looking for some kind of
418 /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
419 /// you can dereference the pointer directly.
422 /// let mut s = [1, 2, 3];
423 /// let ptr: *mut u32 = s.as_mut_ptr();
424 /// let first_value = unsafe { &mut *ptr };
425 /// *first_value = 4;
426 /// # assert_eq!(s, [4, 2, 3]);
427 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
429 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
430 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
432 pub const unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
433 // SAFETY: the caller must guarantee that `self` is be valid for
434 // a mutable reference if it isn't null.
435 if self.is_null() { None } else { unsafe { Some(&mut *self) } }
438 /// Returns `None` if the pointer is null, or else returns a unique reference to
439 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
440 /// that the value has to be initialized.
442 /// For the shared counterpart see [`as_uninit_ref`].
444 /// [`as_mut`]: #method.as_mut
445 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
449 /// When calling this method, you have to ensure that *either* the pointer is null *or*
450 /// all of the following is true:
452 /// * The pointer must be properly aligned.
454 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
456 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
457 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
458 /// In particular, for the duration of this lifetime, the memory the pointer points to must
459 /// not get accessed (read or written) through any other pointer.
461 /// This applies even if the result of this method is unused!
463 /// [the module documentation]: crate::ptr#safety
465 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
466 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
467 pub const unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
471 // SAFETY: the caller must guarantee that `self` meets all the
472 // requirements for a reference.
473 if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
476 /// Returns whether two pointers are guaranteed to be equal.
478 /// At runtime this function behaves like `self == other`.
479 /// However, in some contexts (e.g., compile-time evaluation),
480 /// it is not always possible to determine equality of two pointers, so this function may
481 /// spuriously return `false` for pointers that later actually turn out to be equal.
482 /// But when it returns `true`, the pointers are guaranteed to be equal.
484 /// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
485 /// comparisons for which both functions return `false`.
487 /// [`guaranteed_ne`]: #method.guaranteed_ne
489 /// The return value may change depending on the compiler version and unsafe code might not
490 /// rely on the result of this function for soundness. It is suggested to only use this function
491 /// for performance optimizations where spurious `false` return values by this function do not
492 /// affect the outcome, but just the performance.
493 /// The consequences of using this method to make runtime and compile-time code behave
494 /// differently have not been explored. This method should not be used to introduce such
495 /// differences, and it should also not be stabilized before we have a better understanding
497 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
498 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
500 pub const fn guaranteed_eq(self, other: *mut T) -> bool
504 intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _)
507 /// Returns whether two pointers are guaranteed to be unequal.
509 /// At runtime this function behaves like `self != other`.
510 /// However, in some contexts (e.g., compile-time evaluation),
511 /// it is not always possible to determine the inequality of two pointers, so this function may
512 /// spuriously return `false` for pointers that later actually turn out to be unequal.
513 /// But when it returns `true`, the pointers are guaranteed to be unequal.
515 /// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
516 /// comparisons for which both functions return `false`.
518 /// [`guaranteed_eq`]: #method.guaranteed_eq
520 /// The return value may change depending on the compiler version and unsafe code might not
521 /// rely on the result of this function for soundness. It is suggested to only use this function
522 /// for performance optimizations where spurious `false` return values by this function do not
523 /// affect the outcome, but just the performance.
524 /// The consequences of using this method to make runtime and compile-time code behave
525 /// differently have not been explored. This method should not be used to introduce such
526 /// differences, and it should also not be stabilized before we have a better understanding
528 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
529 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
531 pub const unsafe fn guaranteed_ne(self, other: *mut T) -> bool
535 intrinsics::ptr_guaranteed_ne(self as *const _, other as *const _)
538 /// Calculates the distance between two pointers. The returned value is in
539 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
541 /// This function is the inverse of [`offset`].
543 /// [`offset`]: #method.offset-1
547 /// If any of the following conditions are violated, the result is Undefined
550 /// * Both the starting and other pointer must be either in bounds or one
551 /// byte past the end of the same [allocated object].
553 /// * Both pointers must be *derived from* a pointer to the same object.
554 /// (See below for an example.)
556 /// * The distance between the pointers, in bytes, must be an exact multiple
557 /// of the size of `T`.
559 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
561 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
563 /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
564 /// address space, so two pointers within some value of any Rust type `T` will always satisfy
565 /// the last two conditions. The standard library also generally ensures that allocations
566 /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
567 /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
568 /// always satisfies the last two conditions.
570 /// Most platforms fundamentally can't even construct such a large allocation.
571 /// For instance, no known 64-bit platform can ever serve a request
572 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
573 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
574 /// more than `isize::MAX` bytes with things like Physical Address
575 /// Extension. As such, memory acquired directly from allocators or memory
576 /// mapped files *may* be too large to handle with this function.
577 /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
578 /// such large allocations either.)
580 /// [`add`]: #method.add
581 /// [allocated object]: crate::ptr#allocated-object
585 /// This function panics if `T` is a Zero-Sized Type ("ZST").
592 /// let mut a = [0; 5];
593 /// let ptr1: *mut i32 = &mut a[1];
594 /// let ptr2: *mut i32 = &mut a[3];
596 /// assert_eq!(ptr2.offset_from(ptr1), 2);
597 /// assert_eq!(ptr1.offset_from(ptr2), -2);
598 /// assert_eq!(ptr1.offset(2), ptr2);
599 /// assert_eq!(ptr2.offset(-2), ptr1);
603 /// *Incorrect* usage:
606 /// let ptr1 = Box::into_raw(Box::new(0u8));
607 /// let ptr2 = Box::into_raw(Box::new(1u8));
608 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
609 /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
610 /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff);
611 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
612 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
613 /// // computing their offset is undefined behavior, even though
614 /// // they point to the same address!
616 /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
619 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
620 #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "92980")]
622 pub const unsafe fn offset_from(self, origin: *const T) -> isize
626 // SAFETY: the caller must uphold the safety contract for `offset_from`.
627 unsafe { (self as *const T).offset_from(origin) }
630 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
632 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
633 /// offset of `3 * size_of::<T>()` bytes.
637 /// If any of the following conditions are violated, the result is Undefined
640 /// * Both the starting and resulting pointer must be either in bounds or one
641 /// byte past the end of the same [allocated object].
643 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
645 /// * The offset being in bounds cannot rely on "wrapping around" the address
646 /// space. That is, the infinite-precision sum must fit in a `usize`.
648 /// The compiler and standard library generally tries to ensure allocations
649 /// never reach a size where an offset is a concern. For instance, `Vec`
650 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
651 /// `vec.as_ptr().add(vec.len())` is always safe.
653 /// Most platforms fundamentally can't even construct such an allocation.
654 /// For instance, no known 64-bit platform can ever serve a request
655 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
656 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
657 /// more than `isize::MAX` bytes with things like Physical Address
658 /// Extension. As such, memory acquired directly from allocators or memory
659 /// mapped files *may* be too large to handle with this function.
661 /// Consider using [`wrapping_add`] instead if these constraints are
662 /// difficult to satisfy. The only advantage of this method is that it
663 /// enables more aggressive compiler optimizations.
665 /// [`wrapping_add`]: #method.wrapping_add
666 /// [allocated object]: crate::ptr#allocated-object
673 /// let s: &str = "123";
674 /// let ptr: *const u8 = s.as_ptr();
677 /// println!("{}", *ptr.add(1) as char);
678 /// println!("{}", *ptr.add(2) as char);
681 #[stable(feature = "pointer_methods", since = "1.26.0")]
682 #[must_use = "returns a new pointer rather than modifying its argument"]
683 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
685 pub const unsafe fn add(self, count: usize) -> Self
689 // SAFETY: the caller must uphold the safety contract for `offset`.
690 unsafe { self.offset(count as isize) }
693 /// Calculates the offset from a pointer (convenience for
694 /// `.offset((count as isize).wrapping_neg())`).
696 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
697 /// offset of `3 * size_of::<T>()` bytes.
701 /// If any of the following conditions are violated, the result is Undefined
704 /// * Both the starting and resulting pointer must be either in bounds or one
705 /// byte past the end of the same [allocated object].
707 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
709 /// * The offset being in bounds cannot rely on "wrapping around" the address
710 /// space. That is, the infinite-precision sum must fit in a usize.
712 /// The compiler and standard library generally tries to ensure allocations
713 /// never reach a size where an offset is a concern. For instance, `Vec`
714 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
715 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
717 /// Most platforms fundamentally can't even construct such an allocation.
718 /// For instance, no known 64-bit platform can ever serve a request
719 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
720 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
721 /// more than `isize::MAX` bytes with things like Physical Address
722 /// Extension. As such, memory acquired directly from allocators or memory
723 /// mapped files *may* be too large to handle with this function.
725 /// Consider using [`wrapping_sub`] instead if these constraints are
726 /// difficult to satisfy. The only advantage of this method is that it
727 /// enables more aggressive compiler optimizations.
729 /// [`wrapping_sub`]: #method.wrapping_sub
730 /// [allocated object]: crate::ptr#allocated-object
737 /// let s: &str = "123";
740 /// let end: *const u8 = s.as_ptr().add(3);
741 /// println!("{}", *end.sub(1) as char);
742 /// println!("{}", *end.sub(2) as char);
745 #[stable(feature = "pointer_methods", since = "1.26.0")]
746 #[must_use = "returns a new pointer rather than modifying its argument"]
747 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
749 pub const unsafe fn sub(self, count: usize) -> Self
753 // SAFETY: the caller must uphold the safety contract for `offset`.
754 unsafe { self.offset((count as isize).wrapping_neg()) }
757 /// Calculates the offset from a pointer using wrapping arithmetic.
758 /// (convenience for `.wrapping_offset(count as isize)`)
760 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
761 /// offset of `3 * size_of::<T>()` bytes.
765 /// This operation itself is always safe, but using the resulting pointer is not.
767 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
768 /// be used to read or write other allocated objects.
770 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
771 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
772 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
773 /// `x` and `y` point into the same allocated object.
775 /// Compared to [`add`], this method basically delays the requirement of staying within the
776 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
777 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
778 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
779 /// can be optimized better and is thus preferable in performance-sensitive code.
781 /// The delayed check only considers the value of the pointer that was dereferenced, not the
782 /// intermediate values used during the computation of the final result. For example,
783 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
784 /// allocated object and then re-entering it later is permitted.
786 /// [`add`]: #method.add
787 /// [allocated object]: crate::ptr#allocated-object
794 /// // Iterate using a raw pointer in increments of two elements
795 /// let data = [1u8, 2, 3, 4, 5];
796 /// let mut ptr: *const u8 = data.as_ptr();
798 /// let end_rounded_up = ptr.wrapping_add(6);
800 /// // This loop prints "1, 3, 5, "
801 /// while ptr != end_rounded_up {
803 /// print!("{}, ", *ptr);
805 /// ptr = ptr.wrapping_add(step);
808 #[stable(feature = "pointer_methods", since = "1.26.0")]
809 #[must_use = "returns a new pointer rather than modifying its argument"]
810 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
812 pub const fn wrapping_add(self, count: usize) -> Self
816 self.wrapping_offset(count as isize)
819 /// Calculates the offset from a pointer using wrapping arithmetic.
820 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
822 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
823 /// offset of `3 * size_of::<T>()` bytes.
827 /// This operation itself is always safe, but using the resulting pointer is not.
829 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
830 /// be used to read or write other allocated objects.
832 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
833 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
834 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
835 /// `x` and `y` point into the same allocated object.
837 /// Compared to [`sub`], this method basically delays the requirement of staying within the
838 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
839 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
840 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
841 /// can be optimized better and is thus preferable in performance-sensitive code.
843 /// The delayed check only considers the value of the pointer that was dereferenced, not the
844 /// intermediate values used during the computation of the final result. For example,
845 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
846 /// allocated object and then re-entering it later is permitted.
848 /// [`sub`]: #method.sub
849 /// [allocated object]: crate::ptr#allocated-object
856 /// // Iterate using a raw pointer in increments of two elements (backwards)
857 /// let data = [1u8, 2, 3, 4, 5];
858 /// let mut ptr: *const u8 = data.as_ptr();
859 /// let start_rounded_down = ptr.wrapping_sub(2);
860 /// ptr = ptr.wrapping_add(4);
862 /// // This loop prints "5, 3, 1, "
863 /// while ptr != start_rounded_down {
865 /// print!("{}, ", *ptr);
867 /// ptr = ptr.wrapping_sub(step);
870 #[stable(feature = "pointer_methods", since = "1.26.0")]
871 #[must_use = "returns a new pointer rather than modifying its argument"]
872 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
874 pub const fn wrapping_sub(self, count: usize) -> Self
878 self.wrapping_offset((count as isize).wrapping_neg())
881 /// Sets the pointer value to `ptr`.
883 /// In case `self` is a (fat) pointer to an unsized type, this operation
884 /// will only affect the pointer part, whereas for (thin) pointers to
885 /// sized types, this has the same effect as a simple assignment.
887 /// The resulting pointer will have provenance of `val`, i.e., for a fat
888 /// pointer, this operation is semantically the same as creating a new
889 /// fat pointer with the data pointer value of `val` but the metadata of
894 /// This function is primarily useful for allowing byte-wise pointer
895 /// arithmetic on potentially fat pointers:
898 /// #![feature(set_ptr_value)]
899 /// # use core::fmt::Debug;
900 /// let mut arr: [i32; 3] = [1, 2, 3];
901 /// let mut ptr = arr.as_mut_ptr() as *mut dyn Debug;
902 /// let thin = ptr as *mut u8;
904 /// ptr = ptr.set_ptr_value(thin.add(8));
905 /// # assert_eq!(*(ptr as *mut i32), 3);
906 /// println!("{:?}", &*ptr); // will print "3"
909 #[unstable(feature = "set_ptr_value", issue = "75091")]
910 #[must_use = "returns a new pointer rather than modifying its argument"]
912 pub fn set_ptr_value(mut self, val: *mut u8) -> Self {
913 let thin = &mut self as *mut *mut T as *mut *mut u8;
914 // SAFETY: In case of a thin pointer, this operations is identical
915 // to a simple assignment. In case of a fat pointer, with the current
916 // fat pointer layout implementation, the first field of such a
917 // pointer is always the data pointer, which is likewise assigned.
918 unsafe { *thin = val };
922 /// Reads the value from `self` without moving it. This leaves the
923 /// memory in `self` unchanged.
925 /// See [`ptr::read`] for safety concerns and examples.
927 /// [`ptr::read`]: crate::ptr::read()
928 #[stable(feature = "pointer_methods", since = "1.26.0")]
929 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
931 pub const unsafe fn read(self) -> T
935 // SAFETY: the caller must uphold the safety contract for ``.
936 unsafe { read(self) }
939 /// Performs a volatile read of the value from `self` without moving it. This
940 /// leaves the memory in `self` unchanged.
942 /// Volatile operations are intended to act on I/O memory, and are guaranteed
943 /// to not be elided or reordered by the compiler across other volatile
946 /// See [`ptr::read_volatile`] for safety concerns and examples.
948 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
949 #[stable(feature = "pointer_methods", since = "1.26.0")]
951 pub unsafe fn read_volatile(self) -> T
955 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
956 unsafe { read_volatile(self) }
959 /// Reads the value from `self` without moving it. This leaves the
960 /// memory in `self` unchanged.
962 /// Unlike `read`, the pointer may be unaligned.
964 /// See [`ptr::read_unaligned`] for safety concerns and examples.
966 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
967 #[stable(feature = "pointer_methods", since = "1.26.0")]
968 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
970 pub const unsafe fn read_unaligned(self) -> T
974 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
975 unsafe { read_unaligned(self) }
978 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
979 /// and destination may overlap.
981 /// NOTE: this has the *same* argument order as [`ptr::copy`].
983 /// See [`ptr::copy`] for safety concerns and examples.
985 /// [`ptr::copy`]: crate::ptr::copy()
986 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
987 #[stable(feature = "pointer_methods", since = "1.26.0")]
989 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
993 // SAFETY: the caller must uphold the safety contract for `copy`.
994 unsafe { copy(self, dest, count) }
997 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
998 /// and destination may *not* overlap.
1000 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1002 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1004 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1005 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
1006 #[stable(feature = "pointer_methods", since = "1.26.0")]
1008 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1012 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1013 unsafe { copy_nonoverlapping(self, dest, count) }
1016 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1017 /// and destination may overlap.
1019 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1021 /// See [`ptr::copy`] for safety concerns and examples.
1023 /// [`ptr::copy`]: crate::ptr::copy()
1024 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
1025 #[stable(feature = "pointer_methods", since = "1.26.0")]
1027 pub const unsafe fn copy_from(self, src: *const T, count: usize)
1031 // SAFETY: the caller must uphold the safety contract for `copy`.
1032 unsafe { copy(src, self, count) }
1035 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1036 /// and destination may *not* overlap.
1038 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1040 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1042 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1043 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
1044 #[stable(feature = "pointer_methods", since = "1.26.0")]
1046 pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1050 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1051 unsafe { copy_nonoverlapping(src, self, count) }
1054 /// Executes the destructor (if any) of the pointed-to value.
1056 /// See [`ptr::drop_in_place`] for safety concerns and examples.
1058 /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1059 #[stable(feature = "pointer_methods", since = "1.26.0")]
1061 pub unsafe fn drop_in_place(self) {
1062 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1063 unsafe { drop_in_place(self) }
1066 /// Overwrites a memory location with the given value without reading or
1067 /// dropping the old value.
1069 /// See [`ptr::write`] for safety concerns and examples.
1071 /// [`ptr::write`]: crate::ptr::write()
1072 #[stable(feature = "pointer_methods", since = "1.26.0")]
1073 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1075 pub const unsafe fn write(self, val: T)
1079 // SAFETY: the caller must uphold the safety contract for `write`.
1080 unsafe { write(self, val) }
1083 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1084 /// bytes of memory starting at `self` to `val`.
1086 /// See [`ptr::write_bytes`] for safety concerns and examples.
1088 /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1089 #[stable(feature = "pointer_methods", since = "1.26.0")]
1090 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1092 pub const unsafe fn write_bytes(self, val: u8, count: usize)
1096 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1097 unsafe { write_bytes(self, val, count) }
1100 /// Performs a volatile write of a memory location with the given value without
1101 /// reading or dropping the old value.
1103 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1104 /// to not be elided or reordered by the compiler across other volatile
1107 /// See [`ptr::write_volatile`] for safety concerns and examples.
1109 /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1110 #[stable(feature = "pointer_methods", since = "1.26.0")]
1112 pub unsafe fn write_volatile(self, val: T)
1116 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1117 unsafe { write_volatile(self, val) }
1120 /// Overwrites a memory location with the given value without reading or
1121 /// dropping the old value.
1123 /// Unlike `write`, the pointer may be unaligned.
1125 /// See [`ptr::write_unaligned`] for safety concerns and examples.
1127 /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1128 #[stable(feature = "pointer_methods", since = "1.26.0")]
1129 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1131 pub const unsafe fn write_unaligned(self, val: T)
1135 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1136 unsafe { write_unaligned(self, val) }
1139 /// Replaces the value at `self` with `src`, returning the old
1140 /// value, without dropping either.
1142 /// See [`ptr::replace`] for safety concerns and examples.
1144 /// [`ptr::replace`]: crate::ptr::replace()
1145 #[stable(feature = "pointer_methods", since = "1.26.0")]
1147 pub unsafe fn replace(self, src: T) -> T
1151 // SAFETY: the caller must uphold the safety contract for `replace`.
1152 unsafe { replace(self, src) }
1155 /// Swaps the values at two mutable locations of the same type, without
1156 /// deinitializing either. They may overlap, unlike `mem::swap` which is
1157 /// otherwise equivalent.
1159 /// See [`ptr::swap`] for safety concerns and examples.
1161 /// [`ptr::swap`]: crate::ptr::swap()
1162 #[stable(feature = "pointer_methods", since = "1.26.0")]
1163 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
1165 pub const unsafe fn swap(self, with: *mut T)
1169 // SAFETY: the caller must uphold the safety contract for `swap`.
1170 unsafe { swap(self, with) }
1173 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1176 /// If it is not possible to align the pointer, the implementation returns
1177 /// `usize::MAX`. It is permissible for the implementation to *always*
1178 /// return `usize::MAX`. Only your algorithm's performance can depend
1179 /// on getting a usable offset here, not its correctness.
1181 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1182 /// used with the `wrapping_add` method.
1184 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1185 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1186 /// the returned offset is correct in all terms other than alignment.
1190 /// The function panics if `align` is not a power-of-two.
1194 /// Accessing adjacent `u8` as `u16`
1197 /// # fn foo(n: usize) {
1198 /// # use std::mem::align_of;
1200 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1201 /// let ptr = x.as_ptr().add(n) as *const u8;
1202 /// let offset = ptr.align_offset(align_of::<u16>());
1203 /// if offset < x.len() - n - 1 {
1204 /// let u16_ptr = ptr.add(offset) as *const u16;
1205 /// assert_ne!(*u16_ptr, 500);
1207 /// // while the pointer can be aligned via `offset`, it would point
1208 /// // outside the allocation
1212 #[stable(feature = "align_offset", since = "1.36.0")]
1213 #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1214 pub const fn align_offset(self, align: usize) -> usize
1218 if !align.is_power_of_two() {
1219 panic!("align_offset: align is not a power-of-two");
1222 fn rt_impl<T>(p: *mut T, align: usize) -> usize {
1223 // SAFETY: `align` has been checked to be a power of 2 above
1224 unsafe { align_offset(p, align) }
1227 const fn ctfe_impl<T>(_: *mut T, _: usize) -> usize {
1232 // It is permisseble for `align_offset` to always return `usize::MAX`,
1233 // algorithm correctness can not depend on `align_offset` returning non-max values.
1235 // As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
1236 unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
1240 #[lang = "mut_slice_ptr"]
1242 /// Returns the length of a raw slice.
1244 /// The returned value is the number of **elements**, not the number of bytes.
1246 /// This function is safe, even when the raw slice cannot be cast to a slice
1247 /// reference because the pointer is null or unaligned.
1252 /// #![feature(slice_ptr_len)]
1255 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1256 /// assert_eq!(slice.len(), 3);
1259 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1260 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1261 pub const fn len(self) -> usize {
1265 /// Returns a raw pointer to the slice's buffer.
1267 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
1272 /// #![feature(slice_ptr_get)]
1275 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1276 /// assert_eq!(slice.as_mut_ptr(), 0 as *mut i8);
1279 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1280 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
1281 pub const fn as_mut_ptr(self) -> *mut T {
1285 /// Returns a raw pointer to an element or subslice, without doing bounds
1288 /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
1289 /// is *[undefined behavior]* even if the resulting pointer is not used.
1291 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1296 /// #![feature(slice_ptr_get)]
1298 /// let x = &mut [1, 2, 4] as *mut [i32];
1301 /// assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
1304 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1305 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
1307 pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
1309 I: ~const SliceIndex<[T]>,
1311 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1312 unsafe { index.get_unchecked_mut(self) }
1315 /// Returns `None` if the pointer is null, or else returns a shared slice to
1316 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1317 /// that the value has to be initialized.
1319 /// For the mutable counterpart see [`as_uninit_slice_mut`].
1321 /// [`as_ref`]: #method.as_ref-1
1322 /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
1326 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1327 /// all of the following is true:
1329 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1330 /// and it must be properly aligned. This means in particular:
1332 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1333 /// Slices can never span across multiple allocated objects.
1335 /// * The pointer must be aligned even for zero-length slices. One
1336 /// reason for this is that enum layout optimizations may rely on references
1337 /// (including slices of any length) being aligned and non-null to distinguish
1338 /// them from other data. You can obtain a pointer that is usable as `data`
1339 /// for zero-length slices using [`NonNull::dangling()`].
1341 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1342 /// See the safety documentation of [`pointer::offset`].
1344 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1345 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1346 /// In particular, for the duration of this lifetime, the memory the pointer points to must
1347 /// not get mutated (except inside `UnsafeCell`).
1349 /// This applies even if the result of this method is unused!
1351 /// See also [`slice::from_raw_parts`][].
1353 /// [valid]: crate::ptr#safety
1354 /// [allocated object]: crate::ptr#allocated-object
1356 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1357 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1358 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1362 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1363 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1367 /// Returns `None` if the pointer is null, or else returns a unique slice to
1368 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
1369 /// that the value has to be initialized.
1371 /// For the shared counterpart see [`as_uninit_slice`].
1373 /// [`as_mut`]: #method.as_mut
1374 /// [`as_uninit_slice`]: #method.as_uninit_slice-1
1378 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1379 /// all of the following is true:
1381 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
1382 /// many bytes, and it must be properly aligned. This means in particular:
1384 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1385 /// Slices can never span across multiple allocated objects.
1387 /// * The pointer must be aligned even for zero-length slices. One
1388 /// reason for this is that enum layout optimizations may rely on references
1389 /// (including slices of any length) being aligned and non-null to distinguish
1390 /// them from other data. You can obtain a pointer that is usable as `data`
1391 /// for zero-length slices using [`NonNull::dangling()`].
1393 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1394 /// See the safety documentation of [`pointer::offset`].
1396 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1397 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1398 /// In particular, for the duration of this lifetime, the memory the pointer points to must
1399 /// not get accessed (read or written) through any other pointer.
1401 /// This applies even if the result of this method is unused!
1403 /// See also [`slice::from_raw_parts_mut`][].
1405 /// [valid]: crate::ptr#safety
1406 /// [allocated object]: crate::ptr#allocated-object
1408 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1409 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1410 pub const unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
1414 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
1415 Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
1420 // Equality for pointers
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 impl<T: ?Sized> PartialEq for *mut T {
1424 fn eq(&self, other: &*mut T) -> bool {
1429 #[stable(feature = "rust1", since = "1.0.0")]
1430 impl<T: ?Sized> Eq for *mut T {}
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 impl<T: ?Sized> Ord for *mut T {
1435 fn cmp(&self, other: &*mut T) -> Ordering {
1438 } else if self == other {
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 impl<T: ?Sized> PartialOrd for *mut T {
1449 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
1450 Some(self.cmp(other))
1454 fn lt(&self, other: &*mut T) -> bool {
1459 fn le(&self, other: &*mut T) -> bool {
1464 fn gt(&self, other: &*mut T) -> bool {
1469 fn ge(&self, other: &*mut T) -> bool {