2 use crate::cmp::Ordering::{self, Equal, Greater, Less};
4 use crate::slice::{self, SliceIndex};
6 impl<T: ?Sized> *mut T {
7 /// Returns `true` if the pointer is null.
9 /// Note that unsized types have many possible null pointers, as only the
10 /// raw data pointer is considered, not their length, vtable, etc.
11 /// Therefore, two pointers that are null may still not compare equal to
14 /// ## Behavior during const evaluation
16 /// When this function is used during const evaluation, it may return `false` for pointers
17 /// that turn out to be null at runtime. Specifically, when a pointer to some memory
18 /// is offset beyond its bounds in such a way that the resulting pointer is null,
19 /// the function will still return `false`. There is no way for CTFE to know
20 /// the absolute position of that memory, so we cannot tell if the pointer is
28 /// let mut s = [1, 2, 3];
29 /// let ptr: *mut u32 = s.as_mut_ptr();
30 /// assert!(!ptr.is_null());
32 #[stable(feature = "rust1", since = "1.0.0")]
33 #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")]
35 pub const fn is_null(self) -> bool {
36 // Compare via a cast to a thin pointer, so fat pointers are only
37 // considering their "data" part for null-ness.
38 match (self as *mut u8).guaranteed_eq(null_mut()) {
44 /// Casts to a pointer of another type.
45 #[stable(feature = "ptr_cast", since = "1.38.0")]
46 #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
48 pub const fn cast<U>(self) -> *mut U {
52 /// Use the pointer value in a new pointer of another type.
54 /// In case `val` is a (fat) pointer to an unsized type, this operation
55 /// will ignore the pointer part, whereas for (thin) pointers to sized
56 /// types, this has the same effect as a simple cast.
58 /// The resulting pointer will have provenance of `self`, i.e., for a fat
59 /// pointer, this operation is semantically the same as creating a new
60 /// fat pointer with the data pointer value of `self` but the metadata of
65 /// This function is primarily useful for allowing byte-wise pointer
66 /// arithmetic on potentially fat pointers:
69 /// #![feature(set_ptr_value)]
70 /// # use core::fmt::Debug;
71 /// let mut arr: [i32; 3] = [1, 2, 3];
72 /// let mut ptr = arr.as_mut_ptr() as *mut dyn Debug;
73 /// let thin = ptr as *mut u8;
75 /// ptr = thin.add(8).with_metadata_of(ptr);
76 /// # assert_eq!(*(ptr as *mut i32), 3);
77 /// println!("{:?}", &*ptr); // will print "3"
80 #[unstable(feature = "set_ptr_value", issue = "75091")]
81 #[rustc_const_unstable(feature = "set_ptr_value", issue = "75091")]
82 #[must_use = "returns a new pointer rather than modifying its argument"]
84 pub const fn with_metadata_of<U>(self, meta: *const U) -> *mut U
88 from_raw_parts_mut::<U>(self as *mut (), metadata(meta))
91 /// Changes constness without changing the type.
93 /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
96 /// While not strictly required (`*mut T` coerces to `*const T`), this is provided for symmetry
97 /// with [`cast_mut`] on `*const T` and may have documentation value if used instead of implicit
100 /// [`cast_mut`]: #method.cast_mut
101 #[stable(feature = "ptr_const_cast", since = "1.65.0")]
102 #[rustc_const_stable(feature = "ptr_const_cast", since = "1.65.0")]
104 pub const fn cast_const(self) -> *const T {
108 /// Casts a pointer to its raw bits.
110 /// This is equivalent to `as usize`, but is more specific to enhance readability.
111 /// The inverse method is [`from_bits`](#method.from_bits-1).
113 /// In particular, `*p as usize` and `p as usize` will both compile for
114 /// pointers to numeric types but do very different things, so using this
115 /// helps emphasize that reading the bits was intentional.
120 /// #![feature(ptr_to_from_bits)]
121 /// # #[cfg(not(miri))] { // doctest does not work with strict provenance
122 /// let mut array = [13, 42];
123 /// let mut it = array.iter_mut();
124 /// let p0: *mut i32 = it.next().unwrap();
125 /// assert_eq!(<*mut _>::from_bits(p0.to_bits()), p0);
126 /// let p1: *mut i32 = it.next().unwrap();
127 /// assert_eq!(p1.to_bits() - p0.to_bits(), 4);
130 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
133 note = "replaced by the `exposed_addr` method, or update your code \
134 to follow the strict provenance rules using its APIs"
137 pub fn to_bits(self) -> usize
144 /// Creates a pointer from its raw bits.
146 /// This is equivalent to `as *mut T`, but is more specific to enhance readability.
147 /// The inverse method is [`to_bits`](#method.to_bits-1).
152 /// #![feature(ptr_to_from_bits)]
153 /// # #[cfg(not(miri))] { // doctest does not work with strict provenance
154 /// use std::ptr::NonNull;
155 /// let dangling: *mut u8 = NonNull::dangling().as_ptr();
156 /// assert_eq!(<*mut u8>::from_bits(1), dangling);
159 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
162 note = "replaced by the `ptr::from_exposed_addr_mut` function, or \
163 update your code to follow the strict provenance rules using its APIs"
165 #[allow(fuzzy_provenance_casts)] // this is an unstable and semi-deprecated cast function
167 pub fn from_bits(bits: usize) -> Self
174 /// Gets the "address" portion of the pointer.
176 /// This is similar to `self as usize`, which semantically discards *provenance* and
177 /// *address-space* information. However, unlike `self as usize`, casting the returned address
178 /// back to a pointer yields [`invalid`][], which is undefined behavior to dereference. To
179 /// properly restore the lost information and obtain a dereferenceable pointer, use
180 /// [`with_addr`][pointer::with_addr] or [`map_addr`][pointer::map_addr].
182 /// If using those APIs is not possible because there is no way to preserve a pointer with the
183 /// required provenance, use [`expose_addr`][pointer::expose_addr] and
184 /// [`from_exposed_addr_mut`][from_exposed_addr_mut] instead. However, note that this makes
185 /// your code less portable and less amenable to tools that check for compliance with the Rust
188 /// On most platforms this will produce a value with the same bytes as the original
189 /// pointer, because all the bytes are dedicated to describing the address.
190 /// Platforms which need to store additional information in the pointer may
191 /// perform a change of representation to produce a value containing only the address
192 /// portion of the pointer. What that means is up to the platform to define.
194 /// This API and its claimed semantics are part of the Strict Provenance experiment, and as such
195 /// might change in the future (including possibly weakening this so it becomes wholly
196 /// equivalent to `self as usize`). See the [module documentation][crate::ptr] for details.
199 #[unstable(feature = "strict_provenance", issue = "95228")]
200 pub fn addr(self) -> usize
204 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
205 // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
207 unsafe { mem::transmute(self) }
210 /// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future
211 /// use in [`from_exposed_addr`][].
213 /// This is equivalent to `self as usize`, which semantically discards *provenance* and
214 /// *address-space* information. Furthermore, this (like the `as` cast) has the implicit
215 /// side-effect of marking the provenance as 'exposed', so on platforms that support it you can
216 /// later call [`from_exposed_addr_mut`][] to reconstitute the original pointer including its
217 /// provenance. (Reconstructing address space information, if required, is your responsibility.)
219 /// Using this method means that code is *not* following Strict Provenance rules. Supporting
220 /// [`from_exposed_addr_mut`][] complicates specification and reasoning and may not be supported
221 /// by tools that help you to stay conformant with the Rust memory model, so it is recommended
222 /// to use [`addr`][pointer::addr] wherever possible.
224 /// On most platforms this will produce a value with the same bytes as the original pointer,
225 /// because all the bytes are dedicated to describing the address. Platforms which need to store
226 /// additional information in the pointer may not support this operation, since the 'expose'
227 /// side-effect which is required for [`from_exposed_addr_mut`][] to work is typically not
230 /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
231 /// [module documentation][crate::ptr] for details.
233 /// [`from_exposed_addr_mut`]: from_exposed_addr_mut
236 #[unstable(feature = "strict_provenance", issue = "95228")]
237 pub fn expose_addr(self) -> usize
241 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
245 /// Creates a new pointer with the given address.
247 /// This performs the same operation as an `addr as ptr` cast, but copies
248 /// the *address-space* and *provenance* of `self` to the new pointer.
249 /// This allows us to dynamically preserve and propagate this important
250 /// information in a way that is otherwise impossible with a unary cast.
252 /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
253 /// `self` to the given address, and therefore has all the same capabilities and restrictions.
255 /// This API and its claimed semantics are part of the Strict Provenance experiment,
256 /// see the [module documentation][crate::ptr] for details.
259 #[unstable(feature = "strict_provenance", issue = "95228")]
260 pub fn with_addr(self, addr: usize) -> Self
264 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
266 // In the mean-time, this operation is defined to be "as if" it was
267 // a wrapping_offset, so we can emulate it as such. This should properly
268 // restore pointer provenance even under today's compiler.
269 let self_addr = self.addr() as isize;
270 let dest_addr = addr as isize;
271 let offset = dest_addr.wrapping_sub(self_addr);
273 // This is the canonical desugarring of this operation
274 self.wrapping_byte_offset(offset)
277 /// Creates a new pointer by mapping `self`'s address to a new one.
279 /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
281 /// This API and its claimed semantics are part of the Strict Provenance experiment,
282 /// see the [module documentation][crate::ptr] for details.
285 #[unstable(feature = "strict_provenance", issue = "95228")]
286 pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self
290 self.with_addr(f(self.addr()))
293 /// Decompose a (possibly wide) pointer into its address and metadata components.
295 /// The pointer can be later reconstructed with [`from_raw_parts_mut`].
296 #[unstable(feature = "ptr_metadata", issue = "81513")]
297 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
299 pub const fn to_raw_parts(self) -> (*mut (), <T as super::Pointee>::Metadata) {
300 (self.cast(), super::metadata(self))
303 /// Returns `None` if the pointer is null, or else returns a shared reference to
304 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
305 /// must be used instead.
307 /// For the mutable counterpart see [`as_mut`].
309 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
310 /// [`as_mut`]: #method.as_mut
314 /// When calling this method, you have to ensure that *either* the pointer is null *or*
315 /// all of the following is true:
317 /// * The pointer must be properly aligned.
319 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
321 /// * The pointer must point to an initialized instance of `T`.
323 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
324 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
325 /// In particular, while this reference exists, the memory the pointer points to must
326 /// not get mutated (except inside `UnsafeCell`).
328 /// This applies even if the result of this method is unused!
329 /// (The part about being initialized is not yet fully decided, but until
330 /// it is, the only safe approach is to ensure that they are indeed initialized.)
332 /// [the module documentation]: crate::ptr#safety
339 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
342 /// if let Some(val_back) = ptr.as_ref() {
343 /// println!("We got back the value: {val_back}!");
348 /// # Null-unchecked version
350 /// If you are sure the pointer can never be null and are looking for some kind of
351 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
352 /// dereference the pointer directly.
355 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
358 /// let val_back = &*ptr;
359 /// println!("We got back the value: {val_back}!");
362 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
363 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
365 pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
366 // SAFETY: the caller must guarantee that `self` is valid for a
367 // reference if it isn't null.
368 if self.is_null() { None } else { unsafe { Some(&*self) } }
371 /// Returns `None` if the pointer is null, or else returns a shared reference to
372 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
373 /// that the value has to be initialized.
375 /// For the mutable counterpart see [`as_uninit_mut`].
377 /// [`as_ref`]: #method.as_ref-1
378 /// [`as_uninit_mut`]: #method.as_uninit_mut
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 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
390 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
391 /// In particular, while this reference exists, the memory the pointer points to must
392 /// not get mutated (except inside `UnsafeCell`).
394 /// This applies even if the result of this method is unused!
396 /// [the module documentation]: crate::ptr#safety
403 /// #![feature(ptr_as_uninit)]
405 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
408 /// if let Some(val_back) = ptr.as_uninit_ref() {
409 /// println!("We got back the value: {}!", val_back.assume_init());
414 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
415 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
416 pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
420 // SAFETY: the caller must guarantee that `self` meets all the
421 // requirements for a reference.
422 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
425 /// Calculates the offset from a pointer.
427 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
428 /// offset of `3 * size_of::<T>()` bytes.
432 /// If any of the following conditions are violated, the result is Undefined
435 /// * Both the starting and resulting pointer must be either in bounds or one
436 /// byte past the end of the same [allocated object].
438 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
440 /// * The offset being in bounds cannot rely on "wrapping around" the address
441 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
443 /// The compiler and standard library generally tries to ensure allocations
444 /// never reach a size where an offset is a concern. For instance, `Vec`
445 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
446 /// `vec.as_ptr().add(vec.len())` is always safe.
448 /// Most platforms fundamentally can't even construct such an allocation.
449 /// For instance, no known 64-bit platform can ever serve a request
450 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
451 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
452 /// more than `isize::MAX` bytes with things like Physical Address
453 /// Extension. As such, memory acquired directly from allocators or memory
454 /// mapped files *may* be too large to handle with this function.
456 /// Consider using [`wrapping_offset`] instead if these constraints are
457 /// difficult to satisfy. The only advantage of this method is that it
458 /// enables more aggressive compiler optimizations.
460 /// [`wrapping_offset`]: #method.wrapping_offset
461 /// [allocated object]: crate::ptr#allocated-object
468 /// let mut s = [1, 2, 3];
469 /// let ptr: *mut u32 = s.as_mut_ptr();
472 /// println!("{}", *ptr.offset(1));
473 /// println!("{}", *ptr.offset(2));
476 #[stable(feature = "rust1", since = "1.0.0")]
477 #[must_use = "returns a new pointer rather than modifying its argument"]
478 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
480 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
481 pub const unsafe fn offset(self, count: isize) -> *mut T
485 // SAFETY: the caller must uphold the safety contract for `offset`.
486 // The obtained pointer is valid for writes since the caller must
487 // guarantee that it points to the same allocated object as `self`.
488 unsafe { intrinsics::offset(self, count) as *mut T }
491 /// Calculates the offset from a pointer in bytes.
493 /// `count` is in units of **bytes**.
495 /// This is purely a convenience for casting to a `u8` pointer and
496 /// using [offset][pointer::offset] on it. See that method for documentation
497 /// and safety requirements.
499 /// For non-`Sized` pointees this operation changes only the data pointer,
500 /// leaving the metadata untouched.
503 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
504 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
505 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
506 pub const unsafe fn byte_offset(self, count: isize) -> Self {
507 // SAFETY: the caller must uphold the safety contract for `offset`.
508 unsafe { self.cast::<u8>().offset(count).with_metadata_of(self) }
511 /// Calculates the offset from a pointer using wrapping arithmetic.
512 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
513 /// offset of `3 * size_of::<T>()` bytes.
517 /// This operation itself is always safe, but using the resulting pointer is not.
519 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
520 /// be used to read or write other allocated objects.
522 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
523 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
524 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
525 /// `x` and `y` point into the same allocated object.
527 /// Compared to [`offset`], this method basically delays the requirement of staying within the
528 /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
529 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
530 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
531 /// can be optimized better and is thus preferable in performance-sensitive code.
533 /// The delayed check only considers the value of the pointer that was dereferenced, not the
534 /// intermediate values used during the computation of the final result. For example,
535 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
536 /// words, leaving the allocated object and then re-entering it later is permitted.
538 /// [`offset`]: #method.offset
539 /// [allocated object]: crate::ptr#allocated-object
546 /// // Iterate using a raw pointer in increments of two elements
547 /// let mut data = [1u8, 2, 3, 4, 5];
548 /// let mut ptr: *mut u8 = data.as_mut_ptr();
550 /// let end_rounded_up = ptr.wrapping_offset(6);
552 /// while ptr != end_rounded_up {
556 /// ptr = ptr.wrapping_offset(step);
558 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
560 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
561 #[must_use = "returns a new pointer rather than modifying its argument"]
562 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
564 pub const fn wrapping_offset(self, count: isize) -> *mut T
568 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
569 unsafe { intrinsics::arith_offset(self, count) as *mut T }
572 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
574 /// `count` is in units of **bytes**.
576 /// This is purely a convenience for casting to a `u8` pointer and
577 /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
578 /// for documentation.
580 /// For non-`Sized` pointees this operation changes only the data pointer,
581 /// leaving the metadata untouched.
584 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
585 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
586 pub const fn wrapping_byte_offset(self, count: isize) -> Self {
587 self.cast::<u8>().wrapping_offset(count).with_metadata_of(self)
590 /// Masks out bits of the pointer according to a mask.
592 /// This is convenience for `ptr.map_addr(|a| a & mask)`.
594 /// For non-`Sized` pointees this operation changes only the data pointer,
595 /// leaving the metadata untouched.
600 /// #![feature(ptr_mask, strict_provenance)]
601 /// let mut v = 17_u32;
602 /// let ptr: *mut u32 = &mut v;
604 /// // `u32` is 4 bytes aligned,
605 /// // which means that lower 2 bits are always 0.
606 /// let tag_mask = 0b11;
607 /// let ptr_mask = !tag_mask;
609 /// // We can store something in these lower bits
610 /// let tagged_ptr = ptr.map_addr(|a| a | 0b10);
612 /// // Get the "tag" back
613 /// let tag = tagged_ptr.addr() & tag_mask;
614 /// assert_eq!(tag, 0b10);
616 /// // Note that `tagged_ptr` is unaligned, it's UB to read from/write to it.
617 /// // To get original pointer `mask` can be used:
618 /// let masked_ptr = tagged_ptr.mask(ptr_mask);
619 /// assert_eq!(unsafe { *masked_ptr }, 17);
621 /// unsafe { *masked_ptr = 0 };
622 /// assert_eq!(v, 0);
624 #[unstable(feature = "ptr_mask", issue = "98290")]
625 #[must_use = "returns a new pointer rather than modifying its argument"]
627 pub fn mask(self, mask: usize) -> *mut T {
628 intrinsics::ptr_mask(self.cast::<()>(), mask).cast_mut().with_metadata_of(self)
631 /// Returns `None` if the pointer is null, or else returns a unique reference to
632 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
633 /// must be used instead.
635 /// For the shared counterpart see [`as_ref`].
637 /// [`as_uninit_mut`]: #method.as_uninit_mut
638 /// [`as_ref`]: #method.as_ref-1
642 /// When calling this method, you have to ensure that *either* the pointer is null *or*
643 /// all of the following is true:
645 /// * The pointer must be properly aligned.
647 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
649 /// * The pointer must point to an initialized instance of `T`.
651 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
652 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
653 /// In particular, while this reference exists, the memory the pointer points to must
654 /// not get accessed (read or written) through any other pointer.
656 /// This applies even if the result of this method is unused!
657 /// (The part about being initialized is not yet fully decided, but until
658 /// it is, the only safe approach is to ensure that they are indeed initialized.)
660 /// [the module documentation]: crate::ptr#safety
667 /// let mut s = [1, 2, 3];
668 /// let ptr: *mut u32 = s.as_mut_ptr();
669 /// let first_value = unsafe { ptr.as_mut().unwrap() };
670 /// *first_value = 4;
671 /// # assert_eq!(s, [4, 2, 3]);
672 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
675 /// # Null-unchecked version
677 /// If you are sure the pointer can never be null and are looking for some kind of
678 /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
679 /// you can dereference the pointer directly.
682 /// let mut s = [1, 2, 3];
683 /// let ptr: *mut u32 = s.as_mut_ptr();
684 /// let first_value = unsafe { &mut *ptr };
685 /// *first_value = 4;
686 /// # assert_eq!(s, [4, 2, 3]);
687 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
689 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
690 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
692 pub const unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
693 // SAFETY: the caller must guarantee that `self` is be valid for
694 // a mutable reference if it isn't null.
695 if self.is_null() { None } else { unsafe { Some(&mut *self) } }
698 /// Returns `None` if the pointer is null, or else returns a unique reference to
699 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
700 /// that the value has to be initialized.
702 /// For the shared counterpart see [`as_uninit_ref`].
704 /// [`as_mut`]: #method.as_mut
705 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
709 /// When calling this method, you have to ensure that *either* the pointer is null *or*
710 /// all of the following is true:
712 /// * The pointer must be properly aligned.
714 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
716 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
717 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
718 /// In particular, while this reference exists, the memory the pointer points to must
719 /// not get accessed (read or written) through any other pointer.
721 /// This applies even if the result of this method is unused!
723 /// [the module documentation]: crate::ptr#safety
725 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
726 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
727 pub const unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
731 // SAFETY: the caller must guarantee that `self` meets all the
732 // requirements for a reference.
733 if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
736 /// Returns whether two pointers are guaranteed to be equal.
738 /// At runtime this function behaves like `Some(self == other)`.
739 /// However, in some contexts (e.g., compile-time evaluation),
740 /// it is not always possible to determine equality of two pointers, so this function may
741 /// spuriously return `None` for pointers that later actually turn out to have its equality known.
742 /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
744 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
745 /// version and unsafe code must not
746 /// rely on the result of this function for soundness. It is suggested to only use this function
747 /// for performance optimizations where spurious `None` return values by this function do not
748 /// affect the outcome, but just the performance.
749 /// The consequences of using this method to make runtime and compile-time code behave
750 /// differently have not been explored. This method should not be used to introduce such
751 /// differences, and it should also not be stabilized before we have a better understanding
753 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
754 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
756 pub const fn guaranteed_eq(self, other: *mut T) -> Option<bool>
760 (self as *const T).guaranteed_eq(other as _)
763 /// Returns whether two pointers are guaranteed to be inequal.
765 /// At runtime this function behaves like `Some(self != other)`.
766 /// However, in some contexts (e.g., compile-time evaluation),
767 /// it is not always possible to determine inequality of two pointers, so this function may
768 /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
769 /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
771 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
772 /// version and unsafe code must not
773 /// rely on the result of this function for soundness. It is suggested to only use this function
774 /// for performance optimizations where spurious `None` return values by this function do not
775 /// affect the outcome, but just the performance.
776 /// The consequences of using this method to make runtime and compile-time code behave
777 /// differently have not been explored. This method should not be used to introduce such
778 /// differences, and it should also not be stabilized before we have a better understanding
780 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
781 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
783 pub const fn guaranteed_ne(self, other: *mut T) -> Option<bool>
787 (self as *const T).guaranteed_ne(other as _)
790 /// Calculates the distance between two pointers. The returned value is in
791 /// units of T: the distance in bytes divided by `mem::size_of::<T>()`.
793 /// This function is the inverse of [`offset`].
795 /// [`offset`]: #method.offset-1
799 /// If any of the following conditions are violated, the result is Undefined
802 /// * Both the starting and other pointer must be either in bounds or one
803 /// byte past the end of the same [allocated object].
805 /// * Both pointers must be *derived from* a pointer to the same object.
806 /// (See below for an example.)
808 /// * The distance between the pointers, in bytes, must be an exact multiple
809 /// of the size of `T`.
811 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
813 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
815 /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
816 /// address space, so two pointers within some value of any Rust type `T` will always satisfy
817 /// the last two conditions. The standard library also generally ensures that allocations
818 /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
819 /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
820 /// always satisfies the last two conditions.
822 /// Most platforms fundamentally can't even construct such a large allocation.
823 /// For instance, no known 64-bit platform can ever serve a request
824 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
825 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
826 /// more than `isize::MAX` bytes with things like Physical Address
827 /// Extension. As such, memory acquired directly from allocators or memory
828 /// mapped files *may* be too large to handle with this function.
829 /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
830 /// such large allocations either.)
832 /// [`add`]: #method.add
833 /// [allocated object]: crate::ptr#allocated-object
837 /// This function panics if `T` is a Zero-Sized Type ("ZST").
844 /// let mut a = [0; 5];
845 /// let ptr1: *mut i32 = &mut a[1];
846 /// let ptr2: *mut i32 = &mut a[3];
848 /// assert_eq!(ptr2.offset_from(ptr1), 2);
849 /// assert_eq!(ptr1.offset_from(ptr2), -2);
850 /// assert_eq!(ptr1.offset(2), ptr2);
851 /// assert_eq!(ptr2.offset(-2), ptr1);
855 /// *Incorrect* usage:
858 /// let ptr1 = Box::into_raw(Box::new(0u8));
859 /// let ptr2 = Box::into_raw(Box::new(1u8));
860 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
861 /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
862 /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff);
863 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
864 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
865 /// // computing their offset is undefined behavior, even though
866 /// // they point to the same address!
868 /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
871 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
872 #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
874 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
875 pub const unsafe fn offset_from(self, origin: *const T) -> isize
879 // SAFETY: the caller must uphold the safety contract for `offset_from`.
880 unsafe { (self as *const T).offset_from(origin) }
883 /// Calculates the distance between two pointers. The returned value is in
884 /// units of **bytes**.
886 /// This is purely a convenience for casting to a `u8` pointer and
887 /// using [offset_from][pointer::offset_from] on it. See that method for
888 /// documentation and safety requirements.
890 /// For non-`Sized` pointees this operation considers only the data pointers,
891 /// ignoring the metadata.
893 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
894 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
895 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
896 pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: *const U) -> isize {
897 // SAFETY: the caller must uphold the safety contract for `offset_from`.
898 unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
901 /// Calculates the distance between two pointers, *where it's known that
902 /// `self` is equal to or greater than `origin`*. The returned value is in
903 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
905 /// This computes the same value that [`offset_from`](#method.offset_from)
906 /// would compute, but with the added precondition that the offset is
907 /// guaranteed to be non-negative. This method is equivalent to
908 /// `usize::from(self.offset_from(origin)).unwrap_unchecked()`,
909 /// but it provides slightly more information to the optimizer, which can
910 /// sometimes allow it to optimize slightly better with some backends.
912 /// This method can be though of as recovering the `count` that was passed
913 /// to [`add`](#method.add) (or, with the parameters in the other order,
914 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
915 /// that their safety preconditions are met:
917 /// # #![feature(ptr_sub_ptr)]
918 /// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool {
919 /// ptr.sub_ptr(origin) == count
921 /// origin.add(count) == ptr
923 /// ptr.sub(count) == origin
929 /// - The distance between the pointers must be non-negative (`self >= origin`)
931 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
932 /// apply to this method as well; see it for the full details.
934 /// Importantly, despite the return type of this method being able to represent
935 /// a larger offset, it's still *not permitted* to pass pointers which differ
936 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
937 /// always be less than or equal to `isize::MAX as usize`.
941 /// This function panics if `T` is a Zero-Sized Type ("ZST").
946 /// #![feature(ptr_sub_ptr)]
948 /// let mut a = [0; 5];
949 /// let p: *mut i32 = a.as_mut_ptr();
951 /// let ptr1: *mut i32 = p.add(1);
952 /// let ptr2: *mut i32 = p.add(3);
954 /// assert_eq!(ptr2.sub_ptr(ptr1), 2);
955 /// assert_eq!(ptr1.add(2), ptr2);
956 /// assert_eq!(ptr2.sub(2), ptr1);
957 /// assert_eq!(ptr2.sub_ptr(ptr2), 0);
960 /// // This would be incorrect, as the pointers are not correctly ordered:
961 /// // ptr1.offset_from(ptr2)
962 #[unstable(feature = "ptr_sub_ptr", issue = "95892")]
963 #[rustc_const_unstable(feature = "const_ptr_sub_ptr", issue = "95892")]
965 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
966 pub const unsafe fn sub_ptr(self, origin: *const T) -> usize
970 // SAFETY: the caller must uphold the safety contract for `sub_ptr`.
971 unsafe { (self as *const T).sub_ptr(origin) }
974 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
976 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
977 /// offset of `3 * size_of::<T>()` bytes.
981 /// If any of the following conditions are violated, the result is Undefined
984 /// * Both the starting and resulting pointer must be either in bounds or one
985 /// byte past the end of the same [allocated object].
987 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
989 /// * The offset being in bounds cannot rely on "wrapping around" the address
990 /// space. That is, the infinite-precision sum must fit in a `usize`.
992 /// The compiler and standard library generally tries to ensure allocations
993 /// never reach a size where an offset is a concern. For instance, `Vec`
994 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
995 /// `vec.as_ptr().add(vec.len())` is always safe.
997 /// Most platforms fundamentally can't even construct such an allocation.
998 /// For instance, no known 64-bit platform can ever serve a request
999 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1000 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1001 /// more than `isize::MAX` bytes with things like Physical Address
1002 /// Extension. As such, memory acquired directly from allocators or memory
1003 /// mapped files *may* be too large to handle with this function.
1005 /// Consider using [`wrapping_add`] instead if these constraints are
1006 /// difficult to satisfy. The only advantage of this method is that it
1007 /// enables more aggressive compiler optimizations.
1009 /// [`wrapping_add`]: #method.wrapping_add
1010 /// [allocated object]: crate::ptr#allocated-object
1017 /// let s: &str = "123";
1018 /// let ptr: *const u8 = s.as_ptr();
1021 /// println!("{}", *ptr.add(1) as char);
1022 /// println!("{}", *ptr.add(2) as char);
1025 #[stable(feature = "pointer_methods", since = "1.26.0")]
1026 #[must_use = "returns a new pointer rather than modifying its argument"]
1027 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1029 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1030 pub const unsafe fn add(self, count: usize) -> Self
1034 // SAFETY: the caller must uphold the safety contract for `offset`.
1035 unsafe { self.offset(count as isize) }
1038 /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
1040 /// `count` is in units of bytes.
1042 /// This is purely a convenience for casting to a `u8` pointer and
1043 /// using [add][pointer::add] on it. See that method for documentation
1044 /// and safety requirements.
1046 /// For non-`Sized` pointees this operation changes only the data pointer,
1047 /// leaving the metadata untouched.
1050 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1051 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1052 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1053 pub const unsafe fn byte_add(self, count: usize) -> Self {
1054 // SAFETY: the caller must uphold the safety contract for `add`.
1055 unsafe { self.cast::<u8>().add(count).with_metadata_of(self) }
1058 /// Calculates the offset from a pointer (convenience for
1059 /// `.offset((count as isize).wrapping_neg())`).
1061 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1062 /// offset of `3 * size_of::<T>()` bytes.
1066 /// If any of the following conditions are violated, the result is Undefined
1069 /// * Both the starting and resulting pointer must be either in bounds or one
1070 /// byte past the end of the same [allocated object].
1072 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1074 /// * The offset being in bounds cannot rely on "wrapping around" the address
1075 /// space. That is, the infinite-precision sum must fit in a usize.
1077 /// The compiler and standard library generally tries to ensure allocations
1078 /// never reach a size where an offset is a concern. For instance, `Vec`
1079 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1080 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1082 /// Most platforms fundamentally can't even construct such an allocation.
1083 /// For instance, no known 64-bit platform can ever serve a request
1084 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1085 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1086 /// more than `isize::MAX` bytes with things like Physical Address
1087 /// Extension. As such, memory acquired directly from allocators or memory
1088 /// mapped files *may* be too large to handle with this function.
1090 /// Consider using [`wrapping_sub`] instead if these constraints are
1091 /// difficult to satisfy. The only advantage of this method is that it
1092 /// enables more aggressive compiler optimizations.
1094 /// [`wrapping_sub`]: #method.wrapping_sub
1095 /// [allocated object]: crate::ptr#allocated-object
1102 /// let s: &str = "123";
1105 /// let end: *const u8 = s.as_ptr().add(3);
1106 /// println!("{}", *end.sub(1) as char);
1107 /// println!("{}", *end.sub(2) as char);
1110 #[stable(feature = "pointer_methods", since = "1.26.0")]
1111 #[must_use = "returns a new pointer rather than modifying its argument"]
1112 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1114 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1115 pub const unsafe fn sub(self, count: usize) -> Self
1119 // SAFETY: the caller must uphold the safety contract for `offset`.
1120 unsafe { self.offset((count as isize).wrapping_neg()) }
1123 /// Calculates the offset from a pointer in bytes (convenience for
1124 /// `.byte_offset((count as isize).wrapping_neg())`).
1126 /// `count` is in units of bytes.
1128 /// This is purely a convenience for casting to a `u8` pointer and
1129 /// using [sub][pointer::sub] on it. See that method for documentation
1130 /// and safety requirements.
1132 /// For non-`Sized` pointees this operation changes only the data pointer,
1133 /// leaving the metadata untouched.
1136 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1137 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1138 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1139 pub const unsafe fn byte_sub(self, count: usize) -> Self {
1140 // SAFETY: the caller must uphold the safety contract for `sub`.
1141 unsafe { self.cast::<u8>().sub(count).with_metadata_of(self) }
1144 /// Calculates the offset from a pointer using wrapping arithmetic.
1145 /// (convenience for `.wrapping_offset(count as isize)`)
1147 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1148 /// offset of `3 * size_of::<T>()` bytes.
1152 /// This operation itself is always safe, but using the resulting pointer is not.
1154 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1155 /// be used to read or write other allocated objects.
1157 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1158 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1159 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1160 /// `x` and `y` point into the same allocated object.
1162 /// Compared to [`add`], this method basically delays the requirement of staying within the
1163 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
1164 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1165 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1166 /// can be optimized better and is thus preferable in performance-sensitive code.
1168 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1169 /// intermediate values used during the computation of the final result. For example,
1170 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1171 /// allocated object and then re-entering it later is permitted.
1173 /// [`add`]: #method.add
1174 /// [allocated object]: crate::ptr#allocated-object
1181 /// // Iterate using a raw pointer in increments of two elements
1182 /// let data = [1u8, 2, 3, 4, 5];
1183 /// let mut ptr: *const u8 = data.as_ptr();
1185 /// let end_rounded_up = ptr.wrapping_add(6);
1187 /// // This loop prints "1, 3, 5, "
1188 /// while ptr != end_rounded_up {
1190 /// print!("{}, ", *ptr);
1192 /// ptr = ptr.wrapping_add(step);
1195 #[stable(feature = "pointer_methods", since = "1.26.0")]
1196 #[must_use = "returns a new pointer rather than modifying its argument"]
1197 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1199 pub const fn wrapping_add(self, count: usize) -> Self
1203 self.wrapping_offset(count as isize)
1206 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1207 /// (convenience for `.wrapping_byte_offset(count as isize)`)
1209 /// `count` is in units of bytes.
1211 /// This is purely a convenience for casting to a `u8` pointer and
1212 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1214 /// For non-`Sized` pointees this operation changes only the data pointer,
1215 /// leaving the metadata untouched.
1218 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1219 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1220 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1221 self.cast::<u8>().wrapping_add(count).with_metadata_of(self)
1224 /// Calculates the offset from a pointer using wrapping arithmetic.
1225 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1227 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1228 /// offset of `3 * size_of::<T>()` bytes.
1232 /// This operation itself is always safe, but using the resulting pointer is not.
1234 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1235 /// be used to read or write other allocated objects.
1237 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1238 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1239 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1240 /// `x` and `y` point into the same allocated object.
1242 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1243 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
1244 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1245 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1246 /// can be optimized better and is thus preferable in performance-sensitive code.
1248 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1249 /// intermediate values used during the computation of the final result. For example,
1250 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1251 /// allocated object and then re-entering it later is permitted.
1253 /// [`sub`]: #method.sub
1254 /// [allocated object]: crate::ptr#allocated-object
1261 /// // Iterate using a raw pointer in increments of two elements (backwards)
1262 /// let data = [1u8, 2, 3, 4, 5];
1263 /// let mut ptr: *const u8 = data.as_ptr();
1264 /// let start_rounded_down = ptr.wrapping_sub(2);
1265 /// ptr = ptr.wrapping_add(4);
1267 /// // This loop prints "5, 3, 1, "
1268 /// while ptr != start_rounded_down {
1270 /// print!("{}, ", *ptr);
1272 /// ptr = ptr.wrapping_sub(step);
1275 #[stable(feature = "pointer_methods", since = "1.26.0")]
1276 #[must_use = "returns a new pointer rather than modifying its argument"]
1277 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1279 pub const fn wrapping_sub(self, count: usize) -> Self
1283 self.wrapping_offset((count as isize).wrapping_neg())
1286 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1287 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1289 /// `count` is in units of bytes.
1291 /// This is purely a convenience for casting to a `u8` pointer and
1292 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1294 /// For non-`Sized` pointees this operation changes only the data pointer,
1295 /// leaving the metadata untouched.
1298 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1299 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1300 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1301 self.cast::<u8>().wrapping_sub(count).with_metadata_of(self)
1304 /// Reads the value from `self` without moving it. This leaves the
1305 /// memory in `self` unchanged.
1307 /// See [`ptr::read`] for safety concerns and examples.
1309 /// [`ptr::read`]: crate::ptr::read()
1310 #[stable(feature = "pointer_methods", since = "1.26.0")]
1311 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1313 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1314 pub const unsafe fn read(self) -> T
1318 // SAFETY: the caller must uphold the safety contract for ``.
1319 unsafe { read(self) }
1322 /// Performs a volatile read of the value from `self` without moving it. This
1323 /// leaves the memory in `self` unchanged.
1325 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1326 /// to not be elided or reordered by the compiler across other volatile
1329 /// See [`ptr::read_volatile`] for safety concerns and examples.
1331 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1332 #[stable(feature = "pointer_methods", since = "1.26.0")]
1334 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1335 pub unsafe fn read_volatile(self) -> T
1339 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1340 unsafe { read_volatile(self) }
1343 /// Reads the value from `self` without moving it. This leaves the
1344 /// memory in `self` unchanged.
1346 /// Unlike `read`, the pointer may be unaligned.
1348 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1350 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1351 #[stable(feature = "pointer_methods", since = "1.26.0")]
1352 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1354 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1355 pub const unsafe fn read_unaligned(self) -> T
1359 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1360 unsafe { read_unaligned(self) }
1363 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1364 /// and destination may overlap.
1366 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1368 /// See [`ptr::copy`] for safety concerns and examples.
1370 /// [`ptr::copy`]: crate::ptr::copy()
1371 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1372 #[stable(feature = "pointer_methods", since = "1.26.0")]
1374 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1375 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1379 // SAFETY: the caller must uphold the safety contract for `copy`.
1380 unsafe { copy(self, dest, count) }
1383 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1384 /// and destination may *not* overlap.
1386 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1388 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1390 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1391 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1392 #[stable(feature = "pointer_methods", since = "1.26.0")]
1394 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1395 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1399 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1400 unsafe { copy_nonoverlapping(self, dest, count) }
1403 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1404 /// and destination may overlap.
1406 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1408 /// See [`ptr::copy`] for safety concerns and examples.
1410 /// [`ptr::copy`]: crate::ptr::copy()
1411 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1412 #[stable(feature = "pointer_methods", since = "1.26.0")]
1414 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1415 pub const unsafe fn copy_from(self, src: *const T, count: usize)
1419 // SAFETY: the caller must uphold the safety contract for `copy`.
1420 unsafe { copy(src, self, count) }
1423 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1424 /// and destination may *not* overlap.
1426 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1428 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1430 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1431 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1432 #[stable(feature = "pointer_methods", since = "1.26.0")]
1434 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1435 pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1439 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1440 unsafe { copy_nonoverlapping(src, self, count) }
1443 /// Executes the destructor (if any) of the pointed-to value.
1445 /// See [`ptr::drop_in_place`] for safety concerns and examples.
1447 /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1448 #[stable(feature = "pointer_methods", since = "1.26.0")]
1450 pub unsafe fn drop_in_place(self) {
1451 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1452 unsafe { drop_in_place(self) }
1455 /// Overwrites a memory location with the given value without reading or
1456 /// dropping the old value.
1458 /// See [`ptr::write`] for safety concerns and examples.
1460 /// [`ptr::write`]: crate::ptr::write()
1461 #[stable(feature = "pointer_methods", since = "1.26.0")]
1462 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1464 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1465 pub const unsafe fn write(self, val: T)
1469 // SAFETY: the caller must uphold the safety contract for `write`.
1470 unsafe { write(self, val) }
1473 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1474 /// bytes of memory starting at `self` to `val`.
1476 /// See [`ptr::write_bytes`] for safety concerns and examples.
1478 /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1479 #[doc(alias = "memset")]
1480 #[stable(feature = "pointer_methods", since = "1.26.0")]
1481 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1483 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1484 pub const unsafe fn write_bytes(self, val: u8, count: usize)
1488 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1489 unsafe { write_bytes(self, val, count) }
1492 /// Performs a volatile write of a memory location with the given value without
1493 /// reading or dropping the old value.
1495 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1496 /// to not be elided or reordered by the compiler across other volatile
1499 /// See [`ptr::write_volatile`] for safety concerns and examples.
1501 /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1502 #[stable(feature = "pointer_methods", since = "1.26.0")]
1504 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1505 pub unsafe fn write_volatile(self, val: T)
1509 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1510 unsafe { write_volatile(self, val) }
1513 /// Overwrites a memory location with the given value without reading or
1514 /// dropping the old value.
1516 /// Unlike `write`, the pointer may be unaligned.
1518 /// See [`ptr::write_unaligned`] for safety concerns and examples.
1520 /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1521 #[stable(feature = "pointer_methods", since = "1.26.0")]
1522 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1524 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1525 pub const unsafe fn write_unaligned(self, val: T)
1529 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1530 unsafe { write_unaligned(self, val) }
1533 /// Replaces the value at `self` with `src`, returning the old
1534 /// value, without dropping either.
1536 /// See [`ptr::replace`] for safety concerns and examples.
1538 /// [`ptr::replace`]: crate::ptr::replace()
1539 #[stable(feature = "pointer_methods", since = "1.26.0")]
1541 pub unsafe fn replace(self, src: T) -> T
1545 // SAFETY: the caller must uphold the safety contract for `replace`.
1546 unsafe { replace(self, src) }
1549 /// Swaps the values at two mutable locations of the same type, without
1550 /// deinitializing either. They may overlap, unlike `mem::swap` which is
1551 /// otherwise equivalent.
1553 /// See [`ptr::swap`] for safety concerns and examples.
1555 /// [`ptr::swap`]: crate::ptr::swap()
1556 #[stable(feature = "pointer_methods", since = "1.26.0")]
1557 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
1559 pub const unsafe fn swap(self, with: *mut T)
1563 // SAFETY: the caller must uphold the safety contract for `swap`.
1564 unsafe { swap(self, with) }
1567 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1570 /// If it is not possible to align the pointer, the implementation returns
1571 /// `usize::MAX`. It is permissible for the implementation to *always*
1572 /// return `usize::MAX`. Only your algorithm's performance can depend
1573 /// on getting a usable offset here, not its correctness.
1575 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1576 /// used with the `wrapping_add` method.
1578 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1579 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1580 /// the returned offset is correct in all terms other than alignment.
1584 /// The function panics if `align` is not a power-of-two.
1588 /// Accessing adjacent `u8` as `u16`
1591 /// use std::mem::align_of;
1594 /// let mut x = [5_u8, 6, 7, 8, 9];
1595 /// let ptr = x.as_mut_ptr();
1596 /// let offset = ptr.align_offset(align_of::<u16>());
1598 /// if offset < x.len() - 1 {
1599 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1602 /// assert!(x == [0, 0, 7, 8, 9] || x == [5, 0, 0, 8, 9]);
1604 /// // while the pointer can be aligned via `offset`, it would point
1605 /// // outside the allocation
1611 #[stable(feature = "align_offset", since = "1.36.0")]
1612 #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1613 pub const fn align_offset(self, align: usize) -> usize
1617 if !align.is_power_of_two() {
1618 panic!("align_offset: align is not a power-of-two");
1623 fn rt_impl<T>(p: *mut T, align: usize) -> usize {
1624 // SAFETY: `align` has been checked to be a power of 2 above
1625 unsafe { align_offset(p, align) }
1628 const fn ctfe_impl<T>(_: *mut T, _: usize) -> usize {
1633 // It is permissible for `align_offset` to always return `usize::MAX`,
1634 // algorithm correctness can not depend on `align_offset` returning non-max values.
1636 // As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
1637 unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
1640 #[cfg(not(bootstrap))]
1642 // SAFETY: `align` has been checked to be a power of 2 above
1643 unsafe { align_offset(self, align) }
1647 /// Returns whether the pointer is properly aligned for `T`.
1653 /// #![feature(pointer_is_aligned)]
1654 /// #![feature(pointer_byte_offsets)]
1656 /// // On some platforms, the alignment of i32 is less than 4.
1657 /// #[repr(align(4))]
1658 /// struct AlignedI32(i32);
1660 /// let mut data = AlignedI32(42);
1661 /// let ptr = &mut data as *mut AlignedI32;
1663 /// assert!(ptr.is_aligned());
1664 /// assert!(!ptr.wrapping_byte_add(1).is_aligned());
1667 /// # At compiletime
1668 /// **Note: Alignment at compiletime is experimental and subject to change. See the
1669 /// [tracking issue] for details.**
1671 /// At compiletime, the compiler may not know where a value will end up in memory.
1672 /// Calling this function on a pointer created from a reference at compiletime will only
1673 /// return `true` if the pointer is guaranteed to be aligned. This means that the pointer
1674 /// is never aligned if cast to a type with a stricter alignment than the reference's
1675 /// underlying allocation.
1677 #[cfg_attr(bootstrap, doc = "```ignore")]
1678 #[cfg_attr(not(bootstrap), doc = "```")]
1679 /// #![feature(pointer_is_aligned)]
1680 /// #![feature(const_pointer_is_aligned)]
1681 /// #![feature(const_mut_refs)]
1683 /// // On some platforms, the alignment of primitives is less than their size.
1684 /// #[repr(align(4))]
1685 /// struct AlignedI32(i32);
1686 /// #[repr(align(8))]
1687 /// struct AlignedI64(i64);
1690 /// let mut data = AlignedI32(42);
1691 /// let ptr = &mut data as *mut AlignedI32;
1692 /// assert!(ptr.is_aligned());
1694 /// // At runtime either `ptr1` or `ptr2` would be aligned, but at compiletime neither is aligned.
1695 /// let ptr1 = ptr.cast::<AlignedI64>();
1696 /// let ptr2 = ptr.wrapping_add(1).cast::<AlignedI64>();
1697 /// assert!(!ptr1.is_aligned());
1698 /// assert!(!ptr2.is_aligned());
1702 /// Due to this behavior, it is possible that a runtime pointer derived from a compiletime
1703 /// pointer is aligned, even if the compiletime pointer wasn't aligned.
1705 #[cfg_attr(bootstrap, doc = "```ignore")]
1706 #[cfg_attr(not(bootstrap), doc = "```")]
1707 /// #![feature(pointer_is_aligned)]
1708 /// #![feature(const_pointer_is_aligned)]
1710 /// // On some platforms, the alignment of primitives is less than their size.
1711 /// #[repr(align(4))]
1712 /// struct AlignedI32(i32);
1713 /// #[repr(align(8))]
1714 /// struct AlignedI64(i64);
1716 /// // At compiletime, neither `COMPTIME_PTR` nor `COMPTIME_PTR + 1` is aligned.
1717 /// // Also, note that mutable references are not allowed in the final value of constants.
1718 /// const COMPTIME_PTR: *mut AlignedI32 = (&AlignedI32(42) as *const AlignedI32).cast_mut();
1719 /// const _: () = assert!(!COMPTIME_PTR.cast::<AlignedI64>().is_aligned());
1720 /// const _: () = assert!(!COMPTIME_PTR.wrapping_add(1).cast::<AlignedI64>().is_aligned());
1722 /// // At runtime, either `runtime_ptr` or `runtime_ptr + 1` is aligned.
1723 /// let runtime_ptr = COMPTIME_PTR;
1725 /// runtime_ptr.cast::<AlignedI64>().is_aligned(),
1726 /// runtime_ptr.wrapping_add(1).cast::<AlignedI64>().is_aligned(),
1730 /// If a pointer is created from a fixed address, this function behaves the same during
1731 /// runtime and compiletime.
1733 #[cfg_attr(bootstrap, doc = "```ignore")]
1734 #[cfg_attr(not(bootstrap), doc = "```")]
1735 /// #![feature(pointer_is_aligned)]
1736 /// #![feature(const_pointer_is_aligned)]
1738 /// // On some platforms, the alignment of primitives is less than their size.
1739 /// #[repr(align(4))]
1740 /// struct AlignedI32(i32);
1741 /// #[repr(align(8))]
1742 /// struct AlignedI64(i64);
1745 /// let ptr = 40 as *mut AlignedI32;
1746 /// assert!(ptr.is_aligned());
1748 /// // For pointers with a known address, runtime and compiletime behavior are identical.
1749 /// let ptr1 = ptr.cast::<AlignedI64>();
1750 /// let ptr2 = ptr.wrapping_add(1).cast::<AlignedI64>();
1751 /// assert!(ptr1.is_aligned());
1752 /// assert!(!ptr2.is_aligned());
1756 /// [tracking issue]: https://github.com/rust-lang/rust/issues/104203
1759 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1760 #[rustc_const_unstable(feature = "const_pointer_is_aligned", issue = "104203")]
1761 pub const fn is_aligned(self) -> bool
1765 self.is_aligned_to(mem::align_of::<T>())
1768 /// Returns whether the pointer is aligned to `align`.
1770 /// For non-`Sized` pointees this operation considers only the data pointer,
1771 /// ignoring the metadata.
1775 /// The function panics if `align` is not a power-of-two (this includes 0).
1781 /// #![feature(pointer_is_aligned)]
1782 /// #![feature(pointer_byte_offsets)]
1784 /// // On some platforms, the alignment of i32 is less than 4.
1785 /// #[repr(align(4))]
1786 /// struct AlignedI32(i32);
1788 /// let mut data = AlignedI32(42);
1789 /// let ptr = &mut data as *mut AlignedI32;
1791 /// assert!(ptr.is_aligned_to(1));
1792 /// assert!(ptr.is_aligned_to(2));
1793 /// assert!(ptr.is_aligned_to(4));
1795 /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1796 /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1798 /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1801 /// # At compiletime
1802 /// **Note: Alignment at compiletime is experimental and subject to change. See the
1803 /// [tracking issue] for details.**
1805 /// At compiletime, the compiler may not know where a value will end up in memory.
1806 /// Calling this function on a pointer created from a reference at compiletime will only
1807 /// return `true` if the pointer is guaranteed to be aligned. This means that the pointer
1808 /// cannot be stricter aligned than the reference's underlying allocation.
1810 #[cfg_attr(bootstrap, doc = "```ignore")]
1811 #[cfg_attr(not(bootstrap), doc = "```")]
1812 /// #![feature(pointer_is_aligned)]
1813 /// #![feature(const_pointer_is_aligned)]
1814 /// #![feature(const_mut_refs)]
1816 /// // On some platforms, the alignment of i32 is less than 4.
1817 /// #[repr(align(4))]
1818 /// struct AlignedI32(i32);
1821 /// let mut data = AlignedI32(42);
1822 /// let ptr = &mut data as *mut AlignedI32;
1824 /// assert!(ptr.is_aligned_to(1));
1825 /// assert!(ptr.is_aligned_to(2));
1826 /// assert!(ptr.is_aligned_to(4));
1828 /// // At compiletime, we know for sure that the pointer isn't aligned to 8.
1829 /// assert!(!ptr.is_aligned_to(8));
1830 /// assert!(!ptr.wrapping_add(1).is_aligned_to(8));
1834 /// Due to this behavior, it is possible that a runtime pointer derived from a compiletime
1835 /// pointer is aligned, even if the compiletime pointer wasn't aligned.
1837 #[cfg_attr(bootstrap, doc = "```ignore")]
1838 #[cfg_attr(not(bootstrap), doc = "```")]
1839 /// #![feature(pointer_is_aligned)]
1840 /// #![feature(const_pointer_is_aligned)]
1842 /// // On some platforms, the alignment of i32 is less than 4.
1843 /// #[repr(align(4))]
1844 /// struct AlignedI32(i32);
1846 /// // At compiletime, neither `COMPTIME_PTR` nor `COMPTIME_PTR + 1` is aligned.
1847 /// // Also, note that mutable references are not allowed in the final value of constants.
1848 /// const COMPTIME_PTR: *mut AlignedI32 = (&AlignedI32(42) as *const AlignedI32).cast_mut();
1849 /// const _: () = assert!(!COMPTIME_PTR.is_aligned_to(8));
1850 /// const _: () = assert!(!COMPTIME_PTR.wrapping_add(1).is_aligned_to(8));
1852 /// // At runtime, either `runtime_ptr` or `runtime_ptr + 1` is aligned.
1853 /// let runtime_ptr = COMPTIME_PTR;
1855 /// runtime_ptr.is_aligned_to(8),
1856 /// runtime_ptr.wrapping_add(1).is_aligned_to(8),
1860 /// If a pointer is created from a fixed address, this function behaves the same during
1861 /// runtime and compiletime.
1863 #[cfg_attr(bootstrap, doc = "```ignore")]
1864 #[cfg_attr(not(bootstrap), doc = "```")]
1865 /// #![feature(pointer_is_aligned)]
1866 /// #![feature(const_pointer_is_aligned)]
1869 /// let ptr = 40 as *mut u8;
1870 /// assert!(ptr.is_aligned_to(1));
1871 /// assert!(ptr.is_aligned_to(2));
1872 /// assert!(ptr.is_aligned_to(4));
1873 /// assert!(ptr.is_aligned_to(8));
1874 /// assert!(!ptr.is_aligned_to(16));
1878 /// [tracking issue]: https://github.com/rust-lang/rust/issues/104203
1881 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1882 #[rustc_const_unstable(feature = "const_pointer_is_aligned", issue = "104203")]
1883 pub const fn is_aligned_to(self, align: usize) -> bool {
1884 if !align.is_power_of_two() {
1885 panic!("is_aligned_to: align is not a power-of-two");
1888 // We can't use the address of `self` in a `const fn`, so we use `align_offset` instead.
1889 // The cast to `()` is used to
1890 // 1. deal with fat pointers; and
1891 // 2. ensure that `align_offset` doesn't actually try to compute an offset.
1892 self.cast::<()>().align_offset(align) == 0
1897 /// Returns the length of a raw slice.
1899 /// The returned value is the number of **elements**, not the number of bytes.
1901 /// This function is safe, even when the raw slice cannot be cast to a slice
1902 /// reference because the pointer is null or unaligned.
1907 /// #![feature(slice_ptr_len)]
1910 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1911 /// assert_eq!(slice.len(), 3);
1914 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1915 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1916 pub const fn len(self) -> usize {
1920 /// Returns `true` if the raw slice has a length of 0.
1925 /// #![feature(slice_ptr_len)]
1927 /// let mut a = [1, 2, 3];
1928 /// let ptr = &mut a as *mut [_];
1929 /// assert!(!ptr.is_empty());
1932 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1933 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1934 pub const fn is_empty(self) -> bool {
1938 /// Divides one mutable raw slice into two at an index.
1940 /// The first will contain all indices from `[0, mid)` (excluding
1941 /// the index `mid` itself) and the second will contain all
1942 /// indices from `[mid, len)` (excluding the index `len` itself).
1946 /// Panics if `mid > len`.
1950 /// `mid` must be [in-bounds] of the underlying [allocated object].
1951 /// Which means `self` must be dereferenceable and span a single allocation
1952 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1953 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1955 /// Since `len` being in-bounds it is not a safety invariant of `*mut [T]` the
1956 /// safety requirements of this method are the same as for [`split_at_mut_unchecked`].
1957 /// The explicit bounds check is only as useful as `len` is correct.
1959 /// [`split_at_mut_unchecked`]: #method.split_at_mut_unchecked
1960 /// [in-bounds]: #method.add
1961 /// [allocated object]: crate::ptr#allocated-object
1962 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1967 /// #![feature(raw_slice_split)]
1968 /// #![feature(slice_ptr_get)]
1970 /// let mut v = [1, 0, 3, 0, 5, 6];
1971 /// let ptr = &mut v as *mut [_];
1973 /// let (left, right) = ptr.split_at_mut(2);
1974 /// assert_eq!(&*left, [1, 0]);
1975 /// assert_eq!(&*right, [3, 0, 5, 6]);
1980 #[unstable(feature = "raw_slice_split", issue = "95595")]
1981 pub unsafe fn split_at_mut(self, mid: usize) -> (*mut [T], *mut [T]) {
1982 assert!(mid <= self.len());
1983 // SAFETY: The assert above is only a safety-net as long as `self.len()` is correct
1984 // The actual safety requirements of this function are the same as for `split_at_mut_unchecked`
1985 unsafe { self.split_at_mut_unchecked(mid) }
1988 /// Divides one mutable raw slice into two at an index, without doing bounds checking.
1990 /// The first will contain all indices from `[0, mid)` (excluding
1991 /// the index `mid` itself) and the second will contain all
1992 /// indices from `[mid, len)` (excluding the index `len` itself).
1996 /// `mid` must be [in-bounds] of the underlying [allocated object].
1997 /// Which means `self` must be dereferenceable and span a single allocation
1998 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1999 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
2001 /// [in-bounds]: #method.add
2002 /// [out-of-bounds index]: #method.add
2003 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2008 /// #![feature(raw_slice_split)]
2010 /// let mut v = [1, 0, 3, 0, 5, 6];
2011 /// // scoped to restrict the lifetime of the borrows
2013 /// let ptr = &mut v as *mut [_];
2014 /// let (left, right) = ptr.split_at_mut_unchecked(2);
2015 /// assert_eq!(&*left, [1, 0]);
2016 /// assert_eq!(&*right, [3, 0, 5, 6]);
2017 /// (&mut *left)[1] = 2;
2018 /// (&mut *right)[1] = 4;
2020 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
2023 #[unstable(feature = "raw_slice_split", issue = "95595")]
2024 pub unsafe fn split_at_mut_unchecked(self, mid: usize) -> (*mut [T], *mut [T]) {
2025 let len = self.len();
2026 let ptr = self.as_mut_ptr();
2028 // SAFETY: Caller must pass a valid pointer and an index that is in-bounds.
2029 let tail = unsafe { ptr.add(mid) };
2031 crate::ptr::slice_from_raw_parts_mut(ptr, mid),
2032 crate::ptr::slice_from_raw_parts_mut(tail, len - mid),
2036 /// Returns a raw pointer to the slice's buffer.
2038 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
2043 /// #![feature(slice_ptr_get)]
2046 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
2047 /// assert_eq!(slice.as_mut_ptr(), ptr::null_mut());
2050 #[unstable(feature = "slice_ptr_get", issue = "74265")]
2051 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
2052 pub const fn as_mut_ptr(self) -> *mut T {
2056 /// Returns a raw pointer to an element or subslice, without doing bounds
2059 /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
2060 /// is *[undefined behavior]* even if the resulting pointer is not used.
2062 /// [out-of-bounds index]: #method.add
2063 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2068 /// #![feature(slice_ptr_get)]
2070 /// let x = &mut [1, 2, 4] as *mut [i32];
2073 /// assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
2076 #[unstable(feature = "slice_ptr_get", issue = "74265")]
2077 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
2079 pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
2081 I: ~const SliceIndex<[T]>,
2083 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
2084 unsafe { index.get_unchecked_mut(self) }
2087 /// Returns `None` if the pointer is null, or else returns a shared slice to
2088 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
2089 /// that the value has to be initialized.
2091 /// For the mutable counterpart see [`as_uninit_slice_mut`].
2093 /// [`as_ref`]: #method.as_ref-1
2094 /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
2098 /// When calling this method, you have to ensure that *either* the pointer is null *or*
2099 /// all of the following is true:
2101 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
2102 /// and it must be properly aligned. This means in particular:
2104 /// * The entire memory range of this slice must be contained within a single [allocated object]!
2105 /// Slices can never span across multiple allocated objects.
2107 /// * The pointer must be aligned even for zero-length slices. One
2108 /// reason for this is that enum layout optimizations may rely on references
2109 /// (including slices of any length) being aligned and non-null to distinguish
2110 /// them from other data. You can obtain a pointer that is usable as `data`
2111 /// for zero-length slices using [`NonNull::dangling()`].
2113 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
2114 /// See the safety documentation of [`pointer::offset`].
2116 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
2117 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
2118 /// In particular, while this reference exists, the memory the pointer points to must
2119 /// not get mutated (except inside `UnsafeCell`).
2121 /// This applies even if the result of this method is unused!
2123 /// See also [`slice::from_raw_parts`][].
2125 /// [valid]: crate::ptr#safety
2126 /// [allocated object]: crate::ptr#allocated-object
2128 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
2129 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
2130 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
2134 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
2135 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
2139 /// Returns `None` if the pointer is null, or else returns a unique slice to
2140 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
2141 /// that the value has to be initialized.
2143 /// For the shared counterpart see [`as_uninit_slice`].
2145 /// [`as_mut`]: #method.as_mut
2146 /// [`as_uninit_slice`]: #method.as_uninit_slice-1
2150 /// When calling this method, you have to ensure that *either* the pointer is null *or*
2151 /// all of the following is true:
2153 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
2154 /// many bytes, and it must be properly aligned. This means in particular:
2156 /// * The entire memory range of this slice must be contained within a single [allocated object]!
2157 /// Slices can never span across multiple allocated objects.
2159 /// * The pointer must be aligned even for zero-length slices. One
2160 /// reason for this is that enum layout optimizations may rely on references
2161 /// (including slices of any length) being aligned and non-null to distinguish
2162 /// them from other data. You can obtain a pointer that is usable as `data`
2163 /// for zero-length slices using [`NonNull::dangling()`].
2165 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
2166 /// See the safety documentation of [`pointer::offset`].
2168 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
2169 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
2170 /// In particular, while this reference exists, the memory the pointer points to must
2171 /// not get accessed (read or written) through any other pointer.
2173 /// This applies even if the result of this method is unused!
2175 /// See also [`slice::from_raw_parts_mut`][].
2177 /// [valid]: crate::ptr#safety
2178 /// [allocated object]: crate::ptr#allocated-object
2180 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
2181 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
2182 pub const unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
2186 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
2187 Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
2192 // Equality for pointers
2193 #[stable(feature = "rust1", since = "1.0.0")]
2194 impl<T: ?Sized> PartialEq for *mut T {
2196 fn eq(&self, other: &*mut T) -> bool {
2201 #[stable(feature = "rust1", since = "1.0.0")]
2202 impl<T: ?Sized> Eq for *mut T {}
2204 #[stable(feature = "rust1", since = "1.0.0")]
2205 impl<T: ?Sized> Ord for *mut T {
2207 fn cmp(&self, other: &*mut T) -> Ordering {
2210 } else if self == other {
2218 #[stable(feature = "rust1", since = "1.0.0")]
2219 impl<T: ?Sized> PartialOrd for *mut T {
2221 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2222 Some(self.cmp(other))
2226 fn lt(&self, other: &*mut T) -> bool {
2231 fn le(&self, other: &*mut T) -> bool {
2236 fn gt(&self, other: &*mut T) -> bool {
2241 fn ge(&self, other: &*mut T) -> bool {