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 {
212 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
213 // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
215 unsafe { mem::transmute(self.cast::<()>()) }
218 /// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future
219 /// use in [`from_exposed_addr`][].
221 /// This is equivalent to `self as usize`, which semantically discards *provenance* and
222 /// *address-space* information. Furthermore, this (like the `as` cast) has the implicit
223 /// side-effect of marking the provenance as 'exposed', so on platforms that support it you can
224 /// later call [`from_exposed_addr_mut`][] to reconstitute the original pointer including its
225 /// provenance. (Reconstructing address space information, if required, is your responsibility.)
227 /// Using this method means that code is *not* following Strict Provenance rules. Supporting
228 /// [`from_exposed_addr_mut`][] complicates specification and reasoning and may not be supported
229 /// by tools that help you to stay conformant with the Rust memory model, so it is recommended
230 /// to use [`addr`][pointer::addr] wherever possible.
232 /// On most platforms this will produce a value with the same bytes as the original pointer,
233 /// because all the bytes are dedicated to describing the address. Platforms which need to store
234 /// additional information in the pointer may not support this operation, since the 'expose'
235 /// side-effect which is required for [`from_exposed_addr_mut`][] to work is typically not
238 /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
239 /// [module documentation][crate::ptr] for details.
241 /// [`from_exposed_addr_mut`]: from_exposed_addr_mut
244 #[unstable(feature = "strict_provenance", issue = "95228")]
245 pub fn expose_addr(self) -> usize {
246 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
247 self.cast::<()>() as usize
250 /// Creates a new pointer with the given address.
252 /// This performs the same operation as an `addr as ptr` cast, but copies
253 /// the *address-space* and *provenance* of `self` to the new pointer.
254 /// This allows us to dynamically preserve and propagate this important
255 /// information in a way that is otherwise impossible with a unary cast.
257 /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
258 /// `self` to the given address, and therefore has all the same capabilities and restrictions.
260 /// This API and its claimed semantics are part of the Strict Provenance experiment,
261 /// see the [module documentation][crate::ptr] for details.
264 #[unstable(feature = "strict_provenance", issue = "95228")]
265 pub fn with_addr(self, addr: usize) -> Self {
266 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
268 // In the mean-time, this operation is defined to be "as if" it was
269 // a wrapping_offset, so we can emulate it as such. This should properly
270 // restore pointer provenance even under today's compiler.
271 let self_addr = self.addr() as isize;
272 let dest_addr = addr as isize;
273 let offset = dest_addr.wrapping_sub(self_addr);
275 // This is the canonical desugarring of this operation
276 self.wrapping_byte_offset(offset)
279 /// Creates a new pointer by mapping `self`'s address to a new one.
281 /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
283 /// This API and its claimed semantics are part of the Strict Provenance experiment,
284 /// see the [module documentation][crate::ptr] for details.
287 #[unstable(feature = "strict_provenance", issue = "95228")]
288 pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self {
289 self.with_addr(f(self.addr()))
292 /// Decompose a (possibly wide) pointer into its address and metadata components.
294 /// The pointer can be later reconstructed with [`from_raw_parts_mut`].
295 #[unstable(feature = "ptr_metadata", issue = "81513")]
296 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
298 pub const fn to_raw_parts(self) -> (*mut (), <T as super::Pointee>::Metadata) {
299 (self.cast(), super::metadata(self))
302 /// Returns `None` if the pointer is null, or else returns a shared reference to
303 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
304 /// must be used instead.
306 /// For the mutable counterpart see [`as_mut`].
308 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
309 /// [`as_mut`]: #method.as_mut
313 /// When calling this method, you have to ensure that *either* the pointer is null *or*
314 /// all of the following is true:
316 /// * The pointer must be properly aligned.
318 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
320 /// * The pointer must point to an initialized instance of `T`.
322 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
323 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
324 /// In particular, while this reference exists, the memory the pointer points to must
325 /// not get mutated (except inside `UnsafeCell`).
327 /// This applies even if the result of this method is unused!
328 /// (The part about being initialized is not yet fully decided, but until
329 /// it is, the only safe approach is to ensure that they are indeed initialized.)
331 /// [the module documentation]: crate::ptr#safety
338 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
341 /// if let Some(val_back) = ptr.as_ref() {
342 /// println!("We got back the value: {val_back}!");
347 /// # Null-unchecked version
349 /// If you are sure the pointer can never be null and are looking for some kind of
350 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
351 /// dereference the pointer directly.
354 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
357 /// let val_back = &*ptr;
358 /// println!("We got back the value: {val_back}!");
361 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
362 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
364 pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
365 // SAFETY: the caller must guarantee that `self` is valid for a
366 // reference if it isn't null.
367 if self.is_null() { None } else { unsafe { Some(&*self) } }
370 /// Returns `None` if the pointer is null, or else returns a shared reference to
371 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
372 /// that the value has to be initialized.
374 /// For the mutable counterpart see [`as_uninit_mut`].
376 /// [`as_ref`]: #method.as_ref-1
377 /// [`as_uninit_mut`]: #method.as_uninit_mut
381 /// When calling this method, you have to ensure that *either* the pointer is null *or*
382 /// all of the following is true:
384 /// * The pointer must be properly aligned.
386 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
388 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
389 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
390 /// In particular, while this reference exists, the memory the pointer points to must
391 /// not get mutated (except inside `UnsafeCell`).
393 /// This applies even if the result of this method is unused!
395 /// [the module documentation]: crate::ptr#safety
402 /// #![feature(ptr_as_uninit)]
404 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
407 /// if let Some(val_back) = ptr.as_uninit_ref() {
408 /// println!("We got back the value: {}!", val_back.assume_init());
413 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
414 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
415 pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
419 // SAFETY: the caller must guarantee that `self` meets all the
420 // requirements for a reference.
421 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
424 /// Calculates the offset from a pointer.
426 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
427 /// offset of `3 * size_of::<T>()` bytes.
431 /// If any of the following conditions are violated, the result is Undefined
434 /// * Both the starting and resulting pointer must be either in bounds or one
435 /// byte past the end of the same [allocated object].
437 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
439 /// * The offset being in bounds cannot rely on "wrapping around" the address
440 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
442 /// The compiler and standard library generally tries to ensure allocations
443 /// never reach a size where an offset is a concern. For instance, `Vec`
444 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
445 /// `vec.as_ptr().add(vec.len())` is always safe.
447 /// Most platforms fundamentally can't even construct such an allocation.
448 /// For instance, no known 64-bit platform can ever serve a request
449 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
450 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
451 /// more than `isize::MAX` bytes with things like Physical Address
452 /// Extension. As such, memory acquired directly from allocators or memory
453 /// mapped files *may* be too large to handle with this function.
455 /// Consider using [`wrapping_offset`] instead if these constraints are
456 /// difficult to satisfy. The only advantage of this method is that it
457 /// enables more aggressive compiler optimizations.
459 /// [`wrapping_offset`]: #method.wrapping_offset
460 /// [allocated object]: crate::ptr#allocated-object
467 /// let mut s = [1, 2, 3];
468 /// let ptr: *mut u32 = s.as_mut_ptr();
471 /// println!("{}", *ptr.offset(1));
472 /// println!("{}", *ptr.offset(2));
475 #[stable(feature = "rust1", since = "1.0.0")]
476 #[must_use = "returns a new pointer rather than modifying its argument"]
477 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
479 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
480 pub const unsafe fn offset(self, count: isize) -> *mut T
484 // SAFETY: the caller must uphold the safety contract for `offset`.
485 // The obtained pointer is valid for writes since the caller must
486 // guarantee that it points to the same allocated object as `self`.
487 unsafe { intrinsics::offset(self, count) as *mut T }
490 /// Calculates the offset from a pointer in bytes.
492 /// `count` is in units of **bytes**.
494 /// This is purely a convenience for casting to a `u8` pointer and
495 /// using [offset][pointer::offset] on it. See that method for documentation
496 /// and safety requirements.
498 /// For non-`Sized` pointees this operation changes only the data pointer,
499 /// leaving the metadata untouched.
502 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
503 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
504 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
505 pub const unsafe fn byte_offset(self, count: isize) -> Self {
506 // SAFETY: the caller must uphold the safety contract for `offset`.
507 unsafe { self.cast::<u8>().offset(count).with_metadata_of(self) }
510 /// Calculates the offset from a pointer using wrapping arithmetic.
511 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
512 /// offset of `3 * size_of::<T>()` bytes.
516 /// This operation itself is always safe, but using the resulting pointer is not.
518 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
519 /// be used to read or write other allocated objects.
521 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
522 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
523 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
524 /// `x` and `y` point into the same allocated object.
526 /// Compared to [`offset`], this method basically delays the requirement of staying within the
527 /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
528 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
529 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
530 /// can be optimized better and is thus preferable in performance-sensitive code.
532 /// The delayed check only considers the value of the pointer that was dereferenced, not the
533 /// intermediate values used during the computation of the final result. For example,
534 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
535 /// words, leaving the allocated object and then re-entering it later is permitted.
537 /// [`offset`]: #method.offset
538 /// [allocated object]: crate::ptr#allocated-object
545 /// // Iterate using a raw pointer in increments of two elements
546 /// let mut data = [1u8, 2, 3, 4, 5];
547 /// let mut ptr: *mut u8 = data.as_mut_ptr();
549 /// let end_rounded_up = ptr.wrapping_offset(6);
551 /// while ptr != end_rounded_up {
555 /// ptr = ptr.wrapping_offset(step);
557 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
559 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
560 #[must_use = "returns a new pointer rather than modifying its argument"]
561 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
563 pub const fn wrapping_offset(self, count: isize) -> *mut T
567 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
568 unsafe { intrinsics::arith_offset(self, count) as *mut T }
571 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
573 /// `count` is in units of **bytes**.
575 /// This is purely a convenience for casting to a `u8` pointer and
576 /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
577 /// for documentation.
579 /// For non-`Sized` pointees this operation changes only the data pointer,
580 /// leaving the metadata untouched.
583 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
584 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
585 pub const fn wrapping_byte_offset(self, count: isize) -> Self {
586 self.cast::<u8>().wrapping_offset(count).with_metadata_of(self)
589 /// Masks out bits of the pointer according to a mask.
591 /// This is convenience for `ptr.map_addr(|a| a & mask)`.
593 /// For non-`Sized` pointees this operation changes only the data pointer,
594 /// leaving the metadata untouched.
599 /// #![feature(ptr_mask, strict_provenance)]
600 /// let mut v = 17_u32;
601 /// let ptr: *mut u32 = &mut v;
603 /// // `u32` is 4 bytes aligned,
604 /// // which means that lower 2 bits are always 0.
605 /// let tag_mask = 0b11;
606 /// let ptr_mask = !tag_mask;
608 /// // We can store something in these lower bits
609 /// let tagged_ptr = ptr.map_addr(|a| a | 0b10);
611 /// // Get the "tag" back
612 /// let tag = tagged_ptr.addr() & tag_mask;
613 /// assert_eq!(tag, 0b10);
615 /// // Note that `tagged_ptr` is unaligned, it's UB to read from/write to it.
616 /// // To get original pointer `mask` can be used:
617 /// let masked_ptr = tagged_ptr.mask(ptr_mask);
618 /// assert_eq!(unsafe { *masked_ptr }, 17);
620 /// unsafe { *masked_ptr = 0 };
621 /// assert_eq!(v, 0);
623 #[unstable(feature = "ptr_mask", issue = "98290")]
624 #[must_use = "returns a new pointer rather than modifying its argument"]
626 pub fn mask(self, mask: usize) -> *mut T {
627 intrinsics::ptr_mask(self.cast::<()>(), mask).cast_mut().with_metadata_of(self)
630 /// Returns `None` if the pointer is null, or else returns a unique reference to
631 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
632 /// must be used instead.
634 /// For the shared counterpart see [`as_ref`].
636 /// [`as_uninit_mut`]: #method.as_uninit_mut
637 /// [`as_ref`]: #method.as_ref-1
641 /// When calling this method, you have to ensure that *either* the pointer is null *or*
642 /// all of the following is true:
644 /// * The pointer must be properly aligned.
646 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
648 /// * The pointer must point to an initialized instance of `T`.
650 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
651 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
652 /// In particular, while this reference exists, the memory the pointer points to must
653 /// not get accessed (read or written) through any other pointer.
655 /// This applies even if the result of this method is unused!
656 /// (The part about being initialized is not yet fully decided, but until
657 /// it is, the only safe approach is to ensure that they are indeed initialized.)
659 /// [the module documentation]: crate::ptr#safety
666 /// let mut s = [1, 2, 3];
667 /// let ptr: *mut u32 = s.as_mut_ptr();
668 /// let first_value = unsafe { ptr.as_mut().unwrap() };
669 /// *first_value = 4;
670 /// # assert_eq!(s, [4, 2, 3]);
671 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
674 /// # Null-unchecked version
676 /// If you are sure the pointer can never be null and are looking for some kind of
677 /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
678 /// you can dereference the pointer directly.
681 /// let mut s = [1, 2, 3];
682 /// let ptr: *mut u32 = s.as_mut_ptr();
683 /// let first_value = unsafe { &mut *ptr };
684 /// *first_value = 4;
685 /// # assert_eq!(s, [4, 2, 3]);
686 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
688 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
689 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
691 pub const unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
692 // SAFETY: the caller must guarantee that `self` is be valid for
693 // a mutable reference if it isn't null.
694 if self.is_null() { None } else { unsafe { Some(&mut *self) } }
697 /// Returns `None` if the pointer is null, or else returns a unique reference to
698 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
699 /// that the value has to be initialized.
701 /// For the shared counterpart see [`as_uninit_ref`].
703 /// [`as_mut`]: #method.as_mut
704 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
708 /// When calling this method, you have to ensure that *either* the pointer is null *or*
709 /// all of the following is true:
711 /// * The pointer must be properly aligned.
713 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
715 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
716 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
717 /// In particular, while this reference exists, the memory the pointer points to must
718 /// not get accessed (read or written) through any other pointer.
720 /// This applies even if the result of this method is unused!
722 /// [the module documentation]: crate::ptr#safety
724 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
725 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
726 pub const unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
730 // SAFETY: the caller must guarantee that `self` meets all the
731 // requirements for a reference.
732 if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
735 /// Returns whether two pointers are guaranteed to be equal.
737 /// At runtime this function behaves like `Some(self == other)`.
738 /// However, in some contexts (e.g., compile-time evaluation),
739 /// it is not always possible to determine equality of two pointers, so this function may
740 /// spuriously return `None` for pointers that later actually turn out to have its equality known.
741 /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
743 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
744 /// version and unsafe code must not
745 /// rely on the result of this function for soundness. It is suggested to only use this function
746 /// for performance optimizations where spurious `None` return values by this function do not
747 /// affect the outcome, but just the performance.
748 /// The consequences of using this method to make runtime and compile-time code behave
749 /// differently have not been explored. This method should not be used to introduce such
750 /// differences, and it should also not be stabilized before we have a better understanding
752 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
753 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
755 pub const fn guaranteed_eq(self, other: *mut T) -> Option<bool>
759 (self as *const T).guaranteed_eq(other as _)
762 /// Returns whether two pointers are guaranteed to be inequal.
764 /// At runtime this function behaves like `Some(self != other)`.
765 /// However, in some contexts (e.g., compile-time evaluation),
766 /// it is not always possible to determine inequality of two pointers, so this function may
767 /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
768 /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
770 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
771 /// version and unsafe code must not
772 /// rely on the result of this function for soundness. It is suggested to only use this function
773 /// for performance optimizations where spurious `None` return values by this function do not
774 /// affect the outcome, but just the performance.
775 /// The consequences of using this method to make runtime and compile-time code behave
776 /// differently have not been explored. This method should not be used to introduce such
777 /// differences, and it should also not be stabilized before we have a better understanding
779 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
780 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
782 pub const fn guaranteed_ne(self, other: *mut T) -> Option<bool>
786 (self as *const T).guaranteed_ne(other as _)
789 /// Calculates the distance between two pointers. The returned value is in
790 /// units of T: the distance in bytes divided by `mem::size_of::<T>()`.
792 /// This function is the inverse of [`offset`].
794 /// [`offset`]: #method.offset-1
798 /// If any of the following conditions are violated, the result is Undefined
801 /// * Both the starting and other pointer must be either in bounds or one
802 /// byte past the end of the same [allocated object].
804 /// * Both pointers must be *derived from* a pointer to the same object.
805 /// (See below for an example.)
807 /// * The distance between the pointers, in bytes, must be an exact multiple
808 /// of the size of `T`.
810 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
812 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
814 /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
815 /// address space, so two pointers within some value of any Rust type `T` will always satisfy
816 /// the last two conditions. The standard library also generally ensures that allocations
817 /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
818 /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
819 /// always satisfies the last two conditions.
821 /// Most platforms fundamentally can't even construct such a large allocation.
822 /// For instance, no known 64-bit platform can ever serve a request
823 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
824 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
825 /// more than `isize::MAX` bytes with things like Physical Address
826 /// Extension. As such, memory acquired directly from allocators or memory
827 /// mapped files *may* be too large to handle with this function.
828 /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
829 /// such large allocations either.)
831 /// [`add`]: #method.add
832 /// [allocated object]: crate::ptr#allocated-object
836 /// This function panics if `T` is a Zero-Sized Type ("ZST").
843 /// let mut a = [0; 5];
844 /// let ptr1: *mut i32 = &mut a[1];
845 /// let ptr2: *mut i32 = &mut a[3];
847 /// assert_eq!(ptr2.offset_from(ptr1), 2);
848 /// assert_eq!(ptr1.offset_from(ptr2), -2);
849 /// assert_eq!(ptr1.offset(2), ptr2);
850 /// assert_eq!(ptr2.offset(-2), ptr1);
854 /// *Incorrect* usage:
857 /// let ptr1 = Box::into_raw(Box::new(0u8));
858 /// let ptr2 = Box::into_raw(Box::new(1u8));
859 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
860 /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
861 /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff);
862 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
863 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
864 /// // computing their offset is undefined behavior, even though
865 /// // they point to the same address!
867 /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
870 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
871 #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
873 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
874 pub const unsafe fn offset_from(self, origin: *const T) -> isize
878 // SAFETY: the caller must uphold the safety contract for `offset_from`.
879 unsafe { (self as *const T).offset_from(origin) }
882 /// Calculates the distance between two pointers. The returned value is in
883 /// units of **bytes**.
885 /// This is purely a convenience for casting to a `u8` pointer and
886 /// using [offset_from][pointer::offset_from] on it. See that method for
887 /// documentation and safety requirements.
889 /// For non-`Sized` pointees this operation considers only the data pointers,
890 /// ignoring the metadata.
892 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
893 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
894 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
895 pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: *const U) -> isize {
896 // SAFETY: the caller must uphold the safety contract for `offset_from`.
897 unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
900 /// Calculates the distance between two pointers, *where it's known that
901 /// `self` is equal to or greater than `origin`*. The returned value is in
902 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
904 /// This computes the same value that [`offset_from`](#method.offset_from)
905 /// would compute, but with the added precondition that the offset is
906 /// guaranteed to be non-negative. This method is equivalent to
907 /// `usize::from(self.offset_from(origin)).unwrap_unchecked()`,
908 /// but it provides slightly more information to the optimizer, which can
909 /// sometimes allow it to optimize slightly better with some backends.
911 /// This method can be though of as recovering the `count` that was passed
912 /// to [`add`](#method.add) (or, with the parameters in the other order,
913 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
914 /// that their safety preconditions are met:
916 /// # #![feature(ptr_sub_ptr)]
917 /// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool {
918 /// ptr.sub_ptr(origin) == count
920 /// origin.add(count) == ptr
922 /// ptr.sub(count) == origin
928 /// - The distance between the pointers must be non-negative (`self >= origin`)
930 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
931 /// apply to this method as well; see it for the full details.
933 /// Importantly, despite the return type of this method being able to represent
934 /// a larger offset, it's still *not permitted* to pass pointers which differ
935 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
936 /// always be less than or equal to `isize::MAX as usize`.
940 /// This function panics if `T` is a Zero-Sized Type ("ZST").
945 /// #![feature(ptr_sub_ptr)]
947 /// let mut a = [0; 5];
948 /// let p: *mut i32 = a.as_mut_ptr();
950 /// let ptr1: *mut i32 = p.add(1);
951 /// let ptr2: *mut i32 = p.add(3);
953 /// assert_eq!(ptr2.sub_ptr(ptr1), 2);
954 /// assert_eq!(ptr1.add(2), ptr2);
955 /// assert_eq!(ptr2.sub(2), ptr1);
956 /// assert_eq!(ptr2.sub_ptr(ptr2), 0);
959 /// // This would be incorrect, as the pointers are not correctly ordered:
960 /// // ptr1.offset_from(ptr2)
961 #[unstable(feature = "ptr_sub_ptr", issue = "95892")]
962 #[rustc_const_unstable(feature = "const_ptr_sub_ptr", issue = "95892")]
964 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
965 pub const unsafe fn sub_ptr(self, origin: *const T) -> usize
969 // SAFETY: the caller must uphold the safety contract for `sub_ptr`.
970 unsafe { (self as *const T).sub_ptr(origin) }
973 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
975 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
976 /// offset of `3 * size_of::<T>()` bytes.
980 /// If any of the following conditions are violated, the result is Undefined
983 /// * Both the starting and resulting pointer must be either in bounds or one
984 /// byte past the end of the same [allocated object].
986 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
988 /// * The offset being in bounds cannot rely on "wrapping around" the address
989 /// space. That is, the infinite-precision sum must fit in a `usize`.
991 /// The compiler and standard library generally tries to ensure allocations
992 /// never reach a size where an offset is a concern. For instance, `Vec`
993 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
994 /// `vec.as_ptr().add(vec.len())` is always safe.
996 /// Most platforms fundamentally can't even construct such an allocation.
997 /// For instance, no known 64-bit platform can ever serve a request
998 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
999 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1000 /// more than `isize::MAX` bytes with things like Physical Address
1001 /// Extension. As such, memory acquired directly from allocators or memory
1002 /// mapped files *may* be too large to handle with this function.
1004 /// Consider using [`wrapping_add`] instead if these constraints are
1005 /// difficult to satisfy. The only advantage of this method is that it
1006 /// enables more aggressive compiler optimizations.
1008 /// [`wrapping_add`]: #method.wrapping_add
1009 /// [allocated object]: crate::ptr#allocated-object
1016 /// let s: &str = "123";
1017 /// let ptr: *const u8 = s.as_ptr();
1020 /// println!("{}", *ptr.add(1) as char);
1021 /// println!("{}", *ptr.add(2) as char);
1024 #[stable(feature = "pointer_methods", since = "1.26.0")]
1025 #[must_use = "returns a new pointer rather than modifying its argument"]
1026 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1028 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1029 pub const unsafe fn add(self, count: usize) -> Self
1033 // SAFETY: the caller must uphold the safety contract for `offset`.
1034 unsafe { self.offset(count as isize) }
1037 /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
1039 /// `count` is in units of bytes.
1041 /// This is purely a convenience for casting to a `u8` pointer and
1042 /// using [add][pointer::add] on it. See that method for documentation
1043 /// and safety requirements.
1045 /// For non-`Sized` pointees this operation changes only the data pointer,
1046 /// leaving the metadata untouched.
1049 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1050 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1051 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1052 pub const unsafe fn byte_add(self, count: usize) -> Self {
1053 // SAFETY: the caller must uphold the safety contract for `add`.
1054 unsafe { self.cast::<u8>().add(count).with_metadata_of(self) }
1057 /// Calculates the offset from a pointer (convenience for
1058 /// `.offset((count as isize).wrapping_neg())`).
1060 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1061 /// offset of `3 * size_of::<T>()` bytes.
1065 /// If any of the following conditions are violated, the result is Undefined
1068 /// * Both the starting and resulting pointer must be either in bounds or one
1069 /// byte past the end of the same [allocated object].
1071 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1073 /// * The offset being in bounds cannot rely on "wrapping around" the address
1074 /// space. That is, the infinite-precision sum must fit in a usize.
1076 /// The compiler and standard library generally tries to ensure allocations
1077 /// never reach a size where an offset is a concern. For instance, `Vec`
1078 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1079 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1081 /// Most platforms fundamentally can't even construct such an allocation.
1082 /// For instance, no known 64-bit platform can ever serve a request
1083 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1084 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1085 /// more than `isize::MAX` bytes with things like Physical Address
1086 /// Extension. As such, memory acquired directly from allocators or memory
1087 /// mapped files *may* be too large to handle with this function.
1089 /// Consider using [`wrapping_sub`] instead if these constraints are
1090 /// difficult to satisfy. The only advantage of this method is that it
1091 /// enables more aggressive compiler optimizations.
1093 /// [`wrapping_sub`]: #method.wrapping_sub
1094 /// [allocated object]: crate::ptr#allocated-object
1101 /// let s: &str = "123";
1104 /// let end: *const u8 = s.as_ptr().add(3);
1105 /// println!("{}", *end.sub(1) as char);
1106 /// println!("{}", *end.sub(2) as char);
1109 #[stable(feature = "pointer_methods", since = "1.26.0")]
1110 #[must_use = "returns a new pointer rather than modifying its argument"]
1111 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1113 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1114 pub const unsafe fn sub(self, count: usize) -> Self
1118 // SAFETY: the caller must uphold the safety contract for `offset`.
1119 unsafe { self.offset((count as isize).wrapping_neg()) }
1122 /// Calculates the offset from a pointer in bytes (convenience for
1123 /// `.byte_offset((count as isize).wrapping_neg())`).
1125 /// `count` is in units of bytes.
1127 /// This is purely a convenience for casting to a `u8` pointer and
1128 /// using [sub][pointer::sub] on it. See that method for documentation
1129 /// and safety requirements.
1131 /// For non-`Sized` pointees this operation changes only the data pointer,
1132 /// leaving the metadata untouched.
1135 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1136 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1137 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1138 pub const unsafe fn byte_sub(self, count: usize) -> Self {
1139 // SAFETY: the caller must uphold the safety contract for `sub`.
1140 unsafe { self.cast::<u8>().sub(count).with_metadata_of(self) }
1143 /// Calculates the offset from a pointer using wrapping arithmetic.
1144 /// (convenience for `.wrapping_offset(count as isize)`)
1146 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1147 /// offset of `3 * size_of::<T>()` bytes.
1151 /// This operation itself is always safe, but using the resulting pointer is not.
1153 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1154 /// be used to read or write other allocated objects.
1156 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1157 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1158 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1159 /// `x` and `y` point into the same allocated object.
1161 /// Compared to [`add`], this method basically delays the requirement of staying within the
1162 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
1163 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1164 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1165 /// can be optimized better and is thus preferable in performance-sensitive code.
1167 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1168 /// intermediate values used during the computation of the final result. For example,
1169 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1170 /// allocated object and then re-entering it later is permitted.
1172 /// [`add`]: #method.add
1173 /// [allocated object]: crate::ptr#allocated-object
1180 /// // Iterate using a raw pointer in increments of two elements
1181 /// let data = [1u8, 2, 3, 4, 5];
1182 /// let mut ptr: *const u8 = data.as_ptr();
1184 /// let end_rounded_up = ptr.wrapping_add(6);
1186 /// // This loop prints "1, 3, 5, "
1187 /// while ptr != end_rounded_up {
1189 /// print!("{}, ", *ptr);
1191 /// ptr = ptr.wrapping_add(step);
1194 #[stable(feature = "pointer_methods", since = "1.26.0")]
1195 #[must_use = "returns a new pointer rather than modifying its argument"]
1196 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1198 pub const fn wrapping_add(self, count: usize) -> Self
1202 self.wrapping_offset(count as isize)
1205 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1206 /// (convenience for `.wrapping_byte_offset(count as isize)`)
1208 /// `count` is in units of bytes.
1210 /// This is purely a convenience for casting to a `u8` pointer and
1211 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1213 /// For non-`Sized` pointees this operation changes only the data pointer,
1214 /// leaving the metadata untouched.
1217 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1218 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1219 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1220 self.cast::<u8>().wrapping_add(count).with_metadata_of(self)
1223 /// Calculates the offset from a pointer using wrapping arithmetic.
1224 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1226 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1227 /// offset of `3 * size_of::<T>()` bytes.
1231 /// This operation itself is always safe, but using the resulting pointer is not.
1233 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1234 /// be used to read or write other allocated objects.
1236 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1237 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1238 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1239 /// `x` and `y` point into the same allocated object.
1241 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1242 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
1243 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1244 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1245 /// can be optimized better and is thus preferable in performance-sensitive code.
1247 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1248 /// intermediate values used during the computation of the final result. For example,
1249 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1250 /// allocated object and then re-entering it later is permitted.
1252 /// [`sub`]: #method.sub
1253 /// [allocated object]: crate::ptr#allocated-object
1260 /// // Iterate using a raw pointer in increments of two elements (backwards)
1261 /// let data = [1u8, 2, 3, 4, 5];
1262 /// let mut ptr: *const u8 = data.as_ptr();
1263 /// let start_rounded_down = ptr.wrapping_sub(2);
1264 /// ptr = ptr.wrapping_add(4);
1266 /// // This loop prints "5, 3, 1, "
1267 /// while ptr != start_rounded_down {
1269 /// print!("{}, ", *ptr);
1271 /// ptr = ptr.wrapping_sub(step);
1274 #[stable(feature = "pointer_methods", since = "1.26.0")]
1275 #[must_use = "returns a new pointer rather than modifying its argument"]
1276 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1278 pub const fn wrapping_sub(self, count: usize) -> Self
1282 self.wrapping_offset((count as isize).wrapping_neg())
1285 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1286 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1288 /// `count` is in units of bytes.
1290 /// This is purely a convenience for casting to a `u8` pointer and
1291 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1293 /// For non-`Sized` pointees this operation changes only the data pointer,
1294 /// leaving the metadata untouched.
1297 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1298 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1299 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1300 self.cast::<u8>().wrapping_sub(count).with_metadata_of(self)
1303 /// Reads the value from `self` without moving it. This leaves the
1304 /// memory in `self` unchanged.
1306 /// See [`ptr::read`] for safety concerns and examples.
1308 /// [`ptr::read`]: crate::ptr::read()
1309 #[stable(feature = "pointer_methods", since = "1.26.0")]
1310 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1312 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1313 pub const unsafe fn read(self) -> T
1317 // SAFETY: the caller must uphold the safety contract for ``.
1318 unsafe { read(self) }
1321 /// Performs a volatile read of the value from `self` without moving it. This
1322 /// leaves the memory in `self` unchanged.
1324 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1325 /// to not be elided or reordered by the compiler across other volatile
1328 /// See [`ptr::read_volatile`] for safety concerns and examples.
1330 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1331 #[stable(feature = "pointer_methods", since = "1.26.0")]
1333 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1334 pub unsafe fn read_volatile(self) -> T
1338 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1339 unsafe { read_volatile(self) }
1342 /// Reads the value from `self` without moving it. This leaves the
1343 /// memory in `self` unchanged.
1345 /// Unlike `read`, the pointer may be unaligned.
1347 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1349 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1350 #[stable(feature = "pointer_methods", since = "1.26.0")]
1351 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1353 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1354 pub const unsafe fn read_unaligned(self) -> T
1358 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1359 unsafe { read_unaligned(self) }
1362 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1363 /// and destination may overlap.
1365 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1367 /// See [`ptr::copy`] for safety concerns and examples.
1369 /// [`ptr::copy`]: crate::ptr::copy()
1370 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1371 #[stable(feature = "pointer_methods", since = "1.26.0")]
1373 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1374 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1378 // SAFETY: the caller must uphold the safety contract for `copy`.
1379 unsafe { copy(self, dest, count) }
1382 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1383 /// and destination may *not* overlap.
1385 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1387 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1389 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1390 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1391 #[stable(feature = "pointer_methods", since = "1.26.0")]
1393 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1394 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1398 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1399 unsafe { copy_nonoverlapping(self, dest, count) }
1402 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1403 /// and destination may overlap.
1405 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1407 /// See [`ptr::copy`] for safety concerns and examples.
1409 /// [`ptr::copy`]: crate::ptr::copy()
1410 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1411 #[stable(feature = "pointer_methods", since = "1.26.0")]
1413 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1414 pub const unsafe fn copy_from(self, src: *const T, count: usize)
1418 // SAFETY: the caller must uphold the safety contract for `copy`.
1419 unsafe { copy(src, self, count) }
1422 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1423 /// and destination may *not* overlap.
1425 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1427 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1429 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1430 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1431 #[stable(feature = "pointer_methods", since = "1.26.0")]
1433 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1434 pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1438 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1439 unsafe { copy_nonoverlapping(src, self, count) }
1442 /// Executes the destructor (if any) of the pointed-to value.
1444 /// See [`ptr::drop_in_place`] for safety concerns and examples.
1446 /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1447 #[stable(feature = "pointer_methods", since = "1.26.0")]
1449 pub unsafe fn drop_in_place(self) {
1450 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1451 unsafe { drop_in_place(self) }
1454 /// Overwrites a memory location with the given value without reading or
1455 /// dropping the old value.
1457 /// See [`ptr::write`] for safety concerns and examples.
1459 /// [`ptr::write`]: crate::ptr::write()
1460 #[stable(feature = "pointer_methods", since = "1.26.0")]
1461 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1463 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1464 pub const unsafe fn write(self, val: T)
1468 // SAFETY: the caller must uphold the safety contract for `write`.
1469 unsafe { write(self, val) }
1472 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1473 /// bytes of memory starting at `self` to `val`.
1475 /// See [`ptr::write_bytes`] for safety concerns and examples.
1477 /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1478 #[doc(alias = "memset")]
1479 #[stable(feature = "pointer_methods", since = "1.26.0")]
1480 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1482 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1483 pub const unsafe fn write_bytes(self, val: u8, count: usize)
1487 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1488 unsafe { write_bytes(self, val, count) }
1491 /// Performs a volatile write of a memory location with the given value without
1492 /// reading or dropping the old value.
1494 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1495 /// to not be elided or reordered by the compiler across other volatile
1498 /// See [`ptr::write_volatile`] for safety concerns and examples.
1500 /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1501 #[stable(feature = "pointer_methods", since = "1.26.0")]
1503 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1504 pub unsafe fn write_volatile(self, val: T)
1508 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1509 unsafe { write_volatile(self, val) }
1512 /// Overwrites a memory location with the given value without reading or
1513 /// dropping the old value.
1515 /// Unlike `write`, the pointer may be unaligned.
1517 /// See [`ptr::write_unaligned`] for safety concerns and examples.
1519 /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1520 #[stable(feature = "pointer_methods", since = "1.26.0")]
1521 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1523 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1524 pub const unsafe fn write_unaligned(self, val: T)
1528 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1529 unsafe { write_unaligned(self, val) }
1532 /// Replaces the value at `self` with `src`, returning the old
1533 /// value, without dropping either.
1535 /// See [`ptr::replace`] for safety concerns and examples.
1537 /// [`ptr::replace`]: crate::ptr::replace()
1538 #[stable(feature = "pointer_methods", since = "1.26.0")]
1540 pub unsafe fn replace(self, src: T) -> T
1544 // SAFETY: the caller must uphold the safety contract for `replace`.
1545 unsafe { replace(self, src) }
1548 /// Swaps the values at two mutable locations of the same type, without
1549 /// deinitializing either. They may overlap, unlike `mem::swap` which is
1550 /// otherwise equivalent.
1552 /// See [`ptr::swap`] for safety concerns and examples.
1554 /// [`ptr::swap`]: crate::ptr::swap()
1555 #[stable(feature = "pointer_methods", since = "1.26.0")]
1556 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
1558 pub const unsafe fn swap(self, with: *mut T)
1562 // SAFETY: the caller must uphold the safety contract for `swap`.
1563 unsafe { swap(self, with) }
1566 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1569 /// If it is not possible to align the pointer, the implementation returns
1570 /// `usize::MAX`. It is permissible for the implementation to *always*
1571 /// return `usize::MAX`. Only your algorithm's performance can depend
1572 /// on getting a usable offset here, not its correctness.
1574 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1575 /// used with the `wrapping_add` method.
1577 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1578 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1579 /// the returned offset is correct in all terms other than alignment.
1583 /// The function panics if `align` is not a power-of-two.
1587 /// Accessing adjacent `u8` as `u16`
1590 /// use std::mem::align_of;
1593 /// let mut x = [5_u8, 6, 7, 8, 9];
1594 /// let ptr = x.as_mut_ptr();
1595 /// let offset = ptr.align_offset(align_of::<u16>());
1597 /// if offset < x.len() - 1 {
1598 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1601 /// assert!(x == [0, 0, 7, 8, 9] || x == [5, 0, 0, 8, 9]);
1603 /// // while the pointer can be aligned via `offset`, it would point
1604 /// // outside the allocation
1610 #[stable(feature = "align_offset", since = "1.36.0")]
1611 #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1612 pub const fn align_offset(self, align: usize) -> usize
1616 if !align.is_power_of_two() {
1617 panic!("align_offset: align is not a power-of-two");
1621 // SAFETY: `align` has been checked to be a power of 2 above
1622 unsafe { align_offset(self, align) }
1626 /// Returns whether the pointer is properly aligned for `T`.
1632 /// #![feature(pointer_is_aligned)]
1633 /// #![feature(pointer_byte_offsets)]
1635 /// // On some platforms, the alignment of i32 is less than 4.
1636 /// #[repr(align(4))]
1637 /// struct AlignedI32(i32);
1639 /// let mut data = AlignedI32(42);
1640 /// let ptr = &mut data as *mut AlignedI32;
1642 /// assert!(ptr.is_aligned());
1643 /// assert!(!ptr.wrapping_byte_add(1).is_aligned());
1646 /// # At compiletime
1647 /// **Note: Alignment at compiletime is experimental and subject to change. See the
1648 /// [tracking issue] for details.**
1650 /// At compiletime, the compiler may not know where a value will end up in memory.
1651 /// Calling this function on a pointer created from a reference at compiletime will only
1652 /// return `true` if the pointer is guaranteed to be aligned. This means that the pointer
1653 /// is never aligned if cast to a type with a stricter alignment than the reference's
1654 /// underlying allocation.
1657 /// #![feature(pointer_is_aligned)]
1658 /// #![feature(const_pointer_is_aligned)]
1659 /// #![feature(const_mut_refs)]
1661 /// // On some platforms, the alignment of primitives is less than their size.
1662 /// #[repr(align(4))]
1663 /// struct AlignedI32(i32);
1664 /// #[repr(align(8))]
1665 /// struct AlignedI64(i64);
1668 /// let mut data = AlignedI32(42);
1669 /// let ptr = &mut data as *mut AlignedI32;
1670 /// assert!(ptr.is_aligned());
1672 /// // At runtime either `ptr1` or `ptr2` would be aligned, but at compiletime neither is aligned.
1673 /// let ptr1 = ptr.cast::<AlignedI64>();
1674 /// let ptr2 = ptr.wrapping_add(1).cast::<AlignedI64>();
1675 /// assert!(!ptr1.is_aligned());
1676 /// assert!(!ptr2.is_aligned());
1680 /// Due to this behavior, it is possible that a runtime pointer derived from a compiletime
1681 /// pointer is aligned, even if the compiletime pointer wasn't aligned.
1684 /// #![feature(pointer_is_aligned)]
1685 /// #![feature(const_pointer_is_aligned)]
1687 /// // On some platforms, the alignment of primitives is less than their size.
1688 /// #[repr(align(4))]
1689 /// struct AlignedI32(i32);
1690 /// #[repr(align(8))]
1691 /// struct AlignedI64(i64);
1693 /// // At compiletime, neither `COMPTIME_PTR` nor `COMPTIME_PTR + 1` is aligned.
1694 /// // Also, note that mutable references are not allowed in the final value of constants.
1695 /// const COMPTIME_PTR: *mut AlignedI32 = (&AlignedI32(42) as *const AlignedI32).cast_mut();
1696 /// const _: () = assert!(!COMPTIME_PTR.cast::<AlignedI64>().is_aligned());
1697 /// const _: () = assert!(!COMPTIME_PTR.wrapping_add(1).cast::<AlignedI64>().is_aligned());
1699 /// // At runtime, either `runtime_ptr` or `runtime_ptr + 1` is aligned.
1700 /// let runtime_ptr = COMPTIME_PTR;
1702 /// runtime_ptr.cast::<AlignedI64>().is_aligned(),
1703 /// runtime_ptr.wrapping_add(1).cast::<AlignedI64>().is_aligned(),
1707 /// If a pointer is created from a fixed address, this function behaves the same during
1708 /// runtime and compiletime.
1711 /// #![feature(pointer_is_aligned)]
1712 /// #![feature(const_pointer_is_aligned)]
1714 /// // On some platforms, the alignment of primitives is less than their size.
1715 /// #[repr(align(4))]
1716 /// struct AlignedI32(i32);
1717 /// #[repr(align(8))]
1718 /// struct AlignedI64(i64);
1721 /// let ptr = 40 as *mut AlignedI32;
1722 /// assert!(ptr.is_aligned());
1724 /// // For pointers with a known address, runtime and compiletime behavior are identical.
1725 /// let ptr1 = ptr.cast::<AlignedI64>();
1726 /// let ptr2 = ptr.wrapping_add(1).cast::<AlignedI64>();
1727 /// assert!(ptr1.is_aligned());
1728 /// assert!(!ptr2.is_aligned());
1732 /// [tracking issue]: https://github.com/rust-lang/rust/issues/104203
1735 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1736 #[rustc_const_unstable(feature = "const_pointer_is_aligned", issue = "104203")]
1737 pub const fn is_aligned(self) -> bool
1741 self.is_aligned_to(mem::align_of::<T>())
1744 /// Returns whether the pointer is aligned to `align`.
1746 /// For non-`Sized` pointees this operation considers only the data pointer,
1747 /// ignoring the metadata.
1751 /// The function panics if `align` is not a power-of-two (this includes 0).
1757 /// #![feature(pointer_is_aligned)]
1758 /// #![feature(pointer_byte_offsets)]
1760 /// // On some platforms, the alignment of i32 is less than 4.
1761 /// #[repr(align(4))]
1762 /// struct AlignedI32(i32);
1764 /// let mut data = AlignedI32(42);
1765 /// let ptr = &mut data as *mut AlignedI32;
1767 /// assert!(ptr.is_aligned_to(1));
1768 /// assert!(ptr.is_aligned_to(2));
1769 /// assert!(ptr.is_aligned_to(4));
1771 /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1772 /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1774 /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1777 /// # At compiletime
1778 /// **Note: Alignment at compiletime is experimental and subject to change. See the
1779 /// [tracking issue] for details.**
1781 /// At compiletime, the compiler may not know where a value will end up in memory.
1782 /// Calling this function on a pointer created from a reference at compiletime will only
1783 /// return `true` if the pointer is guaranteed to be aligned. This means that the pointer
1784 /// cannot be stricter aligned than the reference's underlying allocation.
1787 /// #![feature(pointer_is_aligned)]
1788 /// #![feature(const_pointer_is_aligned)]
1789 /// #![feature(const_mut_refs)]
1791 /// // On some platforms, the alignment of i32 is less than 4.
1792 /// #[repr(align(4))]
1793 /// struct AlignedI32(i32);
1796 /// let mut data = AlignedI32(42);
1797 /// let ptr = &mut data as *mut AlignedI32;
1799 /// assert!(ptr.is_aligned_to(1));
1800 /// assert!(ptr.is_aligned_to(2));
1801 /// assert!(ptr.is_aligned_to(4));
1803 /// // At compiletime, we know for sure that the pointer isn't aligned to 8.
1804 /// assert!(!ptr.is_aligned_to(8));
1805 /// assert!(!ptr.wrapping_add(1).is_aligned_to(8));
1809 /// Due to this behavior, it is possible that a runtime pointer derived from a compiletime
1810 /// pointer is aligned, even if the compiletime pointer wasn't aligned.
1813 /// #![feature(pointer_is_aligned)]
1814 /// #![feature(const_pointer_is_aligned)]
1816 /// // On some platforms, the alignment of i32 is less than 4.
1817 /// #[repr(align(4))]
1818 /// struct AlignedI32(i32);
1820 /// // At compiletime, neither `COMPTIME_PTR` nor `COMPTIME_PTR + 1` is aligned.
1821 /// // Also, note that mutable references are not allowed in the final value of constants.
1822 /// const COMPTIME_PTR: *mut AlignedI32 = (&AlignedI32(42) as *const AlignedI32).cast_mut();
1823 /// const _: () = assert!(!COMPTIME_PTR.is_aligned_to(8));
1824 /// const _: () = assert!(!COMPTIME_PTR.wrapping_add(1).is_aligned_to(8));
1826 /// // At runtime, either `runtime_ptr` or `runtime_ptr + 1` is aligned.
1827 /// let runtime_ptr = COMPTIME_PTR;
1829 /// runtime_ptr.is_aligned_to(8),
1830 /// runtime_ptr.wrapping_add(1).is_aligned_to(8),
1834 /// If a pointer is created from a fixed address, this function behaves the same during
1835 /// runtime and compiletime.
1838 /// #![feature(pointer_is_aligned)]
1839 /// #![feature(const_pointer_is_aligned)]
1842 /// let ptr = 40 as *mut u8;
1843 /// assert!(ptr.is_aligned_to(1));
1844 /// assert!(ptr.is_aligned_to(2));
1845 /// assert!(ptr.is_aligned_to(4));
1846 /// assert!(ptr.is_aligned_to(8));
1847 /// assert!(!ptr.is_aligned_to(16));
1851 /// [tracking issue]: https://github.com/rust-lang/rust/issues/104203
1854 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1855 #[rustc_const_unstable(feature = "const_pointer_is_aligned", issue = "104203")]
1856 pub const fn is_aligned_to(self, align: usize) -> bool {
1857 if !align.is_power_of_two() {
1858 panic!("is_aligned_to: align is not a power-of-two");
1862 fn runtime_impl(ptr: *mut (), align: usize) -> bool {
1863 ptr.addr() & (align - 1) == 0
1867 const fn const_impl(ptr: *mut (), align: usize) -> bool {
1868 // We can't use the address of `self` in a `const fn`, so we use `align_offset` instead.
1869 // The cast to `()` is used to
1870 // 1. deal with fat pointers; and
1871 // 2. ensure that `align_offset` doesn't actually try to compute an offset.
1872 ptr.align_offset(align) == 0
1875 // SAFETY: The two versions are equivalent at runtime.
1876 unsafe { const_eval_select((self.cast::<()>(), align), const_impl, runtime_impl) }
1881 /// Returns the length of a raw slice.
1883 /// The returned value is the number of **elements**, not the number of bytes.
1885 /// This function is safe, even when the raw slice cannot be cast to a slice
1886 /// reference because the pointer is null or unaligned.
1891 /// #![feature(slice_ptr_len)]
1894 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1895 /// assert_eq!(slice.len(), 3);
1898 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1899 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1900 pub const fn len(self) -> usize {
1904 /// Returns `true` if the raw slice has a length of 0.
1909 /// #![feature(slice_ptr_len)]
1911 /// let mut a = [1, 2, 3];
1912 /// let ptr = &mut a as *mut [_];
1913 /// assert!(!ptr.is_empty());
1916 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1917 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1918 pub const fn is_empty(self) -> bool {
1922 /// Divides one mutable raw slice into two at an index.
1924 /// The first will contain all indices from `[0, mid)` (excluding
1925 /// the index `mid` itself) and the second will contain all
1926 /// indices from `[mid, len)` (excluding the index `len` itself).
1930 /// Panics if `mid > len`.
1934 /// `mid` must be [in-bounds] of the underlying [allocated object].
1935 /// Which means `self` must be dereferenceable and span a single allocation
1936 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1937 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1939 /// Since `len` being in-bounds it is not a safety invariant of `*mut [T]` the
1940 /// safety requirements of this method are the same as for [`split_at_mut_unchecked`].
1941 /// The explicit bounds check is only as useful as `len` is correct.
1943 /// [`split_at_mut_unchecked`]: #method.split_at_mut_unchecked
1944 /// [in-bounds]: #method.add
1945 /// [allocated object]: crate::ptr#allocated-object
1946 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1951 /// #![feature(raw_slice_split)]
1952 /// #![feature(slice_ptr_get)]
1954 /// let mut v = [1, 0, 3, 0, 5, 6];
1955 /// let ptr = &mut v as *mut [_];
1957 /// let (left, right) = ptr.split_at_mut(2);
1958 /// assert_eq!(&*left, [1, 0]);
1959 /// assert_eq!(&*right, [3, 0, 5, 6]);
1964 #[unstable(feature = "raw_slice_split", issue = "95595")]
1965 pub unsafe fn split_at_mut(self, mid: usize) -> (*mut [T], *mut [T]) {
1966 assert!(mid <= self.len());
1967 // SAFETY: The assert above is only a safety-net as long as `self.len()` is correct
1968 // The actual safety requirements of this function are the same as for `split_at_mut_unchecked`
1969 unsafe { self.split_at_mut_unchecked(mid) }
1972 /// Divides one mutable raw slice into two at an index, without doing bounds checking.
1974 /// The first will contain all indices from `[0, mid)` (excluding
1975 /// the index `mid` itself) and the second will contain all
1976 /// indices from `[mid, len)` (excluding the index `len` itself).
1980 /// `mid` must be [in-bounds] of the underlying [allocated object].
1981 /// Which means `self` must be dereferenceable and span a single allocation
1982 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1983 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1985 /// [in-bounds]: #method.add
1986 /// [out-of-bounds index]: #method.add
1987 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1992 /// #![feature(raw_slice_split)]
1994 /// let mut v = [1, 0, 3, 0, 5, 6];
1995 /// // scoped to restrict the lifetime of the borrows
1997 /// let ptr = &mut v as *mut [_];
1998 /// let (left, right) = ptr.split_at_mut_unchecked(2);
1999 /// assert_eq!(&*left, [1, 0]);
2000 /// assert_eq!(&*right, [3, 0, 5, 6]);
2001 /// (&mut *left)[1] = 2;
2002 /// (&mut *right)[1] = 4;
2004 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
2007 #[unstable(feature = "raw_slice_split", issue = "95595")]
2008 pub unsafe fn split_at_mut_unchecked(self, mid: usize) -> (*mut [T], *mut [T]) {
2009 let len = self.len();
2010 let ptr = self.as_mut_ptr();
2012 // SAFETY: Caller must pass a valid pointer and an index that is in-bounds.
2013 let tail = unsafe { ptr.add(mid) };
2015 crate::ptr::slice_from_raw_parts_mut(ptr, mid),
2016 crate::ptr::slice_from_raw_parts_mut(tail, len - mid),
2020 /// Returns a raw pointer to the slice's buffer.
2022 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
2027 /// #![feature(slice_ptr_get)]
2030 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
2031 /// assert_eq!(slice.as_mut_ptr(), ptr::null_mut());
2034 #[unstable(feature = "slice_ptr_get", issue = "74265")]
2035 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
2036 pub const fn as_mut_ptr(self) -> *mut T {
2040 /// Returns a raw pointer to an element or subslice, without doing bounds
2043 /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
2044 /// is *[undefined behavior]* even if the resulting pointer is not used.
2046 /// [out-of-bounds index]: #method.add
2047 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2052 /// #![feature(slice_ptr_get)]
2054 /// let x = &mut [1, 2, 4] as *mut [i32];
2057 /// assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
2060 #[unstable(feature = "slice_ptr_get", issue = "74265")]
2061 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
2063 pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
2065 I: ~const SliceIndex<[T]>,
2067 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
2068 unsafe { index.get_unchecked_mut(self) }
2071 /// Returns `None` if the pointer is null, or else returns a shared slice to
2072 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
2073 /// that the value has to be initialized.
2075 /// For the mutable counterpart see [`as_uninit_slice_mut`].
2077 /// [`as_ref`]: #method.as_ref-1
2078 /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
2082 /// When calling this method, you have to ensure that *either* the pointer is null *or*
2083 /// all of the following is true:
2085 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
2086 /// and it must be properly aligned. This means in particular:
2088 /// * The entire memory range of this slice must be contained within a single [allocated object]!
2089 /// Slices can never span across multiple allocated objects.
2091 /// * The pointer must be aligned even for zero-length slices. One
2092 /// reason for this is that enum layout optimizations may rely on references
2093 /// (including slices of any length) being aligned and non-null to distinguish
2094 /// them from other data. You can obtain a pointer that is usable as `data`
2095 /// for zero-length slices using [`NonNull::dangling()`].
2097 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
2098 /// See the safety documentation of [`pointer::offset`].
2100 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
2101 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
2102 /// In particular, while this reference exists, the memory the pointer points to must
2103 /// not get mutated (except inside `UnsafeCell`).
2105 /// This applies even if the result of this method is unused!
2107 /// See also [`slice::from_raw_parts`][].
2109 /// [valid]: crate::ptr#safety
2110 /// [allocated object]: crate::ptr#allocated-object
2112 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
2113 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
2114 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
2118 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
2119 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
2123 /// Returns `None` if the pointer is null, or else returns a unique slice to
2124 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
2125 /// that the value has to be initialized.
2127 /// For the shared counterpart see [`as_uninit_slice`].
2129 /// [`as_mut`]: #method.as_mut
2130 /// [`as_uninit_slice`]: #method.as_uninit_slice-1
2134 /// When calling this method, you have to ensure that *either* the pointer is null *or*
2135 /// all of the following is true:
2137 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
2138 /// many bytes, and it must be properly aligned. This means in particular:
2140 /// * The entire memory range of this slice must be contained within a single [allocated object]!
2141 /// Slices can never span across multiple allocated objects.
2143 /// * The pointer must be aligned even for zero-length slices. One
2144 /// reason for this is that enum layout optimizations may rely on references
2145 /// (including slices of any length) being aligned and non-null to distinguish
2146 /// them from other data. You can obtain a pointer that is usable as `data`
2147 /// for zero-length slices using [`NonNull::dangling()`].
2149 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
2150 /// See the safety documentation of [`pointer::offset`].
2152 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
2153 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
2154 /// In particular, while this reference exists, the memory the pointer points to must
2155 /// not get accessed (read or written) through any other pointer.
2157 /// This applies even if the result of this method is unused!
2159 /// See also [`slice::from_raw_parts_mut`][].
2161 /// [valid]: crate::ptr#safety
2162 /// [allocated object]: crate::ptr#allocated-object
2164 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
2165 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
2166 pub const unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
2170 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
2171 Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
2176 // Equality for pointers
2177 #[stable(feature = "rust1", since = "1.0.0")]
2178 impl<T: ?Sized> PartialEq for *mut T {
2180 fn eq(&self, other: &*mut T) -> bool {
2185 #[stable(feature = "rust1", since = "1.0.0")]
2186 impl<T: ?Sized> Eq for *mut T {}
2188 #[stable(feature = "rust1", since = "1.0.0")]
2189 impl<T: ?Sized> Ord for *mut T {
2191 fn cmp(&self, other: &*mut T) -> Ordering {
2194 } else if self == other {
2202 #[stable(feature = "rust1", since = "1.0.0")]
2203 impl<T: ?Sized> PartialOrd for *mut T {
2205 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2206 Some(self.cmp(other))
2210 fn lt(&self, other: &*mut T) -> bool {
2215 fn le(&self, other: &*mut T) -> bool {
2220 fn gt(&self, other: &*mut T) -> bool {
2225 fn ge(&self, other: &*mut T) -> bool {