2 use crate::cmp::Ordering::{self, Equal, Greater, Less};
3 use crate::intrinsics::{self, const_eval_select};
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 {
37 fn runtime_impl(ptr: *mut u8) -> bool {
42 const fn const_impl(ptr: *mut u8) -> bool {
43 // Compare via a cast to a thin pointer, so fat pointers are only
44 // considering their "data" part for null-ness.
45 match (ptr).guaranteed_eq(null_mut()) {
51 // SAFETY: The two versions are equivalent at runtime.
52 unsafe { const_eval_select((self as *mut u8,), const_impl, runtime_impl) }
55 /// Casts to a pointer of another type.
56 #[stable(feature = "ptr_cast", since = "1.38.0")]
57 #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
59 pub const fn cast<U>(self) -> *mut U {
63 /// Use the pointer value in a new pointer of another type.
65 /// In case `val` is a (fat) pointer to an unsized type, this operation
66 /// will ignore the pointer part, whereas for (thin) pointers to sized
67 /// types, this has the same effect as a simple cast.
69 /// The resulting pointer will have provenance of `self`, i.e., for a fat
70 /// pointer, this operation is semantically the same as creating a new
71 /// fat pointer with the data pointer value of `self` but the metadata of
76 /// This function is primarily useful for allowing byte-wise pointer
77 /// arithmetic on potentially fat pointers:
80 /// #![feature(set_ptr_value)]
81 /// # use core::fmt::Debug;
82 /// let mut arr: [i32; 3] = [1, 2, 3];
83 /// let mut ptr = arr.as_mut_ptr() as *mut dyn Debug;
84 /// let thin = ptr as *mut u8;
86 /// ptr = thin.add(8).with_metadata_of(ptr);
87 /// # assert_eq!(*(ptr as *mut i32), 3);
88 /// println!("{:?}", &*ptr); // will print "3"
91 #[unstable(feature = "set_ptr_value", issue = "75091")]
92 #[rustc_const_unstable(feature = "set_ptr_value", issue = "75091")]
93 #[must_use = "returns a new pointer rather than modifying its argument"]
95 pub const fn with_metadata_of<U>(self, meta: *const U) -> *mut U
99 from_raw_parts_mut::<U>(self as *mut (), metadata(meta))
102 /// Changes constness without changing the type.
104 /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
107 /// While not strictly required (`*mut T` coerces to `*const T`), this is provided for symmetry
108 /// with [`cast_mut`] on `*const T` and may have documentation value if used instead of implicit
111 /// [`cast_mut`]: #method.cast_mut
112 #[stable(feature = "ptr_const_cast", since = "1.65.0")]
113 #[rustc_const_stable(feature = "ptr_const_cast", since = "1.65.0")]
115 pub const fn cast_const(self) -> *const T {
119 /// Casts a pointer to its raw bits.
121 /// This is equivalent to `as usize`, but is more specific to enhance readability.
122 /// The inverse method is [`from_bits`](#method.from_bits-1).
124 /// In particular, `*p as usize` and `p as usize` will both compile for
125 /// pointers to numeric types but do very different things, so using this
126 /// helps emphasize that reading the bits was intentional.
131 /// #![feature(ptr_to_from_bits)]
132 /// # #[cfg(not(miri))] { // doctest does not work with strict provenance
133 /// let mut array = [13, 42];
134 /// let mut it = array.iter_mut();
135 /// let p0: *mut i32 = it.next().unwrap();
136 /// assert_eq!(<*mut _>::from_bits(p0.to_bits()), p0);
137 /// let p1: *mut i32 = it.next().unwrap();
138 /// assert_eq!(p1.to_bits() - p0.to_bits(), 4);
141 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
144 note = "replaced by the `exposed_addr` method, or update your code \
145 to follow the strict provenance rules using its APIs"
148 pub fn to_bits(self) -> usize
155 /// Creates a pointer from its raw bits.
157 /// This is equivalent to `as *mut T`, but is more specific to enhance readability.
158 /// The inverse method is [`to_bits`](#method.to_bits-1).
163 /// #![feature(ptr_to_from_bits)]
164 /// # #[cfg(not(miri))] { // doctest does not work with strict provenance
165 /// use std::ptr::NonNull;
166 /// let dangling: *mut u8 = NonNull::dangling().as_ptr();
167 /// assert_eq!(<*mut u8>::from_bits(1), dangling);
170 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
173 note = "replaced by the `ptr::from_exposed_addr_mut` function, or \
174 update your code to follow the strict provenance rules using its APIs"
176 #[allow(fuzzy_provenance_casts)] // this is an unstable and semi-deprecated cast function
178 pub fn from_bits(bits: usize) -> Self
185 /// Gets the "address" portion of the pointer.
187 /// This is similar to `self as usize`, which semantically discards *provenance* and
188 /// *address-space* information. However, unlike `self as usize`, casting the returned address
189 /// back to a pointer yields [`invalid`][], which is undefined behavior to dereference. To
190 /// properly restore the lost information and obtain a dereferenceable pointer, use
191 /// [`with_addr`][pointer::with_addr] or [`map_addr`][pointer::map_addr].
193 /// If using those APIs is not possible because there is no way to preserve a pointer with the
194 /// required provenance, use [`expose_addr`][pointer::expose_addr] and
195 /// [`from_exposed_addr_mut`][from_exposed_addr_mut] instead. However, note that this makes
196 /// your code less portable and less amenable to tools that check for compliance with the Rust
199 /// On most platforms this will produce a value with the same bytes as the original
200 /// pointer, because all the bytes are dedicated to describing the address.
201 /// Platforms which need to store additional information in the pointer may
202 /// perform a change of representation to produce a value containing only the address
203 /// portion of the pointer. What that means is up to the platform to define.
205 /// This API and its claimed semantics are part of the Strict Provenance experiment, and as such
206 /// might change in the future (including possibly weakening this so it becomes wholly
207 /// equivalent to `self as usize`). See the [module documentation][crate::ptr] for details.
210 #[unstable(feature = "strict_provenance", issue = "95228")]
211 pub fn addr(self) -> usize
215 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
216 // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
218 unsafe { mem::transmute(self) }
221 /// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future
222 /// use in [`from_exposed_addr`][].
224 /// This is equivalent to `self as usize`, which semantically discards *provenance* and
225 /// *address-space* information. Furthermore, this (like the `as` cast) has the implicit
226 /// side-effect of marking the provenance as 'exposed', so on platforms that support it you can
227 /// later call [`from_exposed_addr_mut`][] to reconstitute the original pointer including its
228 /// provenance. (Reconstructing address space information, if required, is your responsibility.)
230 /// Using this method means that code is *not* following Strict Provenance rules. Supporting
231 /// [`from_exposed_addr_mut`][] complicates specification and reasoning and may not be supported
232 /// by tools that help you to stay conformant with the Rust memory model, so it is recommended
233 /// to use [`addr`][pointer::addr] wherever possible.
235 /// On most platforms this will produce a value with the same bytes as the original pointer,
236 /// because all the bytes are dedicated to describing the address. Platforms which need to store
237 /// additional information in the pointer may not support this operation, since the 'expose'
238 /// side-effect which is required for [`from_exposed_addr_mut`][] to work is typically not
241 /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
242 /// [module documentation][crate::ptr] for details.
244 /// [`from_exposed_addr_mut`]: from_exposed_addr_mut
247 #[unstable(feature = "strict_provenance", issue = "95228")]
248 pub fn expose_addr(self) -> usize
252 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
256 /// Creates a new pointer with the given address.
258 /// This performs the same operation as an `addr as ptr` cast, but copies
259 /// the *address-space* and *provenance* of `self` to the new pointer.
260 /// This allows us to dynamically preserve and propagate this important
261 /// information in a way that is otherwise impossible with a unary cast.
263 /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
264 /// `self` to the given address, and therefore has all the same capabilities and restrictions.
266 /// This API and its claimed semantics are part of the Strict Provenance experiment,
267 /// see the [module documentation][crate::ptr] for details.
270 #[unstable(feature = "strict_provenance", issue = "95228")]
271 pub fn with_addr(self, addr: usize) -> Self
275 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
277 // In the mean-time, this operation is defined to be "as if" it was
278 // a wrapping_offset, so we can emulate it as such. This should properly
279 // restore pointer provenance even under today's compiler.
280 let self_addr = self.addr() as isize;
281 let dest_addr = addr as isize;
282 let offset = dest_addr.wrapping_sub(self_addr);
284 // This is the canonical desugarring of this operation
285 self.wrapping_byte_offset(offset)
288 /// Creates a new pointer by mapping `self`'s address to a new one.
290 /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
292 /// This API and its claimed semantics are part of the Strict Provenance experiment,
293 /// see the [module documentation][crate::ptr] for details.
296 #[unstable(feature = "strict_provenance", issue = "95228")]
297 pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self
301 self.with_addr(f(self.addr()))
304 /// Decompose a (possibly wide) pointer into its address and metadata components.
306 /// The pointer can be later reconstructed with [`from_raw_parts_mut`].
307 #[unstable(feature = "ptr_metadata", issue = "81513")]
308 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
310 pub const fn to_raw_parts(self) -> (*mut (), <T as super::Pointee>::Metadata) {
311 (self.cast(), super::metadata(self))
314 /// Returns `None` if the pointer is null, or else returns a shared reference to
315 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
316 /// must be used instead.
318 /// For the mutable counterpart see [`as_mut`].
320 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
321 /// [`as_mut`]: #method.as_mut
325 /// When calling this method, you have to ensure that *either* the pointer is null *or*
326 /// all of the following is true:
328 /// * The pointer must be properly aligned.
330 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
332 /// * The pointer must point to an initialized instance of `T`.
334 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
335 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
336 /// In particular, while this reference exists, the memory the pointer points to must
337 /// not get mutated (except inside `UnsafeCell`).
339 /// This applies even if the result of this method is unused!
340 /// (The part about being initialized is not yet fully decided, but until
341 /// it is, the only safe approach is to ensure that they are indeed initialized.)
343 /// [the module documentation]: crate::ptr#safety
350 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
353 /// if let Some(val_back) = ptr.as_ref() {
354 /// println!("We got back the value: {val_back}!");
359 /// # Null-unchecked version
361 /// If you are sure the pointer can never be null and are looking for some kind of
362 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
363 /// dereference the pointer directly.
366 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
369 /// let val_back = &*ptr;
370 /// println!("We got back the value: {val_back}!");
373 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
374 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
376 pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
377 // SAFETY: the caller must guarantee that `self` is valid for a
378 // reference if it isn't null.
379 if self.is_null() { None } else { unsafe { Some(&*self) } }
382 /// Returns `None` if the pointer is null, or else returns a shared reference to
383 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
384 /// that the value has to be initialized.
386 /// For the mutable counterpart see [`as_uninit_mut`].
388 /// [`as_ref`]: #method.as_ref-1
389 /// [`as_uninit_mut`]: #method.as_uninit_mut
393 /// When calling this method, you have to ensure that *either* the pointer is null *or*
394 /// all of the following is true:
396 /// * The pointer must be properly aligned.
398 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
400 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
401 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
402 /// In particular, while this reference exists, the memory the pointer points to must
403 /// not get mutated (except inside `UnsafeCell`).
405 /// This applies even if the result of this method is unused!
407 /// [the module documentation]: crate::ptr#safety
414 /// #![feature(ptr_as_uninit)]
416 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
419 /// if let Some(val_back) = ptr.as_uninit_ref() {
420 /// println!("We got back the value: {}!", val_back.assume_init());
425 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
426 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
427 pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
431 // SAFETY: the caller must guarantee that `self` meets all the
432 // requirements for a reference.
433 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
436 /// Calculates the offset from a pointer.
438 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
439 /// offset of `3 * size_of::<T>()` bytes.
443 /// If any of the following conditions are violated, the result is Undefined
446 /// * Both the starting and resulting pointer must be either in bounds or one
447 /// byte past the end of the same [allocated object].
449 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
451 /// * The offset being in bounds cannot rely on "wrapping around" the address
452 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
454 /// The compiler and standard library generally tries to ensure allocations
455 /// never reach a size where an offset is a concern. For instance, `Vec`
456 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
457 /// `vec.as_ptr().add(vec.len())` is always safe.
459 /// Most platforms fundamentally can't even construct such an allocation.
460 /// For instance, no known 64-bit platform can ever serve a request
461 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
462 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
463 /// more than `isize::MAX` bytes with things like Physical Address
464 /// Extension. As such, memory acquired directly from allocators or memory
465 /// mapped files *may* be too large to handle with this function.
467 /// Consider using [`wrapping_offset`] instead if these constraints are
468 /// difficult to satisfy. The only advantage of this method is that it
469 /// enables more aggressive compiler optimizations.
471 /// [`wrapping_offset`]: #method.wrapping_offset
472 /// [allocated object]: crate::ptr#allocated-object
479 /// let mut s = [1, 2, 3];
480 /// let ptr: *mut u32 = s.as_mut_ptr();
483 /// println!("{}", *ptr.offset(1));
484 /// println!("{}", *ptr.offset(2));
487 #[stable(feature = "rust1", since = "1.0.0")]
488 #[must_use = "returns a new pointer rather than modifying its argument"]
489 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
491 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
492 pub const unsafe fn offset(self, count: isize) -> *mut T
496 // SAFETY: the caller must uphold the safety contract for `offset`.
497 // The obtained pointer is valid for writes since the caller must
498 // guarantee that it points to the same allocated object as `self`.
499 unsafe { intrinsics::offset(self, count) as *mut T }
502 /// Calculates the offset from a pointer in bytes.
504 /// `count` is in units of **bytes**.
506 /// This is purely a convenience for casting to a `u8` pointer and
507 /// using [offset][pointer::offset] on it. See that method for documentation
508 /// and safety requirements.
510 /// For non-`Sized` pointees this operation changes only the data pointer,
511 /// leaving the metadata untouched.
514 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
515 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
516 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
517 pub const unsafe fn byte_offset(self, count: isize) -> Self {
518 // SAFETY: the caller must uphold the safety contract for `offset`.
519 unsafe { self.cast::<u8>().offset(count).with_metadata_of(self) }
522 /// Calculates the offset from a pointer using wrapping arithmetic.
523 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
524 /// offset of `3 * size_of::<T>()` bytes.
528 /// This operation itself is always safe, but using the resulting pointer is not.
530 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
531 /// be used to read or write other allocated objects.
533 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
534 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
535 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
536 /// `x` and `y` point into the same allocated object.
538 /// Compared to [`offset`], this method basically delays the requirement of staying within the
539 /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
540 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
541 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
542 /// can be optimized better and is thus preferable in performance-sensitive code.
544 /// The delayed check only considers the value of the pointer that was dereferenced, not the
545 /// intermediate values used during the computation of the final result. For example,
546 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
547 /// words, leaving the allocated object and then re-entering it later is permitted.
549 /// [`offset`]: #method.offset
550 /// [allocated object]: crate::ptr#allocated-object
557 /// // Iterate using a raw pointer in increments of two elements
558 /// let mut data = [1u8, 2, 3, 4, 5];
559 /// let mut ptr: *mut u8 = data.as_mut_ptr();
561 /// let end_rounded_up = ptr.wrapping_offset(6);
563 /// while ptr != end_rounded_up {
567 /// ptr = ptr.wrapping_offset(step);
569 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
571 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
572 #[must_use = "returns a new pointer rather than modifying its argument"]
573 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
575 pub const fn wrapping_offset(self, count: isize) -> *mut T
579 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
580 unsafe { intrinsics::arith_offset(self, count) as *mut T }
583 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
585 /// `count` is in units of **bytes**.
587 /// This is purely a convenience for casting to a `u8` pointer and
588 /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
589 /// for documentation.
591 /// For non-`Sized` pointees this operation changes only the data pointer,
592 /// leaving the metadata untouched.
595 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
596 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
597 pub const fn wrapping_byte_offset(self, count: isize) -> Self {
598 self.cast::<u8>().wrapping_offset(count).with_metadata_of(self)
601 /// Masks out bits of the pointer according to a mask.
603 /// This is convenience for `ptr.map_addr(|a| a & mask)`.
605 /// For non-`Sized` pointees this operation changes only the data pointer,
606 /// leaving the metadata untouched.
611 /// #![feature(ptr_mask, strict_provenance)]
612 /// let mut v = 17_u32;
613 /// let ptr: *mut u32 = &mut v;
615 /// // `u32` is 4 bytes aligned,
616 /// // which means that lower 2 bits are always 0.
617 /// let tag_mask = 0b11;
618 /// let ptr_mask = !tag_mask;
620 /// // We can store something in these lower bits
621 /// let tagged_ptr = ptr.map_addr(|a| a | 0b10);
623 /// // Get the "tag" back
624 /// let tag = tagged_ptr.addr() & tag_mask;
625 /// assert_eq!(tag, 0b10);
627 /// // Note that `tagged_ptr` is unaligned, it's UB to read from/write to it.
628 /// // To get original pointer `mask` can be used:
629 /// let masked_ptr = tagged_ptr.mask(ptr_mask);
630 /// assert_eq!(unsafe { *masked_ptr }, 17);
632 /// unsafe { *masked_ptr = 0 };
633 /// assert_eq!(v, 0);
635 #[unstable(feature = "ptr_mask", issue = "98290")]
636 #[must_use = "returns a new pointer rather than modifying its argument"]
638 pub fn mask(self, mask: usize) -> *mut T {
639 intrinsics::ptr_mask(self.cast::<()>(), mask).cast_mut().with_metadata_of(self)
642 /// Returns `None` if the pointer is null, or else returns a unique reference to
643 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
644 /// must be used instead.
646 /// For the shared counterpart see [`as_ref`].
648 /// [`as_uninit_mut`]: #method.as_uninit_mut
649 /// [`as_ref`]: #method.as_ref-1
653 /// When calling this method, you have to ensure that *either* the pointer is null *or*
654 /// all of the following is true:
656 /// * The pointer must be properly aligned.
658 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
660 /// * The pointer must point to an initialized instance of `T`.
662 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
663 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
664 /// In particular, while this reference exists, the memory the pointer points to must
665 /// not get accessed (read or written) through any other pointer.
667 /// This applies even if the result of this method is unused!
668 /// (The part about being initialized is not yet fully decided, but until
669 /// it is, the only safe approach is to ensure that they are indeed initialized.)
671 /// [the module documentation]: crate::ptr#safety
678 /// let mut s = [1, 2, 3];
679 /// let ptr: *mut u32 = s.as_mut_ptr();
680 /// let first_value = unsafe { ptr.as_mut().unwrap() };
681 /// *first_value = 4;
682 /// # assert_eq!(s, [4, 2, 3]);
683 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
686 /// # Null-unchecked version
688 /// If you are sure the pointer can never be null and are looking for some kind of
689 /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
690 /// you can dereference the pointer directly.
693 /// let mut s = [1, 2, 3];
694 /// let ptr: *mut u32 = s.as_mut_ptr();
695 /// let first_value = unsafe { &mut *ptr };
696 /// *first_value = 4;
697 /// # assert_eq!(s, [4, 2, 3]);
698 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
700 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
701 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
703 pub const unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
704 // SAFETY: the caller must guarantee that `self` is be valid for
705 // a mutable reference if it isn't null.
706 if self.is_null() { None } else { unsafe { Some(&mut *self) } }
709 /// Returns `None` if the pointer is null, or else returns a unique reference to
710 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
711 /// that the value has to be initialized.
713 /// For the shared counterpart see [`as_uninit_ref`].
715 /// [`as_mut`]: #method.as_mut
716 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
720 /// When calling this method, you have to ensure that *either* the pointer is null *or*
721 /// all of the following is true:
723 /// * The pointer must be properly aligned.
725 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
727 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
728 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
729 /// In particular, while this reference exists, the memory the pointer points to must
730 /// not get accessed (read or written) through any other pointer.
732 /// This applies even if the result of this method is unused!
734 /// [the module documentation]: crate::ptr#safety
736 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
737 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
738 pub const unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
742 // SAFETY: the caller must guarantee that `self` meets all the
743 // requirements for a reference.
744 if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
747 /// Returns whether two pointers are guaranteed to be equal.
749 /// At runtime this function behaves like `Some(self == other)`.
750 /// However, in some contexts (e.g., compile-time evaluation),
751 /// it is not always possible to determine equality of two pointers, so this function may
752 /// spuriously return `None` for pointers that later actually turn out to have its equality known.
753 /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
755 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
756 /// version and unsafe code must not
757 /// rely on the result of this function for soundness. It is suggested to only use this function
758 /// for performance optimizations where spurious `None` return values by this function do not
759 /// affect the outcome, but just the performance.
760 /// The consequences of using this method to make runtime and compile-time code behave
761 /// differently have not been explored. This method should not be used to introduce such
762 /// differences, and it should also not be stabilized before we have a better understanding
764 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
765 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
767 pub const fn guaranteed_eq(self, other: *mut T) -> Option<bool>
771 (self as *const T).guaranteed_eq(other as _)
774 /// Returns whether two pointers are guaranteed to be inequal.
776 /// At runtime this function behaves like `Some(self != other)`.
777 /// However, in some contexts (e.g., compile-time evaluation),
778 /// it is not always possible to determine inequality of two pointers, so this function may
779 /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
780 /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
782 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
783 /// version and unsafe code must not
784 /// rely on the result of this function for soundness. It is suggested to only use this function
785 /// for performance optimizations where spurious `None` return values by this function do not
786 /// affect the outcome, but just the performance.
787 /// The consequences of using this method to make runtime and compile-time code behave
788 /// differently have not been explored. This method should not be used to introduce such
789 /// differences, and it should also not be stabilized before we have a better understanding
791 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
792 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
794 pub const fn guaranteed_ne(self, other: *mut T) -> Option<bool>
798 (self as *const T).guaranteed_ne(other as _)
801 /// Calculates the distance between two pointers. The returned value is in
802 /// units of T: the distance in bytes divided by `mem::size_of::<T>()`.
804 /// This function is the inverse of [`offset`].
806 /// [`offset`]: #method.offset-1
810 /// If any of the following conditions are violated, the result is Undefined
813 /// * Both the starting and other pointer must be either in bounds or one
814 /// byte past the end of the same [allocated object].
816 /// * Both pointers must be *derived from* a pointer to the same object.
817 /// (See below for an example.)
819 /// * The distance between the pointers, in bytes, must be an exact multiple
820 /// of the size of `T`.
822 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
824 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
826 /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
827 /// address space, so two pointers within some value of any Rust type `T` will always satisfy
828 /// the last two conditions. The standard library also generally ensures that allocations
829 /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
830 /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
831 /// always satisfies the last two conditions.
833 /// Most platforms fundamentally can't even construct such a large allocation.
834 /// For instance, no known 64-bit platform can ever serve a request
835 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
836 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
837 /// more than `isize::MAX` bytes with things like Physical Address
838 /// Extension. As such, memory acquired directly from allocators or memory
839 /// mapped files *may* be too large to handle with this function.
840 /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
841 /// such large allocations either.)
843 /// [`add`]: #method.add
844 /// [allocated object]: crate::ptr#allocated-object
848 /// This function panics if `T` is a Zero-Sized Type ("ZST").
855 /// let mut a = [0; 5];
856 /// let ptr1: *mut i32 = &mut a[1];
857 /// let ptr2: *mut i32 = &mut a[3];
859 /// assert_eq!(ptr2.offset_from(ptr1), 2);
860 /// assert_eq!(ptr1.offset_from(ptr2), -2);
861 /// assert_eq!(ptr1.offset(2), ptr2);
862 /// assert_eq!(ptr2.offset(-2), ptr1);
866 /// *Incorrect* usage:
869 /// let ptr1 = Box::into_raw(Box::new(0u8));
870 /// let ptr2 = Box::into_raw(Box::new(1u8));
871 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
872 /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
873 /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff);
874 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
875 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
876 /// // computing their offset is undefined behavior, even though
877 /// // they point to the same address!
879 /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
882 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
883 #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
885 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
886 pub const unsafe fn offset_from(self, origin: *const T) -> isize
890 // SAFETY: the caller must uphold the safety contract for `offset_from`.
891 unsafe { (self as *const T).offset_from(origin) }
894 /// Calculates the distance between two pointers. The returned value is in
895 /// units of **bytes**.
897 /// This is purely a convenience for casting to a `u8` pointer and
898 /// using [offset_from][pointer::offset_from] on it. See that method for
899 /// documentation and safety requirements.
901 /// For non-`Sized` pointees this operation considers only the data pointers,
902 /// ignoring the metadata.
904 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
905 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
906 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
907 pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: *const U) -> isize {
908 // SAFETY: the caller must uphold the safety contract for `offset_from`.
909 unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
912 /// Calculates the distance between two pointers, *where it's known that
913 /// `self` is equal to or greater than `origin`*. The returned value is in
914 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
916 /// This computes the same value that [`offset_from`](#method.offset_from)
917 /// would compute, but with the added precondition that the offset is
918 /// guaranteed to be non-negative. This method is equivalent to
919 /// `usize::from(self.offset_from(origin)).unwrap_unchecked()`,
920 /// but it provides slightly more information to the optimizer, which can
921 /// sometimes allow it to optimize slightly better with some backends.
923 /// This method can be though of as recovering the `count` that was passed
924 /// to [`add`](#method.add) (or, with the parameters in the other order,
925 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
926 /// that their safety preconditions are met:
928 /// # #![feature(ptr_sub_ptr)]
929 /// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool {
930 /// ptr.sub_ptr(origin) == count
932 /// origin.add(count) == ptr
934 /// ptr.sub(count) == origin
940 /// - The distance between the pointers must be non-negative (`self >= origin`)
942 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
943 /// apply to this method as well; see it for the full details.
945 /// Importantly, despite the return type of this method being able to represent
946 /// a larger offset, it's still *not permitted* to pass pointers which differ
947 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
948 /// always be less than or equal to `isize::MAX as usize`.
952 /// This function panics if `T` is a Zero-Sized Type ("ZST").
957 /// #![feature(ptr_sub_ptr)]
959 /// let mut a = [0; 5];
960 /// let p: *mut i32 = a.as_mut_ptr();
962 /// let ptr1: *mut i32 = p.add(1);
963 /// let ptr2: *mut i32 = p.add(3);
965 /// assert_eq!(ptr2.sub_ptr(ptr1), 2);
966 /// assert_eq!(ptr1.add(2), ptr2);
967 /// assert_eq!(ptr2.sub(2), ptr1);
968 /// assert_eq!(ptr2.sub_ptr(ptr2), 0);
971 /// // This would be incorrect, as the pointers are not correctly ordered:
972 /// // ptr1.offset_from(ptr2)
973 #[unstable(feature = "ptr_sub_ptr", issue = "95892")]
974 #[rustc_const_unstable(feature = "const_ptr_sub_ptr", issue = "95892")]
976 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
977 pub const unsafe fn sub_ptr(self, origin: *const T) -> usize
981 // SAFETY: the caller must uphold the safety contract for `sub_ptr`.
982 unsafe { (self as *const T).sub_ptr(origin) }
985 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
987 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
988 /// offset of `3 * size_of::<T>()` bytes.
992 /// If any of the following conditions are violated, the result is Undefined
995 /// * Both the starting and resulting pointer must be either in bounds or one
996 /// byte past the end of the same [allocated object].
998 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
1000 /// * The offset being in bounds cannot rely on "wrapping around" the address
1001 /// space. That is, the infinite-precision sum must fit in a `usize`.
1003 /// The compiler and standard library generally tries to ensure allocations
1004 /// never reach a size where an offset is a concern. For instance, `Vec`
1005 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1006 /// `vec.as_ptr().add(vec.len())` is always safe.
1008 /// Most platforms fundamentally can't even construct such an allocation.
1009 /// For instance, no known 64-bit platform can ever serve a request
1010 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1011 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1012 /// more than `isize::MAX` bytes with things like Physical Address
1013 /// Extension. As such, memory acquired directly from allocators or memory
1014 /// mapped files *may* be too large to handle with this function.
1016 /// Consider using [`wrapping_add`] instead if these constraints are
1017 /// difficult to satisfy. The only advantage of this method is that it
1018 /// enables more aggressive compiler optimizations.
1020 /// [`wrapping_add`]: #method.wrapping_add
1021 /// [allocated object]: crate::ptr#allocated-object
1028 /// let s: &str = "123";
1029 /// let ptr: *const u8 = s.as_ptr();
1032 /// println!("{}", *ptr.add(1) as char);
1033 /// println!("{}", *ptr.add(2) as char);
1036 #[stable(feature = "pointer_methods", since = "1.26.0")]
1037 #[must_use = "returns a new pointer rather than modifying its argument"]
1038 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1040 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1041 pub const unsafe fn add(self, count: usize) -> Self
1045 // SAFETY: the caller must uphold the safety contract for `offset`.
1046 unsafe { self.offset(count as isize) }
1049 /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
1051 /// `count` is in units of bytes.
1053 /// This is purely a convenience for casting to a `u8` pointer and
1054 /// using [add][pointer::add] on it. See that method for documentation
1055 /// and safety requirements.
1057 /// For non-`Sized` pointees this operation changes only the data pointer,
1058 /// leaving the metadata untouched.
1061 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1062 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1063 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1064 pub const unsafe fn byte_add(self, count: usize) -> Self {
1065 // SAFETY: the caller must uphold the safety contract for `add`.
1066 unsafe { self.cast::<u8>().add(count).with_metadata_of(self) }
1069 /// Calculates the offset from a pointer (convenience for
1070 /// `.offset((count as isize).wrapping_neg())`).
1072 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1073 /// offset of `3 * size_of::<T>()` bytes.
1077 /// If any of the following conditions are violated, the result is Undefined
1080 /// * Both the starting and resulting pointer must be either in bounds or one
1081 /// byte past the end of the same [allocated object].
1083 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1085 /// * The offset being in bounds cannot rely on "wrapping around" the address
1086 /// space. That is, the infinite-precision sum must fit in a usize.
1088 /// The compiler and standard library generally tries to ensure allocations
1089 /// never reach a size where an offset is a concern. For instance, `Vec`
1090 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1091 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1093 /// Most platforms fundamentally can't even construct such an allocation.
1094 /// For instance, no known 64-bit platform can ever serve a request
1095 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1096 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1097 /// more than `isize::MAX` bytes with things like Physical Address
1098 /// Extension. As such, memory acquired directly from allocators or memory
1099 /// mapped files *may* be too large to handle with this function.
1101 /// Consider using [`wrapping_sub`] instead if these constraints are
1102 /// difficult to satisfy. The only advantage of this method is that it
1103 /// enables more aggressive compiler optimizations.
1105 /// [`wrapping_sub`]: #method.wrapping_sub
1106 /// [allocated object]: crate::ptr#allocated-object
1113 /// let s: &str = "123";
1116 /// let end: *const u8 = s.as_ptr().add(3);
1117 /// println!("{}", *end.sub(1) as char);
1118 /// println!("{}", *end.sub(2) as char);
1121 #[stable(feature = "pointer_methods", since = "1.26.0")]
1122 #[must_use = "returns a new pointer rather than modifying its argument"]
1123 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1125 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1126 pub const unsafe fn sub(self, count: usize) -> Self
1130 // SAFETY: the caller must uphold the safety contract for `offset`.
1131 unsafe { self.offset((count as isize).wrapping_neg()) }
1134 /// Calculates the offset from a pointer in bytes (convenience for
1135 /// `.byte_offset((count as isize).wrapping_neg())`).
1137 /// `count` is in units of bytes.
1139 /// This is purely a convenience for casting to a `u8` pointer and
1140 /// using [sub][pointer::sub] on it. See that method for documentation
1141 /// and safety requirements.
1143 /// For non-`Sized` pointees this operation changes only the data pointer,
1144 /// leaving the metadata untouched.
1147 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1148 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1149 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1150 pub const unsafe fn byte_sub(self, count: usize) -> Self {
1151 // SAFETY: the caller must uphold the safety contract for `sub`.
1152 unsafe { self.cast::<u8>().sub(count).with_metadata_of(self) }
1155 /// Calculates the offset from a pointer using wrapping arithmetic.
1156 /// (convenience for `.wrapping_offset(count as isize)`)
1158 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1159 /// offset of `3 * size_of::<T>()` bytes.
1163 /// This operation itself is always safe, but using the resulting pointer is not.
1165 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1166 /// be used to read or write other allocated objects.
1168 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1169 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1170 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1171 /// `x` and `y` point into the same allocated object.
1173 /// Compared to [`add`], this method basically delays the requirement of staying within the
1174 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
1175 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1176 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1177 /// can be optimized better and is thus preferable in performance-sensitive code.
1179 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1180 /// intermediate values used during the computation of the final result. For example,
1181 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1182 /// allocated object and then re-entering it later is permitted.
1184 /// [`add`]: #method.add
1185 /// [allocated object]: crate::ptr#allocated-object
1192 /// // Iterate using a raw pointer in increments of two elements
1193 /// let data = [1u8, 2, 3, 4, 5];
1194 /// let mut ptr: *const u8 = data.as_ptr();
1196 /// let end_rounded_up = ptr.wrapping_add(6);
1198 /// // This loop prints "1, 3, 5, "
1199 /// while ptr != end_rounded_up {
1201 /// print!("{}, ", *ptr);
1203 /// ptr = ptr.wrapping_add(step);
1206 #[stable(feature = "pointer_methods", since = "1.26.0")]
1207 #[must_use = "returns a new pointer rather than modifying its argument"]
1208 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1210 pub const fn wrapping_add(self, count: usize) -> Self
1214 self.wrapping_offset(count as isize)
1217 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1218 /// (convenience for `.wrapping_byte_offset(count as isize)`)
1220 /// `count` is in units of bytes.
1222 /// This is purely a convenience for casting to a `u8` pointer and
1223 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1225 /// For non-`Sized` pointees this operation changes only the data pointer,
1226 /// leaving the metadata untouched.
1229 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1230 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1231 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1232 self.cast::<u8>().wrapping_add(count).with_metadata_of(self)
1235 /// Calculates the offset from a pointer using wrapping arithmetic.
1236 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1238 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1239 /// offset of `3 * size_of::<T>()` bytes.
1243 /// This operation itself is always safe, but using the resulting pointer is not.
1245 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1246 /// be used to read or write other allocated objects.
1248 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1249 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1250 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1251 /// `x` and `y` point into the same allocated object.
1253 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1254 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
1255 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1256 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1257 /// can be optimized better and is thus preferable in performance-sensitive code.
1259 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1260 /// intermediate values used during the computation of the final result. For example,
1261 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1262 /// allocated object and then re-entering it later is permitted.
1264 /// [`sub`]: #method.sub
1265 /// [allocated object]: crate::ptr#allocated-object
1272 /// // Iterate using a raw pointer in increments of two elements (backwards)
1273 /// let data = [1u8, 2, 3, 4, 5];
1274 /// let mut ptr: *const u8 = data.as_ptr();
1275 /// let start_rounded_down = ptr.wrapping_sub(2);
1276 /// ptr = ptr.wrapping_add(4);
1278 /// // This loop prints "5, 3, 1, "
1279 /// while ptr != start_rounded_down {
1281 /// print!("{}, ", *ptr);
1283 /// ptr = ptr.wrapping_sub(step);
1286 #[stable(feature = "pointer_methods", since = "1.26.0")]
1287 #[must_use = "returns a new pointer rather than modifying its argument"]
1288 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1290 pub const fn wrapping_sub(self, count: usize) -> Self
1294 self.wrapping_offset((count as isize).wrapping_neg())
1297 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1298 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1300 /// `count` is in units of bytes.
1302 /// This is purely a convenience for casting to a `u8` pointer and
1303 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1305 /// For non-`Sized` pointees this operation changes only the data pointer,
1306 /// leaving the metadata untouched.
1309 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1310 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1311 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1312 self.cast::<u8>().wrapping_sub(count).with_metadata_of(self)
1315 /// Reads the value from `self` without moving it. This leaves the
1316 /// memory in `self` unchanged.
1318 /// See [`ptr::read`] for safety concerns and examples.
1320 /// [`ptr::read`]: crate::ptr::read()
1321 #[stable(feature = "pointer_methods", since = "1.26.0")]
1322 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1324 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1325 pub const unsafe fn read(self) -> T
1329 // SAFETY: the caller must uphold the safety contract for ``.
1330 unsafe { read(self) }
1333 /// Performs a volatile read of the value from `self` without moving it. This
1334 /// leaves the memory in `self` unchanged.
1336 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1337 /// to not be elided or reordered by the compiler across other volatile
1340 /// See [`ptr::read_volatile`] for safety concerns and examples.
1342 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1343 #[stable(feature = "pointer_methods", since = "1.26.0")]
1345 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1346 pub unsafe fn read_volatile(self) -> T
1350 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1351 unsafe { read_volatile(self) }
1354 /// Reads the value from `self` without moving it. This leaves the
1355 /// memory in `self` unchanged.
1357 /// Unlike `read`, the pointer may be unaligned.
1359 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1361 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1362 #[stable(feature = "pointer_methods", since = "1.26.0")]
1363 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1365 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1366 pub const unsafe fn read_unaligned(self) -> T
1370 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1371 unsafe { read_unaligned(self) }
1374 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1375 /// and destination may overlap.
1377 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1379 /// See [`ptr::copy`] for safety concerns and examples.
1381 /// [`ptr::copy`]: crate::ptr::copy()
1382 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1383 #[stable(feature = "pointer_methods", since = "1.26.0")]
1385 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1386 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1390 // SAFETY: the caller must uphold the safety contract for `copy`.
1391 unsafe { copy(self, dest, count) }
1394 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1395 /// and destination may *not* overlap.
1397 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1399 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1401 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1402 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1403 #[stable(feature = "pointer_methods", since = "1.26.0")]
1405 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1406 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1410 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1411 unsafe { copy_nonoverlapping(self, dest, count) }
1414 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1415 /// and destination may overlap.
1417 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1419 /// See [`ptr::copy`] for safety concerns and examples.
1421 /// [`ptr::copy`]: crate::ptr::copy()
1422 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1423 #[stable(feature = "pointer_methods", since = "1.26.0")]
1425 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1426 pub const unsafe fn copy_from(self, src: *const T, count: usize)
1430 // SAFETY: the caller must uphold the safety contract for `copy`.
1431 unsafe { copy(src, self, count) }
1434 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1435 /// and destination may *not* overlap.
1437 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1439 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1441 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1442 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1443 #[stable(feature = "pointer_methods", since = "1.26.0")]
1445 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1446 pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1450 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1451 unsafe { copy_nonoverlapping(src, self, count) }
1454 /// Executes the destructor (if any) of the pointed-to value.
1456 /// See [`ptr::drop_in_place`] for safety concerns and examples.
1458 /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1459 #[stable(feature = "pointer_methods", since = "1.26.0")]
1461 pub unsafe fn drop_in_place(self) {
1462 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1463 unsafe { drop_in_place(self) }
1466 /// Overwrites a memory location with the given value without reading or
1467 /// dropping the old value.
1469 /// See [`ptr::write`] for safety concerns and examples.
1471 /// [`ptr::write`]: crate::ptr::write()
1472 #[stable(feature = "pointer_methods", since = "1.26.0")]
1473 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1475 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1476 pub const unsafe fn write(self, val: T)
1480 // SAFETY: the caller must uphold the safety contract for `write`.
1481 unsafe { write(self, val) }
1484 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1485 /// bytes of memory starting at `self` to `val`.
1487 /// See [`ptr::write_bytes`] for safety concerns and examples.
1489 /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1490 #[doc(alias = "memset")]
1491 #[stable(feature = "pointer_methods", since = "1.26.0")]
1492 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1494 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1495 pub const unsafe fn write_bytes(self, val: u8, count: usize)
1499 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1500 unsafe { write_bytes(self, val, count) }
1503 /// Performs a volatile write of a memory location with the given value without
1504 /// reading or dropping the old value.
1506 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1507 /// to not be elided or reordered by the compiler across other volatile
1510 /// See [`ptr::write_volatile`] for safety concerns and examples.
1512 /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1513 #[stable(feature = "pointer_methods", since = "1.26.0")]
1515 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1516 pub unsafe fn write_volatile(self, val: T)
1520 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1521 unsafe { write_volatile(self, val) }
1524 /// Overwrites a memory location with the given value without reading or
1525 /// dropping the old value.
1527 /// Unlike `write`, the pointer may be unaligned.
1529 /// See [`ptr::write_unaligned`] for safety concerns and examples.
1531 /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1532 #[stable(feature = "pointer_methods", since = "1.26.0")]
1533 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1535 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1536 pub const unsafe fn write_unaligned(self, val: T)
1540 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1541 unsafe { write_unaligned(self, val) }
1544 /// Replaces the value at `self` with `src`, returning the old
1545 /// value, without dropping either.
1547 /// See [`ptr::replace`] for safety concerns and examples.
1549 /// [`ptr::replace`]: crate::ptr::replace()
1550 #[stable(feature = "pointer_methods", since = "1.26.0")]
1552 pub unsafe fn replace(self, src: T) -> T
1556 // SAFETY: the caller must uphold the safety contract for `replace`.
1557 unsafe { replace(self, src) }
1560 /// Swaps the values at two mutable locations of the same type, without
1561 /// deinitializing either. They may overlap, unlike `mem::swap` which is
1562 /// otherwise equivalent.
1564 /// See [`ptr::swap`] for safety concerns and examples.
1566 /// [`ptr::swap`]: crate::ptr::swap()
1567 #[stable(feature = "pointer_methods", since = "1.26.0")]
1568 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
1570 pub const unsafe fn swap(self, with: *mut T)
1574 // SAFETY: the caller must uphold the safety contract for `swap`.
1575 unsafe { swap(self, with) }
1578 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1581 /// If it is not possible to align the pointer, the implementation returns
1582 /// `usize::MAX`. It is permissible for the implementation to *always*
1583 /// return `usize::MAX`. Only your algorithm's performance can depend
1584 /// on getting a usable offset here, not its correctness.
1586 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1587 /// used with the `wrapping_add` method.
1589 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1590 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1591 /// the returned offset is correct in all terms other than alignment.
1595 /// The function panics if `align` is not a power-of-two.
1599 /// Accessing adjacent `u8` as `u16`
1602 /// use std::mem::align_of;
1605 /// let mut x = [5_u8, 6, 7, 8, 9];
1606 /// let ptr = x.as_mut_ptr();
1607 /// let offset = ptr.align_offset(align_of::<u16>());
1609 /// if offset < x.len() - 1 {
1610 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1613 /// assert!(x == [0, 0, 7, 8, 9] || x == [5, 0, 0, 8, 9]);
1615 /// // while the pointer can be aligned via `offset`, it would point
1616 /// // outside the allocation
1622 #[stable(feature = "align_offset", since = "1.36.0")]
1623 #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1624 pub const fn align_offset(self, align: usize) -> usize
1628 if !align.is_power_of_two() {
1629 panic!("align_offset: align is not a power-of-two");
1633 // SAFETY: `align` has been checked to be a power of 2 above
1634 unsafe { align_offset(self, align) }
1638 /// Returns whether the pointer is properly aligned for `T`.
1644 /// #![feature(pointer_is_aligned)]
1645 /// #![feature(pointer_byte_offsets)]
1647 /// // On some platforms, the alignment of i32 is less than 4.
1648 /// #[repr(align(4))]
1649 /// struct AlignedI32(i32);
1651 /// let mut data = AlignedI32(42);
1652 /// let ptr = &mut data as *mut AlignedI32;
1654 /// assert!(ptr.is_aligned());
1655 /// assert!(!ptr.wrapping_byte_add(1).is_aligned());
1658 /// # At compiletime
1659 /// **Note: Alignment at compiletime is experimental and subject to change. See the
1660 /// [tracking issue] for details.**
1662 /// At compiletime, the compiler may not know where a value will end up in memory.
1663 /// Calling this function on a pointer created from a reference at compiletime will only
1664 /// return `true` if the pointer is guaranteed to be aligned. This means that the pointer
1665 /// is never aligned if cast to a type with a stricter alignment than the reference's
1666 /// underlying allocation.
1669 /// #![feature(pointer_is_aligned)]
1670 /// #![feature(const_pointer_is_aligned)]
1671 /// #![feature(const_mut_refs)]
1673 /// // On some platforms, the alignment of primitives is less than their size.
1674 /// #[repr(align(4))]
1675 /// struct AlignedI32(i32);
1676 /// #[repr(align(8))]
1677 /// struct AlignedI64(i64);
1680 /// let mut data = AlignedI32(42);
1681 /// let ptr = &mut data as *mut AlignedI32;
1682 /// assert!(ptr.is_aligned());
1684 /// // At runtime either `ptr1` or `ptr2` would be aligned, but at compiletime neither is aligned.
1685 /// let ptr1 = ptr.cast::<AlignedI64>();
1686 /// let ptr2 = ptr.wrapping_add(1).cast::<AlignedI64>();
1687 /// assert!(!ptr1.is_aligned());
1688 /// assert!(!ptr2.is_aligned());
1692 /// Due to this behavior, it is possible that a runtime pointer derived from a compiletime
1693 /// pointer is aligned, even if the compiletime pointer wasn't aligned.
1696 /// #![feature(pointer_is_aligned)]
1697 /// #![feature(const_pointer_is_aligned)]
1699 /// // On some platforms, the alignment of primitives is less than their size.
1700 /// #[repr(align(4))]
1701 /// struct AlignedI32(i32);
1702 /// #[repr(align(8))]
1703 /// struct AlignedI64(i64);
1705 /// // At compiletime, neither `COMPTIME_PTR` nor `COMPTIME_PTR + 1` is aligned.
1706 /// // Also, note that mutable references are not allowed in the final value of constants.
1707 /// const COMPTIME_PTR: *mut AlignedI32 = (&AlignedI32(42) as *const AlignedI32).cast_mut();
1708 /// const _: () = assert!(!COMPTIME_PTR.cast::<AlignedI64>().is_aligned());
1709 /// const _: () = assert!(!COMPTIME_PTR.wrapping_add(1).cast::<AlignedI64>().is_aligned());
1711 /// // At runtime, either `runtime_ptr` or `runtime_ptr + 1` is aligned.
1712 /// let runtime_ptr = COMPTIME_PTR;
1714 /// runtime_ptr.cast::<AlignedI64>().is_aligned(),
1715 /// runtime_ptr.wrapping_add(1).cast::<AlignedI64>().is_aligned(),
1719 /// If a pointer is created from a fixed address, this function behaves the same during
1720 /// runtime and compiletime.
1723 /// #![feature(pointer_is_aligned)]
1724 /// #![feature(const_pointer_is_aligned)]
1726 /// // On some platforms, the alignment of primitives is less than their size.
1727 /// #[repr(align(4))]
1728 /// struct AlignedI32(i32);
1729 /// #[repr(align(8))]
1730 /// struct AlignedI64(i64);
1733 /// let ptr = 40 as *mut AlignedI32;
1734 /// assert!(ptr.is_aligned());
1736 /// // For pointers with a known address, runtime and compiletime behavior are identical.
1737 /// let ptr1 = ptr.cast::<AlignedI64>();
1738 /// let ptr2 = ptr.wrapping_add(1).cast::<AlignedI64>();
1739 /// assert!(ptr1.is_aligned());
1740 /// assert!(!ptr2.is_aligned());
1744 /// [tracking issue]: https://github.com/rust-lang/rust/issues/104203
1747 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1748 #[rustc_const_unstable(feature = "const_pointer_is_aligned", issue = "104203")]
1749 pub const fn is_aligned(self) -> bool
1753 self.is_aligned_to(mem::align_of::<T>())
1756 /// Returns whether the pointer is aligned to `align`.
1758 /// For non-`Sized` pointees this operation considers only the data pointer,
1759 /// ignoring the metadata.
1763 /// The function panics if `align` is not a power-of-two (this includes 0).
1769 /// #![feature(pointer_is_aligned)]
1770 /// #![feature(pointer_byte_offsets)]
1772 /// // On some platforms, the alignment of i32 is less than 4.
1773 /// #[repr(align(4))]
1774 /// struct AlignedI32(i32);
1776 /// let mut data = AlignedI32(42);
1777 /// let ptr = &mut data as *mut AlignedI32;
1779 /// assert!(ptr.is_aligned_to(1));
1780 /// assert!(ptr.is_aligned_to(2));
1781 /// assert!(ptr.is_aligned_to(4));
1783 /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1784 /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1786 /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1789 /// # At compiletime
1790 /// **Note: Alignment at compiletime is experimental and subject to change. See the
1791 /// [tracking issue] for details.**
1793 /// At compiletime, the compiler may not know where a value will end up in memory.
1794 /// Calling this function on a pointer created from a reference at compiletime will only
1795 /// return `true` if the pointer is guaranteed to be aligned. This means that the pointer
1796 /// cannot be stricter aligned than the reference's underlying allocation.
1799 /// #![feature(pointer_is_aligned)]
1800 /// #![feature(const_pointer_is_aligned)]
1801 /// #![feature(const_mut_refs)]
1803 /// // On some platforms, the alignment of i32 is less than 4.
1804 /// #[repr(align(4))]
1805 /// struct AlignedI32(i32);
1808 /// let mut data = AlignedI32(42);
1809 /// let ptr = &mut data as *mut AlignedI32;
1811 /// assert!(ptr.is_aligned_to(1));
1812 /// assert!(ptr.is_aligned_to(2));
1813 /// assert!(ptr.is_aligned_to(4));
1815 /// // At compiletime, we know for sure that the pointer isn't aligned to 8.
1816 /// assert!(!ptr.is_aligned_to(8));
1817 /// assert!(!ptr.wrapping_add(1).is_aligned_to(8));
1821 /// Due to this behavior, it is possible that a runtime pointer derived from a compiletime
1822 /// pointer is aligned, even if the compiletime pointer wasn't aligned.
1825 /// #![feature(pointer_is_aligned)]
1826 /// #![feature(const_pointer_is_aligned)]
1828 /// // On some platforms, the alignment of i32 is less than 4.
1829 /// #[repr(align(4))]
1830 /// struct AlignedI32(i32);
1832 /// // At compiletime, neither `COMPTIME_PTR` nor `COMPTIME_PTR + 1` is aligned.
1833 /// // Also, note that mutable references are not allowed in the final value of constants.
1834 /// const COMPTIME_PTR: *mut AlignedI32 = (&AlignedI32(42) as *const AlignedI32).cast_mut();
1835 /// const _: () = assert!(!COMPTIME_PTR.is_aligned_to(8));
1836 /// const _: () = assert!(!COMPTIME_PTR.wrapping_add(1).is_aligned_to(8));
1838 /// // At runtime, either `runtime_ptr` or `runtime_ptr + 1` is aligned.
1839 /// let runtime_ptr = COMPTIME_PTR;
1841 /// runtime_ptr.is_aligned_to(8),
1842 /// runtime_ptr.wrapping_add(1).is_aligned_to(8),
1846 /// If a pointer is created from a fixed address, this function behaves the same during
1847 /// runtime and compiletime.
1850 /// #![feature(pointer_is_aligned)]
1851 /// #![feature(const_pointer_is_aligned)]
1854 /// let ptr = 40 as *mut u8;
1855 /// assert!(ptr.is_aligned_to(1));
1856 /// assert!(ptr.is_aligned_to(2));
1857 /// assert!(ptr.is_aligned_to(4));
1858 /// assert!(ptr.is_aligned_to(8));
1859 /// assert!(!ptr.is_aligned_to(16));
1863 /// [tracking issue]: https://github.com/rust-lang/rust/issues/104203
1866 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1867 #[rustc_const_unstable(feature = "const_pointer_is_aligned", issue = "104203")]
1868 pub const fn is_aligned_to(self, align: usize) -> bool {
1869 if !align.is_power_of_two() {
1870 panic!("is_aligned_to: align is not a power-of-two");
1874 fn runtime_impl(ptr: *mut (), align: usize) -> bool {
1875 ptr.addr() & (align - 1) == 0
1879 const fn const_impl(ptr: *mut (), align: usize) -> bool {
1880 // We can't use the address of `self` in a `const fn`, so we use `align_offset` instead.
1881 // The cast to `()` is used to
1882 // 1. deal with fat pointers; and
1883 // 2. ensure that `align_offset` doesn't actually try to compute an offset.
1884 ptr.align_offset(align) == 0
1887 // SAFETY: The two versions are equivalent at runtime.
1888 unsafe { const_eval_select((self.cast::<()>(), align), const_impl, runtime_impl) }
1893 /// Returns the length of a raw slice.
1895 /// The returned value is the number of **elements**, not the number of bytes.
1897 /// This function is safe, even when the raw slice cannot be cast to a slice
1898 /// reference because the pointer is null or unaligned.
1903 /// #![feature(slice_ptr_len)]
1906 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1907 /// assert_eq!(slice.len(), 3);
1910 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1911 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1912 pub const fn len(self) -> usize {
1916 /// Returns `true` if the raw slice has a length of 0.
1921 /// #![feature(slice_ptr_len)]
1923 /// let mut a = [1, 2, 3];
1924 /// let ptr = &mut a as *mut [_];
1925 /// assert!(!ptr.is_empty());
1928 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1929 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1930 pub const fn is_empty(self) -> bool {
1934 /// Divides one mutable raw slice into two at an index.
1936 /// The first will contain all indices from `[0, mid)` (excluding
1937 /// the index `mid` itself) and the second will contain all
1938 /// indices from `[mid, len)` (excluding the index `len` itself).
1942 /// Panics if `mid > len`.
1946 /// `mid` must be [in-bounds] of the underlying [allocated object].
1947 /// Which means `self` must be dereferenceable and span a single allocation
1948 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1949 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1951 /// Since `len` being in-bounds it is not a safety invariant of `*mut [T]` the
1952 /// safety requirements of this method are the same as for [`split_at_mut_unchecked`].
1953 /// The explicit bounds check is only as useful as `len` is correct.
1955 /// [`split_at_mut_unchecked`]: #method.split_at_mut_unchecked
1956 /// [in-bounds]: #method.add
1957 /// [allocated object]: crate::ptr#allocated-object
1958 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1963 /// #![feature(raw_slice_split)]
1964 /// #![feature(slice_ptr_get)]
1966 /// let mut v = [1, 0, 3, 0, 5, 6];
1967 /// let ptr = &mut v as *mut [_];
1969 /// let (left, right) = ptr.split_at_mut(2);
1970 /// assert_eq!(&*left, [1, 0]);
1971 /// assert_eq!(&*right, [3, 0, 5, 6]);
1976 #[unstable(feature = "raw_slice_split", issue = "95595")]
1977 pub unsafe fn split_at_mut(self, mid: usize) -> (*mut [T], *mut [T]) {
1978 assert!(mid <= self.len());
1979 // SAFETY: The assert above is only a safety-net as long as `self.len()` is correct
1980 // The actual safety requirements of this function are the same as for `split_at_mut_unchecked`
1981 unsafe { self.split_at_mut_unchecked(mid) }
1984 /// Divides one mutable raw slice into two at an index, without doing bounds checking.
1986 /// The first will contain all indices from `[0, mid)` (excluding
1987 /// the index `mid` itself) and the second will contain all
1988 /// indices from `[mid, len)` (excluding the index `len` itself).
1992 /// `mid` must be [in-bounds] of the underlying [allocated object].
1993 /// Which means `self` must be dereferenceable and span a single allocation
1994 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1995 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1997 /// [in-bounds]: #method.add
1998 /// [out-of-bounds index]: #method.add
1999 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2004 /// #![feature(raw_slice_split)]
2006 /// let mut v = [1, 0, 3, 0, 5, 6];
2007 /// // scoped to restrict the lifetime of the borrows
2009 /// let ptr = &mut v as *mut [_];
2010 /// let (left, right) = ptr.split_at_mut_unchecked(2);
2011 /// assert_eq!(&*left, [1, 0]);
2012 /// assert_eq!(&*right, [3, 0, 5, 6]);
2013 /// (&mut *left)[1] = 2;
2014 /// (&mut *right)[1] = 4;
2016 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
2019 #[unstable(feature = "raw_slice_split", issue = "95595")]
2020 pub unsafe fn split_at_mut_unchecked(self, mid: usize) -> (*mut [T], *mut [T]) {
2021 let len = self.len();
2022 let ptr = self.as_mut_ptr();
2024 // SAFETY: Caller must pass a valid pointer and an index that is in-bounds.
2025 let tail = unsafe { ptr.add(mid) };
2027 crate::ptr::slice_from_raw_parts_mut(ptr, mid),
2028 crate::ptr::slice_from_raw_parts_mut(tail, len - mid),
2032 /// Returns a raw pointer to the slice's buffer.
2034 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
2039 /// #![feature(slice_ptr_get)]
2042 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
2043 /// assert_eq!(slice.as_mut_ptr(), ptr::null_mut());
2046 #[unstable(feature = "slice_ptr_get", issue = "74265")]
2047 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
2048 pub const fn as_mut_ptr(self) -> *mut T {
2052 /// Returns a raw pointer to an element or subslice, without doing bounds
2055 /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
2056 /// is *[undefined behavior]* even if the resulting pointer is not used.
2058 /// [out-of-bounds index]: #method.add
2059 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2064 /// #![feature(slice_ptr_get)]
2066 /// let x = &mut [1, 2, 4] as *mut [i32];
2069 /// assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
2072 #[unstable(feature = "slice_ptr_get", issue = "74265")]
2073 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
2075 pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
2077 I: ~const SliceIndex<[T]>,
2079 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
2080 unsafe { index.get_unchecked_mut(self) }
2083 /// Returns `None` if the pointer is null, or else returns a shared slice to
2084 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
2085 /// that the value has to be initialized.
2087 /// For the mutable counterpart see [`as_uninit_slice_mut`].
2089 /// [`as_ref`]: #method.as_ref-1
2090 /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
2094 /// When calling this method, you have to ensure that *either* the pointer is null *or*
2095 /// all of the following is true:
2097 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
2098 /// and it must be properly aligned. This means in particular:
2100 /// * The entire memory range of this slice must be contained within a single [allocated object]!
2101 /// Slices can never span across multiple allocated objects.
2103 /// * The pointer must be aligned even for zero-length slices. One
2104 /// reason for this is that enum layout optimizations may rely on references
2105 /// (including slices of any length) being aligned and non-null to distinguish
2106 /// them from other data. You can obtain a pointer that is usable as `data`
2107 /// for zero-length slices using [`NonNull::dangling()`].
2109 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
2110 /// See the safety documentation of [`pointer::offset`].
2112 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
2113 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
2114 /// In particular, while this reference exists, the memory the pointer points to must
2115 /// not get mutated (except inside `UnsafeCell`).
2117 /// This applies even if the result of this method is unused!
2119 /// See also [`slice::from_raw_parts`][].
2121 /// [valid]: crate::ptr#safety
2122 /// [allocated object]: crate::ptr#allocated-object
2124 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
2125 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
2126 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
2130 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
2131 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
2135 /// Returns `None` if the pointer is null, or else returns a unique slice to
2136 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
2137 /// that the value has to be initialized.
2139 /// For the shared counterpart see [`as_uninit_slice`].
2141 /// [`as_mut`]: #method.as_mut
2142 /// [`as_uninit_slice`]: #method.as_uninit_slice-1
2146 /// When calling this method, you have to ensure that *either* the pointer is null *or*
2147 /// all of the following is true:
2149 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
2150 /// many bytes, and it must be properly aligned. This means in particular:
2152 /// * The entire memory range of this slice must be contained within a single [allocated object]!
2153 /// Slices can never span across multiple allocated objects.
2155 /// * The pointer must be aligned even for zero-length slices. One
2156 /// reason for this is that enum layout optimizations may rely on references
2157 /// (including slices of any length) being aligned and non-null to distinguish
2158 /// them from other data. You can obtain a pointer that is usable as `data`
2159 /// for zero-length slices using [`NonNull::dangling()`].
2161 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
2162 /// See the safety documentation of [`pointer::offset`].
2164 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
2165 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
2166 /// In particular, while this reference exists, the memory the pointer points to must
2167 /// not get accessed (read or written) through any other pointer.
2169 /// This applies even if the result of this method is unused!
2171 /// See also [`slice::from_raw_parts_mut`][].
2173 /// [valid]: crate::ptr#safety
2174 /// [allocated object]: crate::ptr#allocated-object
2176 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
2177 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
2178 pub const unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
2182 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
2183 Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
2188 // Equality for pointers
2189 #[stable(feature = "rust1", since = "1.0.0")]
2190 impl<T: ?Sized> PartialEq for *mut T {
2192 fn eq(&self, other: &*mut T) -> bool {
2197 #[stable(feature = "rust1", since = "1.0.0")]
2198 impl<T: ?Sized> Eq for *mut T {}
2200 #[stable(feature = "rust1", since = "1.0.0")]
2201 impl<T: ?Sized> Ord for *mut T {
2203 fn cmp(&self, other: &*mut T) -> Ordering {
2206 } else if self == other {
2214 #[stable(feature = "rust1", since = "1.0.0")]
2215 impl<T: ?Sized> PartialOrd for *mut T {
2217 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2218 Some(self.cmp(other))
2222 fn lt(&self, other: &*mut T) -> bool {
2227 fn le(&self, other: &*mut T) -> bool {
2232 fn gt(&self, other: &*mut T) -> bool {
2237 fn ge(&self, other: &*mut T) -> bool {