core/ptr/mut_ptr.rs
1use super::*;
2use crate::cmp::Ordering::{Equal, Greater, Less};
3use crate::intrinsics::const_eval_select;
4use crate::marker::{Destruct, PointeeSized};
5use crate::mem::{self, SizedTypeProperties};
6use crate::slice::{self, SliceIndex};
7
8impl<T: PointeeSized> *mut T {
9 #[doc = include_str!("docs/is_null.md")]
10 ///
11 /// # Examples
12 ///
13 /// ```
14 /// let mut s = [1, 2, 3];
15 /// let ptr: *mut u32 = s.as_mut_ptr();
16 /// assert!(!ptr.is_null());
17 /// ```
18 #[stable(feature = "rust1", since = "1.0.0")]
19 #[rustc_const_stable(feature = "const_ptr_is_null", since = "1.84.0")]
20 #[rustc_diagnostic_item = "ptr_is_null"]
21 #[inline]
22 pub const fn is_null(self) -> bool {
23 self.cast_const().is_null()
24 }
25
26 /// Casts to a pointer of another type.
27 #[stable(feature = "ptr_cast", since = "1.38.0")]
28 #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
29 #[rustc_diagnostic_item = "ptr_cast"]
30 #[inline(always)]
31 pub const fn cast<U>(self) -> *mut U {
32 self as _
33 }
34
35 /// Try to cast to a pointer of another type by checking alignment.
36 ///
37 /// If the pointer is properly aligned to the target type, it will be
38 /// cast to the target type. Otherwise, `None` is returned.
39 ///
40 /// # Examples
41 ///
42 /// ```rust
43 /// let mut x = 0u64;
44 ///
45 /// let aligned: *mut u64 = &mut x;
46 /// let unaligned = unsafe { aligned.byte_add(1) };
47 ///
48 /// assert!(aligned.try_cast_aligned::<u32>().is_some());
49 /// assert!(unaligned.try_cast_aligned::<u32>().is_none());
50 /// ```
51 #[stable(feature = "pointer_try_cast_aligned", since = "1.101.0")]
52 #[must_use = "this returns the result of the operation, \
53 without modifying the original"]
54 #[inline]
55 pub fn try_cast_aligned<U>(self) -> Option<*mut U> {
56 if self.is_aligned_to(align_of::<U>()) { Some(self.cast()) } else { None }
57 }
58
59 /// Uses the address value in a new pointer of another type.
60 ///
61 /// This operation will ignore the address part of its `meta` operand and discard existing
62 /// metadata of `self`. For pointers to a sized types (thin pointers), this has the same effect
63 /// as a simple cast. For pointers to an unsized type (fat pointers) this recombines the address
64 /// with new metadata such as slice lengths or `dyn`-vtable.
65 ///
66 /// The resulting pointer will have provenance of `self`. This operation is semantically the
67 /// same as creating a new pointer with the data pointer value of `self` but the metadata of
68 /// `meta`, being fat or thin depending on the `meta` operand.
69 ///
70 /// # Examples
71 ///
72 /// This function is primarily useful for enabling pointer arithmetic on potentially fat
73 /// pointers. The pointer is cast to a sized pointee to utilize offset operations and then
74 /// recombined with its own original metadata.
75 ///
76 /// ```
77 /// #![feature(set_ptr_value)]
78 /// # use core::fmt::Debug;
79 /// let mut arr: [i32; 3] = [1, 2, 3];
80 /// let mut ptr = arr.as_mut_ptr() as *mut dyn Debug;
81 /// let thin = ptr as *mut u8;
82 /// unsafe {
83 /// ptr = thin.add(8).with_metadata_of(ptr);
84 /// # assert_eq!(*(ptr as *mut i32), 3);
85 /// println!("{:?}", &*ptr); // will print "3"
86 /// }
87 /// ```
88 ///
89 /// # *Incorrect* usage
90 ///
91 /// The provenance from pointers is *not* combined. The result must only be used to refer to the
92 /// address allowed by `self`.
93 ///
94 /// ```rust,no_run
95 /// #![feature(set_ptr_value)]
96 /// let mut x = 0u32;
97 /// let mut y = 1u32;
98 ///
99 /// let x = (&mut x) as *mut u32;
100 /// let y = (&mut y) as *mut u32;
101 ///
102 /// let offset = (x as usize - y as usize) / 4;
103 /// let bad = x.wrapping_add(offset).with_metadata_of(y);
104 ///
105 /// // This dereference is UB. The pointer only has provenance for `x` but points to `y`.
106 /// println!("{:?}", unsafe { &*bad });
107 /// ```
108 #[unstable(feature = "set_ptr_value", issue = "75091")]
109 #[must_use = "returns a new pointer rather than modifying its argument"]
110 #[inline]
111 pub const fn with_metadata_of<U>(self, meta: *const U) -> *mut U
112 where
113 U: PointeeSized,
114 {
115 from_raw_parts_mut::<U>(self as *mut (), metadata(meta))
116 }
117
118 /// Changes constness without changing the type.
119 ///
120 /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
121 /// refactored.
122 ///
123 /// While not strictly required (`*mut T` coerces to `*const T`), this is provided for symmetry
124 /// with [`cast_mut`] on `*const T` and may have documentation value if used instead of implicit
125 /// coercion.
126 ///
127 /// [`cast_mut`]: pointer::cast_mut
128 #[stable(feature = "ptr_const_cast", since = "1.65.0")]
129 #[rustc_const_stable(feature = "ptr_const_cast", since = "1.65.0")]
130 #[rustc_diagnostic_item = "ptr_cast_const"]
131 #[inline(always)]
132 pub const fn cast_const(self) -> *const T {
133 self as _
134 }
135
136 #[doc = include_str!("./docs/addr.md")]
137 ///
138 /// [without_provenance]: without_provenance_mut
139 #[must_use]
140 #[inline(always)]
141 #[expect(clippy::transmutes_expressible_as_ptr_casts, reason = "implements pointer cast")]
142 #[stable(feature = "strict_provenance", since = "1.84.0")]
143 pub fn addr(self) -> usize {
144 // A pointer-to-integer transmute currently has exactly the right semantics: it returns the
145 // address without exposing the provenance. Note that this is *not* a stable guarantee about
146 // transmute semantics, it relies on sysroot crates having special status.
147 // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
148 // provenance).
149 unsafe { mem::transmute(self.cast::<()>()) }
150 }
151
152 /// Exposes the ["provenance"][crate::ptr#provenance] part of the pointer for future use in
153 /// [`with_exposed_provenance_mut`] and returns the "address" portion.
154 ///
155 /// This is equivalent to `self as usize`, which semantically discards provenance information.
156 /// Furthermore, this (like the `as` cast) has the implicit side-effect of marking the
157 /// provenance as 'exposed', so on platforms that support it you can later call
158 /// [`with_exposed_provenance_mut`] to reconstitute the original pointer including its provenance.
159 ///
160 /// Due to its inherent ambiguity, [`with_exposed_provenance_mut`] may not be supported by tools
161 /// that help you to stay conformant with the Rust memory model. It is recommended to use
162 /// [Strict Provenance][crate::ptr#strict-provenance] APIs such as [`with_addr`][pointer::with_addr]
163 /// wherever possible, in which case [`addr`][pointer::addr] should be used instead of `expose_provenance`.
164 ///
165 /// On most platforms this will produce a value with the same bytes as the original pointer,
166 /// because all the bytes are dedicated to describing the address. Platforms which need to store
167 /// additional information in the pointer may not support this operation, since the 'expose'
168 /// side-effect which is required for [`with_exposed_provenance_mut`] to work is typically not
169 /// available.
170 ///
171 /// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
172 ///
173 /// [`with_exposed_provenance_mut`]: with_exposed_provenance_mut
174 #[inline(always)]
175 #[stable(feature = "exposed_provenance", since = "1.84.0")]
176 #[expect(implicit_provenance_casts, reason = "this *is* the replacement")]
177 pub fn expose_provenance(self) -> usize {
178 self.cast::<()>() as usize
179 }
180
181 /// Creates a new pointer with the given address and the [provenance][crate::ptr#provenance] of
182 /// `self`.
183 ///
184 /// This is similar to a `addr as *mut T` cast, but copies
185 /// the *provenance* of `self` to the new pointer.
186 /// This avoids the inherent ambiguity of the unary cast.
187 ///
188 /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
189 /// `self` to the given address, and therefore has all the same capabilities and restrictions.
190 ///
191 /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
192 #[must_use]
193 #[inline]
194 #[stable(feature = "strict_provenance", since = "1.84.0")]
195 pub fn with_addr(self, addr: usize) -> Self {
196 // This should probably be an intrinsic to avoid doing any sort of arithmetic, but
197 // meanwhile, we can implement it with `wrapping_offset`, which preserves the pointer's
198 // provenance.
199 let self_addr = self.addr() as isize;
200 let dest_addr = addr as isize;
201 let offset = dest_addr.wrapping_sub(self_addr);
202 self.wrapping_byte_offset(offset)
203 }
204
205 /// Creates a new pointer by mapping `self`'s address to a new one, preserving the original
206 /// pointer's [provenance][crate::ptr#provenance].
207 ///
208 /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
209 ///
210 /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
211 #[must_use]
212 #[inline]
213 #[stable(feature = "strict_provenance", since = "1.84.0")]
214 pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self {
215 self.with_addr(f(self.addr()))
216 }
217
218 /// Decompose a (possibly wide) pointer into its data pointer and metadata components.
219 ///
220 /// The pointer can be later reconstructed with [`from_raw_parts_mut`].
221 #[unstable(feature = "ptr_metadata", issue = "81513")]
222 #[inline]
223 pub const fn to_raw_parts(self) -> (*mut (), <T as super::Pointee>::Metadata) {
224 (self.cast(), super::metadata(self))
225 }
226
227 #[doc = include_str!("./docs/as_ref.md")]
228 ///
229 /// ```
230 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
231 ///
232 /// unsafe {
233 /// let val_back = ptr.as_ref_unchecked();
234 /// println!("We got back the value: {val_back}!");
235 /// }
236 /// ```
237 ///
238 /// # Examples
239 ///
240 /// ```
241 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
242 ///
243 /// unsafe {
244 /// if let Some(val_back) = ptr.as_ref() {
245 /// println!("We got back the value: {val_back}!");
246 /// }
247 /// }
248 /// ```
249 ///
250 /// # See Also
251 ///
252 /// For the mutable counterpart see [`as_mut`].
253 ///
254 /// [`is_null`]: #method.is_null-1
255 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
256 /// [`as_ref_unchecked`]: #method.as_ref_unchecked-1
257 /// [`as_mut`]: #method.as_mut
258 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
259 #[rustc_const_stable(feature = "const_ptr_is_null", since = "1.84.0")]
260 #[inline]
261 pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
262 // SAFETY: the caller must guarantee that `self` is valid for a
263 // reference if it isn't null.
264 if self.is_null() { None } else { unsafe { Some(&*self) } }
265 }
266
267 /// Returns a shared reference to the value behind the pointer.
268 /// If the pointer may be null or the value may be uninitialized, [`as_uninit_ref`] must be used instead.
269 /// If the pointer may be null, but the value is known to have been initialized, [`as_ref`] must be used instead.
270 ///
271 /// For the mutable counterpart see [`as_mut_unchecked`].
272 ///
273 /// [`as_ref`]: #method.as_ref
274 /// [`as_uninit_ref`]: #method.as_uninit_ref
275 /// [`as_mut_unchecked`]: #method.as_mut_unchecked
276 ///
277 /// # Safety
278 ///
279 /// When calling this method, you have to ensure that the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
280 ///
281 /// # Examples
282 ///
283 /// ```
284 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
285 ///
286 /// unsafe {
287 /// println!("We got back the value: {}!", ptr.as_ref_unchecked());
288 /// }
289 /// ```
290 #[stable(feature = "ptr_as_ref_unchecked", since = "1.95.0")]
291 #[rustc_const_stable(feature = "ptr_as_ref_unchecked", since = "1.95.0")]
292 #[inline]
293 #[must_use]
294 pub const unsafe fn as_ref_unchecked<'a>(self) -> &'a T {
295 // SAFETY: the caller must guarantee that `self` is valid for a reference
296 unsafe { &*self }
297 }
298
299 #[doc = include_str!("./docs/as_uninit_ref.md")]
300 ///
301 /// [`is_null`]: #method.is_null-1
302 /// [`as_ref`]: pointer#method.as_ref-1
303 ///
304 /// # See Also
305 /// For the mutable counterpart see [`as_uninit_mut`].
306 ///
307 /// [`as_uninit_mut`]: #method.as_uninit_mut
308 ///
309 /// # Examples
310 ///
311 /// ```
312 /// #![feature(ptr_as_uninit)]
313 ///
314 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
315 ///
316 /// unsafe {
317 /// if let Some(val_back) = ptr.as_uninit_ref() {
318 /// println!("We got back the value: {}!", val_back.assume_init());
319 /// }
320 /// }
321 /// ```
322 #[inline]
323 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
324 pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
325 where
326 T: Sized,
327 {
328 // SAFETY: the caller must guarantee that `self` meets all the
329 // requirements for a reference.
330 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
331 }
332
333 #[doc = include_str!("./docs/offset.md")]
334 ///
335 /// Consider using [`wrapping_offset`](#method.wrapping_offset) instead if these constraints are
336 /// difficult to satisfy. The only advantage of this method is that it
337 /// enables more aggressive compiler optimizations.
338 ///
339 /// # Examples
340 ///
341 /// ```
342 /// let mut s = [1, 2, 3];
343 /// let ptr: *mut u32 = s.as_mut_ptr();
344 ///
345 /// unsafe {
346 /// assert_eq!(2, *ptr.offset(1));
347 /// assert_eq!(3, *ptr.offset(2));
348 /// }
349 /// ```
350 #[stable(feature = "rust1", since = "1.0.0")]
351 #[must_use = "returns a new pointer rather than modifying its argument"]
352 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
353 #[inline(always)]
354 #[track_caller]
355 pub const unsafe fn offset(self, count: isize) -> *mut T
356 where
357 T: Sized,
358 {
359 #[inline]
360 #[rustc_allow_const_fn_unstable(const_eval_select)]
361 const fn runtime_offset_nowrap(this: *const (), count: isize, size: usize) -> bool {
362 // We can use const_eval_select here because this is only for UB checks.
363 const_eval_select!(
364 @capture { this: *const (), count: isize, size: usize } -> bool:
365 if const {
366 true
367 } else {
368 // `size` is the size of a Rust type, so we know that
369 // `size <= isize::MAX` and thus `as` cast here is not lossy.
370 let Some(byte_offset) = count.checked_mul(size as isize) else {
371 return false;
372 };
373 let (_, overflow) = this.addr().overflowing_add_signed(byte_offset);
374 !overflow
375 }
376 )
377 }
378
379 ub_checks::assert_unsafe_precondition!(
380 check_language_ub,
381 "ptr::offset requires the address calculation to not overflow",
382 (
383 this: *const () = self as *const (),
384 count: isize = count,
385 size: usize = size_of::<T>(),
386 ) => runtime_offset_nowrap(this, count, size)
387 );
388
389 // SAFETY: the caller must uphold the safety contract for `offset`.
390 // The obtained pointer is valid for writes since the caller must
391 // guarantee that it points to the same allocation as `self`.
392 unsafe { intrinsics::offset(self, count) }
393 }
394
395 /// Adds a signed offset in bytes to a pointer.
396 ///
397 /// `count` is in units of **bytes**.
398 ///
399 /// This is purely a convenience for casting to a `u8` pointer and
400 /// using [offset][pointer::offset] on it.
401 ///
402 /// For non-`Sized` pointees this operation changes only the data pointer,
403 /// leaving the metadata untouched.
404 ///
405 /// # Safety
406 ///
407 /// See [offset][pointer::offset] for documentation and safety requirements.
408 #[must_use]
409 #[inline(always)]
410 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
411 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
412 #[track_caller]
413 pub const unsafe fn byte_offset(self, count: isize) -> Self {
414 // SAFETY: the caller must uphold the safety contract for `offset`.
415 unsafe { self.cast::<u8>().offset(count).with_metadata_of(self) }
416 }
417
418 /// Adds a signed offset to a pointer using wrapping arithmetic.
419 ///
420 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
421 /// offset of `3 * size_of::<T>()` bytes.
422 ///
423 /// # Safety
424 ///
425 /// This operation itself is always safe, but using the resulting pointer is not.
426 ///
427 /// The resulting pointer "remembers" the [allocation] that `self` points to
428 /// (this is called "[Provenance](ptr/index.html#provenance)").
429 /// The pointer must not be used to read or write other allocations.
430 ///
431 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
432 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
433 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
434 /// `x` and `y` point into the same allocation.
435 ///
436 /// Compared to [`offset`], this method basically delays the requirement of staying within the
437 /// same allocation: [`offset`] is immediate Undefined Behavior when crossing object
438 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
439 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
440 /// can be optimized better and is thus preferable in performance-sensitive code.
441 ///
442 /// The delayed check only considers the value of the pointer that was dereferenced, not the
443 /// intermediate values used during the computation of the final result. For example,
444 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
445 /// words, leaving the allocation and then re-entering it later is permitted.
446 ///
447 /// [`offset`]: #method.offset
448 /// [allocation]: crate::ptr#allocation
449 ///
450 /// # Examples
451 ///
452 /// ```
453 /// // Iterate using a raw pointer in increments of two elements
454 /// let mut data = [1u8, 2, 3, 4, 5];
455 /// let mut ptr: *mut u8 = data.as_mut_ptr();
456 /// let step = 2;
457 /// let end_rounded_up = ptr.wrapping_offset(6);
458 ///
459 /// while ptr != end_rounded_up {
460 /// unsafe {
461 /// *ptr = 0;
462 /// }
463 /// ptr = ptr.wrapping_offset(step);
464 /// }
465 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
466 /// ```
467 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
468 #[must_use = "returns a new pointer rather than modifying its argument"]
469 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
470 #[inline(always)]
471 pub const fn wrapping_offset(self, count: isize) -> *mut T
472 where
473 T: Sized,
474 {
475 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
476 unsafe { intrinsics::arith_offset(self, count) as *mut T }
477 }
478
479 /// Adds a signed offset in bytes to a pointer using wrapping arithmetic.
480 ///
481 /// `count` is in units of **bytes**.
482 ///
483 /// This is purely a convenience for casting to a `u8` pointer and
484 /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
485 /// for documentation.
486 ///
487 /// For non-`Sized` pointees this operation changes only the data pointer,
488 /// leaving the metadata untouched.
489 #[must_use]
490 #[inline(always)]
491 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
492 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
493 pub const fn wrapping_byte_offset(self, count: isize) -> Self {
494 self.cast::<u8>().wrapping_offset(count).with_metadata_of(self)
495 }
496
497 /// Masks out bits of the pointer according to a mask.
498 ///
499 /// This is convenience for `ptr.map_addr(|a| a & mask)`.
500 ///
501 /// For non-`Sized` pointees this operation changes only the data pointer,
502 /// leaving the metadata untouched.
503 ///
504 /// ## Examples
505 ///
506 /// ```
507 /// #![feature(ptr_mask)]
508 /// let mut v = 17_u32;
509 /// let ptr: *mut u32 = &mut v;
510 ///
511 /// // `u32` is 4 bytes aligned,
512 /// // which means that lower 2 bits are always 0.
513 /// let tag_mask = 0b11;
514 /// let ptr_mask = !tag_mask;
515 ///
516 /// // We can store something in these lower bits
517 /// let tagged_ptr = ptr.map_addr(|a| a | 0b10);
518 ///
519 /// // Get the "tag" back
520 /// let tag = tagged_ptr.addr() & tag_mask;
521 /// assert_eq!(tag, 0b10);
522 ///
523 /// // Note that `tagged_ptr` is unaligned, it's UB to read from/write to it.
524 /// // To get original pointer `mask` can be used:
525 /// let masked_ptr = tagged_ptr.mask(ptr_mask);
526 /// assert_eq!(unsafe { *masked_ptr }, 17);
527 ///
528 /// unsafe { *masked_ptr = 0 };
529 /// assert_eq!(v, 0);
530 /// ```
531 #[unstable(feature = "ptr_mask", issue = "98290")]
532 #[must_use = "returns a new pointer rather than modifying its argument"]
533 #[inline(always)]
534 pub fn mask(self, mask: usize) -> *mut T {
535 intrinsics::ptr_mask(self.cast::<()>(), mask).cast_mut().with_metadata_of(self)
536 }
537
538 /// Returns `None` if the pointer is null, or else returns a unique reference to
539 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
540 /// must be used instead. If the value is known to be non-null, [`as_mut_unchecked`]
541 /// can be used instead.
542 ///
543 /// For the shared counterpart see [`as_ref`].
544 ///
545 /// [`as_uninit_mut`]: #method.as_uninit_mut
546 /// [`as_mut_unchecked`]: #method.as_mut_unchecked
547 /// [`as_ref`]: pointer#method.as_ref-1
548 ///
549 /// # Safety
550 ///
551 /// When calling this method, you have to ensure that *either*
552 /// the pointer is null *or*
553 /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
554 ///
555 /// # Panics during const evaluation
556 ///
557 /// This method will panic during const evaluation if the pointer cannot be
558 /// determined to be null or not. See [`is_null`] for more information.
559 ///
560 /// [`is_null`]: #method.is_null-1
561 ///
562 /// # Examples
563 ///
564 /// ```
565 /// let mut s = [1, 2, 3];
566 /// let ptr: *mut u32 = s.as_mut_ptr();
567 /// let first_value = unsafe { ptr.as_mut().unwrap() };
568 /// *first_value = 4;
569 /// # assert_eq!(s, [4, 2, 3]);
570 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
571 /// ```
572 ///
573 /// # Null-unchecked version
574 ///
575 /// If you are sure the pointer can never be null, you can use `as_mut_unchecked` which returns
576 /// `&mut T` instead of `Option<&mut T>`.
577 ///
578 /// ```
579 /// let mut s = [1, 2, 3];
580 /// let ptr: *mut u32 = s.as_mut_ptr();
581 /// let first_value = unsafe { ptr.as_mut_unchecked() };
582 /// *first_value = 4;
583 /// # assert_eq!(s, [4, 2, 3]);
584 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
585 /// ```
586 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
587 #[rustc_const_stable(feature = "const_ptr_is_null", since = "1.84.0")]
588 #[inline]
589 pub const unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
590 // SAFETY: the caller must guarantee that `self` is be valid for
591 // a mutable reference if it isn't null.
592 if self.is_null() { None } else { unsafe { Some(&mut *self) } }
593 }
594
595 /// Returns a unique reference to the value behind the pointer.
596 /// If the pointer may be null or the value may be uninitialized, [`as_uninit_mut`] must be used instead.
597 /// If the pointer may be null, but the value is known to have been initialized, [`as_mut`] must be used instead.
598 ///
599 /// For the shared counterpart see [`as_ref_unchecked`].
600 ///
601 /// [`as_mut`]: #method.as_mut
602 /// [`as_uninit_mut`]: #method.as_uninit_mut
603 /// [`as_ref_unchecked`]: #method.as_ref_unchecked
604 ///
605 /// # Safety
606 ///
607 /// When calling this method, you have to ensure that
608 /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
609 ///
610 /// # Examples
611 ///
612 /// ```
613 /// let mut s = [1, 2, 3];
614 /// let ptr: *mut u32 = s.as_mut_ptr();
615 /// let first_value = unsafe { ptr.as_mut_unchecked() };
616 /// *first_value = 4;
617 /// # assert_eq!(s, [4, 2, 3]);
618 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
619 /// ```
620 #[stable(feature = "ptr_as_ref_unchecked", since = "1.95.0")]
621 #[rustc_const_stable(feature = "ptr_as_ref_unchecked", since = "1.95.0")]
622 #[inline]
623 #[must_use]
624 pub const unsafe fn as_mut_unchecked<'a>(self) -> &'a mut T {
625 // SAFETY: the caller must guarantee that `self` is valid for a reference
626 unsafe { &mut *self }
627 }
628
629 /// Returns `None` if the pointer is null, or else returns a unique reference to
630 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
631 /// that the value has to be initialized.
632 ///
633 /// For the shared counterpart see [`as_uninit_ref`].
634 ///
635 /// [`as_mut`]: #method.as_mut
636 /// [`as_uninit_ref`]: pointer#method.as_uninit_ref-1
637 ///
638 /// # Safety
639 ///
640 /// When calling this method, you have to ensure that *either* the pointer is null *or*
641 /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
642 /// Note that because the created reference is to `MaybeUninit<T>`, the
643 /// source pointer can point to uninitialized memory.
644 ///
645 /// # Panics during const evaluation
646 ///
647 /// This method will panic during const evaluation if the pointer cannot be
648 /// determined to be null or not. See [`is_null`] for more information.
649 ///
650 /// [`is_null`]: #method.is_null-1
651 #[inline]
652 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
653 pub const unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
654 where
655 T: Sized,
656 {
657 // SAFETY: the caller must guarantee that `self` meets all the
658 // requirements for a reference.
659 if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
660 }
661
662 /// Returns whether two pointers are guaranteed to be equal.
663 ///
664 /// At runtime this function behaves like `Some(self == other)`.
665 /// However, in some contexts (e.g., compile-time evaluation),
666 /// it is not always possible to determine equality of two pointers, so this function may
667 /// spuriously return `None` for pointers that later actually turn out to have its equality known.
668 /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
669 ///
670 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
671 /// version and unsafe code must not
672 /// rely on the result of this function for soundness. It is suggested to only use this function
673 /// for performance optimizations where spurious `None` return values by this function do not
674 /// affect the outcome, but just the performance.
675 /// The consequences of using this method to make runtime and compile-time code behave
676 /// differently have not been explored. This method should not be used to introduce such
677 /// differences, and it should also not be stabilized before we have a better understanding
678 /// of this issue.
679 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
680 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
681 #[inline]
682 pub const fn guaranteed_eq(self, other: *mut T) -> Option<bool>
683 where
684 T: Sized,
685 {
686 (self as *const T).guaranteed_eq(other as _)
687 }
688
689 /// Returns whether two pointers are guaranteed to be inequal.
690 ///
691 /// At runtime this function behaves like `Some(self != other)`.
692 /// However, in some contexts (e.g., compile-time evaluation),
693 /// it is not always possible to determine inequality of two pointers, so this function may
694 /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
695 /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
696 ///
697 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
698 /// version and unsafe code must not
699 /// rely on the result of this function for soundness. It is suggested to only use this function
700 /// for performance optimizations where spurious `None` return values by this function do not
701 /// affect the outcome, but just the performance.
702 /// The consequences of using this method to make runtime and compile-time code behave
703 /// differently have not been explored. This method should not be used to introduce such
704 /// differences, and it should also not be stabilized before we have a better understanding
705 /// of this issue.
706 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
707 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
708 #[inline]
709 pub const fn guaranteed_ne(self, other: *mut T) -> Option<bool>
710 where
711 T: Sized,
712 {
713 (self as *const T).guaranteed_ne(other as _)
714 }
715
716 /// Calculates the distance between two pointers within the same allocation. The returned value is in
717 /// units of T: the distance in bytes divided by `size_of::<T>()`.
718 ///
719 /// This is equivalent to `(self as isize - origin as isize) / (size_of::<T>() as isize)`,
720 /// except that it has a lot more opportunities for UB, in exchange for the compiler
721 /// better understanding what you are doing.
722 ///
723 /// The primary motivation of this method is for computing the `len` of an array/slice
724 /// of `T` that you are currently representing as a "start" and "end" pointer
725 /// (and "end" is "one past the end" of the array).
726 /// In that case, `end.offset_from(start)` gets you the length of the array.
727 ///
728 /// All of the following safety requirements are trivially satisfied for this usecase.
729 ///
730 /// [`offset`]: pointer#method.offset-1
731 ///
732 /// # Safety
733 ///
734 /// If any of the following conditions are violated, the result is Undefined Behavior:
735 ///
736 /// * `self` and `origin` must either
737 ///
738 /// * point to the same address, or
739 /// * both be [derived from][crate::ptr#provenance] a pointer to the same [allocation], and the memory range between
740 /// the two pointers must be in bounds of that object. (See below for an example.)
741 ///
742 /// * The distance between the pointers, in bytes, must be an exact multiple
743 /// of the size of `T`.
744 ///
745 /// As a consequence, the absolute distance between the pointers, in bytes, computed on
746 /// mathematical integers (without "wrapping around"), cannot overflow an `isize`. This is
747 /// implied by the in-bounds requirement, and the fact that no allocation can be larger
748 /// than `isize::MAX` bytes.
749 ///
750 /// The requirement for pointers to be derived from the same allocation is primarily
751 /// needed for `const`-compatibility: the distance between pointers into *different* allocated
752 /// objects is not known at compile-time. However, the requirement also exists at
753 /// runtime and may be exploited by optimizations. If you wish to compute the difference between
754 /// pointers that are not guaranteed to be from the same allocation, use
755 /// `(self.addr() as isize - origin.addr() as isize) / size_of::<T>()`.
756 ///
757 /// [`add`]: #method.add
758 /// [allocation]: crate::ptr#allocation
759 ///
760 /// # Panics
761 ///
762 /// This function panics if `T` is a Zero-Sized Type ("ZST").
763 ///
764 /// # Examples
765 ///
766 /// Basic usage:
767 ///
768 /// ```
769 /// let mut a = [0; 5];
770 /// let ptr1: *mut i32 = &mut a[1];
771 /// let ptr2: *mut i32 = &mut a[3];
772 /// unsafe {
773 /// assert_eq!(ptr2.offset_from(ptr1), 2);
774 /// assert_eq!(ptr1.offset_from(ptr2), -2);
775 /// assert_eq!(ptr1.offset(2), ptr2);
776 /// assert_eq!(ptr2.offset(-2), ptr1);
777 /// }
778 /// ```
779 ///
780 /// *Incorrect* usage:
781 ///
782 /// ```rust,no_run
783 /// let ptr1 = Box::into_raw(Box::new(0u8));
784 /// let ptr2 = Box::into_raw(Box::new(1u8));
785 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
786 /// // Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.
787 /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff).wrapping_offset(1);
788 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
789 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
790 /// // computing their offset is undefined behavior, even though
791 /// // they point to addresses that are in-bounds of the same object!
792 /// unsafe {
793 /// let one = ptr2_other.offset_from(ptr2); // Undefined Behavior! ⚠️
794 /// }
795 /// ```
796 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
797 #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
798 #[inline(always)]
799 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
800 pub const unsafe fn offset_from(self, origin: *const T) -> isize
801 where
802 T: Sized,
803 {
804 // SAFETY: the caller must uphold the safety contract for `offset_from`.
805 unsafe { (self as *const T).offset_from(origin) }
806 }
807
808 /// Calculates the distance between two pointers within the same allocation. The returned value is in
809 /// units of **bytes**.
810 ///
811 /// This is purely a convenience for casting to a `u8` pointer and
812 /// using [`offset_from`][pointer::offset_from] on it.
813 ///
814 /// For non-`Sized` pointees this operation considers only the data pointers,
815 /// ignoring the metadata.
816 ///
817 /// # Safety
818 ///
819 /// See [`offset_from`][pointer::offset_from] for documentation and safety requirements.
820 #[inline(always)]
821 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
822 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
823 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
824 pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: *const U) -> isize {
825 // SAFETY: the caller must uphold the safety contract for `offset_from`.
826 unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
827 }
828
829 /// Calculates the distance between two pointers within the same allocation, *where it's known that
830 /// `self` is equal to or greater than `origin`*. The returned value is in
831 /// units of T: the distance in bytes is divided by `size_of::<T>()`.
832 ///
833 /// This computes the same value that [`offset_from`](#method.offset_from)
834 /// would compute, but with the added precondition that the offset is
835 /// guaranteed to be non-negative. This method is equivalent to
836 /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`,
837 /// but it provides slightly more information to the optimizer, which can
838 /// sometimes allow it to optimize slightly better with some backends.
839 ///
840 /// This method can be thought of as recovering the `count` that was passed
841 /// to [`add`](#method.add) (or, with the parameters in the other order,
842 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
843 /// that their safety preconditions are met:
844 /// ```rust
845 /// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool { unsafe {
846 /// ptr.offset_from_unsigned(origin) == count
847 /// # &&
848 /// origin.add(count) == ptr
849 /// # &&
850 /// ptr.sub(count) == origin
851 /// # } }
852 /// ```
853 ///
854 /// # Safety
855 ///
856 /// - The distance between the pointers must be non-negative (`self >= origin`)
857 ///
858 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
859 /// apply to this method as well; see it for the full details.
860 ///
861 /// Importantly, despite the return type of this method being able to represent
862 /// a larger offset, it's still *not permitted* to pass pointers which differ
863 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
864 /// always be less than or equal to `isize::MAX as usize`.
865 ///
866 /// # Panics
867 ///
868 /// This function panics if `T` is a Zero-Sized Type ("ZST").
869 ///
870 /// # Examples
871 ///
872 /// ```
873 /// let mut a = [0; 5];
874 /// let p: *mut i32 = a.as_mut_ptr();
875 /// unsafe {
876 /// let ptr1: *mut i32 = p.add(1);
877 /// let ptr2: *mut i32 = p.add(3);
878 ///
879 /// assert_eq!(ptr2.offset_from_unsigned(ptr1), 2);
880 /// assert_eq!(ptr1.add(2), ptr2);
881 /// assert_eq!(ptr2.sub(2), ptr1);
882 /// assert_eq!(ptr2.offset_from_unsigned(ptr2), 0);
883 /// }
884 ///
885 /// // This would be incorrect, as the pointers are not correctly ordered:
886 /// // ptr1.offset_from(ptr2)
887 /// ```
888 #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
889 #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
890 #[inline]
891 #[track_caller]
892 pub const unsafe fn offset_from_unsigned(self, origin: *const T) -> usize
893 where
894 T: Sized,
895 {
896 // SAFETY: the caller must uphold the safety contract for `offset_from_unsigned`.
897 unsafe { (self as *const T).offset_from_unsigned(origin) }
898 }
899
900 /// Calculates the distance between two pointers within the same allocation, *where it's known that
901 /// `self` is equal to or greater than `origin`*. The returned value is in
902 /// units of **bytes**.
903 ///
904 /// This is purely a convenience for casting to a `u8` pointer and
905 /// using [`offset_from_unsigned`][pointer::offset_from_unsigned] on it.
906 ///
907 /// For non-`Sized` pointees this operation considers only the data pointers,
908 /// ignoring the metadata.
909 ///
910 /// # Safety
911 ///
912 /// See [`offset_from_unsigned`][pointer::offset_from_unsigned] for documentation and safety requirements.
913 #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
914 #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
915 #[inline]
916 #[track_caller]
917 pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: *mut U) -> usize {
918 // SAFETY: the caller must uphold the safety contract for `byte_offset_from_unsigned`.
919 unsafe { (self as *const T).byte_offset_from_unsigned(origin) }
920 }
921
922 #[doc = include_str!("./docs/add.md")]
923 ///
924 /// Consider using [`wrapping_add`](#method.wrapping_add) instead if these constraints are
925 /// difficult to satisfy. The only advantage of this method is that it
926 /// enables more aggressive compiler optimizations.
927 ///
928 /// # Examples
929 ///
930 /// ```
931 /// let mut s: String = "123".to_string();
932 /// let ptr: *mut u8 = s.as_mut_ptr();
933 ///
934 /// unsafe {
935 /// assert_eq!('2', *ptr.add(1) as char);
936 /// assert_eq!('3', *ptr.add(2) as char);
937 /// }
938 /// ```
939 #[stable(feature = "pointer_methods", since = "1.26.0")]
940 #[must_use = "returns a new pointer rather than modifying its argument"]
941 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
942 #[inline(always)]
943 #[track_caller]
944 pub const unsafe fn add(self, count: usize) -> Self
945 where
946 T: Sized,
947 {
948 #[cfg(debug_assertions)]
949 #[inline]
950 #[rustc_allow_const_fn_unstable(const_eval_select)]
951 const fn runtime_add_nowrap(this: *const (), count: usize, size: usize) -> bool {
952 const_eval_select!(
953 @capture { this: *const (), count: usize, size: usize } -> bool:
954 if const {
955 true
956 } else {
957 let Some(byte_offset) = count.checked_mul(size) else {
958 return false;
959 };
960 let (_, overflow) = this.addr().overflowing_add(byte_offset);
961 byte_offset <= (isize::MAX as usize) && !overflow
962 }
963 )
964 }
965
966 #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
967 ub_checks::assert_unsafe_precondition!(
968 check_language_ub,
969 "ptr::add requires that the address calculation does not overflow",
970 (
971 this: *const () = self as *const (),
972 count: usize = count,
973 size: usize = size_of::<T>(),
974 ) => runtime_add_nowrap(this, count, size)
975 );
976
977 // SAFETY: the caller must uphold the safety contract for `offset`.
978 unsafe { intrinsics::offset(self, count) }
979 }
980
981 /// Adds an unsigned offset in bytes to a pointer.
982 ///
983 /// `count` is in units of bytes.
984 ///
985 /// This is purely a convenience for casting to a `u8` pointer and
986 /// using [add][pointer::add] on it.
987 ///
988 /// For non-`Sized` pointees this operation changes only the data pointer,
989 /// leaving the metadata untouched.
990 ///
991 /// # Safety
992 ///
993 /// See [`add`][pointer::add] for documentation and safety requirements.
994 #[must_use]
995 #[inline(always)]
996 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
997 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
998 #[track_caller]
999 pub const unsafe fn byte_add(self, count: usize) -> Self {
1000 // SAFETY: the caller must uphold the safety contract for `add`.
1001 unsafe { self.cast::<u8>().add(count).with_metadata_of(self) }
1002 }
1003
1004 #[doc = include_str!("./docs/sub.md")]
1005 ///
1006 /// Consider using [`wrapping_sub`](#method.wrapping_sub) instead if these constraints are
1007 /// difficult to satisfy. The only advantage of this method is that it
1008 /// enables more aggressive compiler optimizations.
1009 ///
1010 /// # Examples
1011 ///
1012 /// ```
1013 /// let s: &str = "123";
1014 ///
1015 /// unsafe {
1016 /// let end: *const u8 = s.as_ptr().add(3);
1017 /// assert_eq!('3', *end.sub(1) as char);
1018 /// assert_eq!('2', *end.sub(2) as char);
1019 /// }
1020 /// ```
1021 #[stable(feature = "pointer_methods", since = "1.26.0")]
1022 #[must_use = "returns a new pointer rather than modifying its argument"]
1023 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1024 #[inline(always)]
1025 #[track_caller]
1026 pub const unsafe fn sub(self, count: usize) -> Self
1027 where
1028 T: Sized,
1029 {
1030 #[cfg(debug_assertions)]
1031 #[inline]
1032 #[rustc_allow_const_fn_unstable(const_eval_select)]
1033 const fn runtime_sub_nowrap(this: *const (), count: usize, size: usize) -> bool {
1034 const_eval_select!(
1035 @capture { this: *const (), count: usize, size: usize } -> bool:
1036 if const {
1037 true
1038 } else {
1039 let Some(byte_offset) = count.checked_mul(size) else {
1040 return false;
1041 };
1042 byte_offset <= (isize::MAX as usize) && this.addr() >= byte_offset
1043 }
1044 )
1045 }
1046
1047 #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
1048 ub_checks::assert_unsafe_precondition!(
1049 check_language_ub,
1050 "ptr::sub requires that the address calculation does not overflow",
1051 (
1052 this: *const () = self as *const (),
1053 count: usize = count,
1054 size: usize = size_of::<T>(),
1055 ) => runtime_sub_nowrap(this, count, size)
1056 );
1057
1058 if T::IS_ZST {
1059 // Pointer arithmetic does nothing when the pointee is a ZST.
1060 self
1061 } else {
1062 // SAFETY: the caller must uphold the safety contract for `offset`.
1063 // Because the pointee is *not* a ZST, that means that `count` is
1064 // at most `isize::MAX`, and thus the negation cannot overflow.
1065 unsafe { intrinsics::offset(self, intrinsics::unchecked_sub(0, count as isize)) }
1066 }
1067 }
1068
1069 /// Subtracts an unsigned offset in bytes from a pointer.
1070 ///
1071 /// `count` is in units of bytes.
1072 ///
1073 /// This is purely a convenience for casting to a `u8` pointer and
1074 /// using [sub][pointer::sub] on it.
1075 ///
1076 /// For non-`Sized` pointees this operation changes only the data pointer,
1077 /// leaving the metadata untouched.
1078 ///
1079 /// # Safety
1080 ///
1081 /// See [`sub`][pointer::sub] for documentation and safety requirements.
1082 #[must_use]
1083 #[inline(always)]
1084 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1085 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1086 #[track_caller]
1087 pub const unsafe fn byte_sub(self, count: usize) -> Self {
1088 // SAFETY: the caller must uphold the safety contract for `sub`.
1089 unsafe { self.cast::<u8>().sub(count).with_metadata_of(self) }
1090 }
1091
1092 /// Adds an unsigned offset to a pointer using wrapping arithmetic.
1093 ///
1094 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1095 /// offset of `3 * size_of::<T>()` bytes.
1096 ///
1097 /// # Safety
1098 ///
1099 /// This operation itself is always safe, but using the resulting pointer is not.
1100 ///
1101 /// The resulting pointer "remembers" the [allocation] that `self` points to; it must not
1102 /// be used to read or write other allocations.
1103 ///
1104 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1105 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1106 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1107 /// `x` and `y` point into the same allocation.
1108 ///
1109 /// Compared to [`add`], this method basically delays the requirement of staying within the
1110 /// same allocation: [`add`] is immediate Undefined Behavior when crossing object
1111 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1112 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1113 /// can be optimized better and is thus preferable in performance-sensitive code.
1114 ///
1115 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1116 /// intermediate values used during the computation of the final result. For example,
1117 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1118 /// allocation and then re-entering it later is permitted.
1119 ///
1120 /// [`add`]: #method.add
1121 /// [allocation]: crate::ptr#allocation
1122 ///
1123 /// # Examples
1124 ///
1125 /// ```
1126 /// // Iterate using a raw pointer in increments of two elements
1127 /// let data = [1u8, 2, 3, 4, 5];
1128 /// let mut ptr: *const u8 = data.as_ptr();
1129 /// let step = 2;
1130 /// let end_rounded_up = ptr.wrapping_add(6);
1131 ///
1132 /// // This loop prints "1, 3, 5, "
1133 /// while ptr != end_rounded_up {
1134 /// unsafe {
1135 /// print!("{}, ", *ptr);
1136 /// }
1137 /// ptr = ptr.wrapping_add(step);
1138 /// }
1139 /// ```
1140 #[stable(feature = "pointer_methods", since = "1.26.0")]
1141 #[must_use = "returns a new pointer rather than modifying its argument"]
1142 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1143 #[allow(clippy::ptr_offset_with_cast)]
1144 #[inline(always)]
1145 pub const fn wrapping_add(self, count: usize) -> Self
1146 where
1147 T: Sized,
1148 {
1149 self.wrapping_offset(count as isize)
1150 }
1151
1152 /// Adds an unsigned offset in bytes to a pointer using wrapping arithmetic.
1153 ///
1154 /// `count` is in units of bytes.
1155 ///
1156 /// This is purely a convenience for casting to a `u8` pointer and
1157 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1158 ///
1159 /// For non-`Sized` pointees this operation changes only the data pointer,
1160 /// leaving the metadata untouched.
1161 #[must_use]
1162 #[inline(always)]
1163 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1164 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1165 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1166 self.cast::<u8>().wrapping_add(count).with_metadata_of(self)
1167 }
1168
1169 /// Subtracts an unsigned offset from a pointer using wrapping arithmetic.
1170 ///
1171 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1172 /// offset of `3 * size_of::<T>()` bytes.
1173 ///
1174 /// # Safety
1175 ///
1176 /// This operation itself is always safe, but using the resulting pointer is not.
1177 ///
1178 /// The resulting pointer "remembers" the [allocation] that `self` points to; it must not
1179 /// be used to read or write other allocations.
1180 ///
1181 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1182 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1183 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1184 /// `x` and `y` point into the same allocation.
1185 ///
1186 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1187 /// same allocation: [`sub`] is immediate Undefined Behavior when crossing object
1188 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1189 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1190 /// can be optimized better and is thus preferable in performance-sensitive code.
1191 ///
1192 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1193 /// intermediate values used during the computation of the final result. For example,
1194 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1195 /// allocation and then re-entering it later is permitted.
1196 ///
1197 /// [`sub`]: #method.sub
1198 /// [allocation]: crate::ptr#allocation
1199 ///
1200 /// # Examples
1201 ///
1202 /// ```
1203 /// // Iterate using a raw pointer in increments of two elements (backwards)
1204 /// let data = [1u8, 2, 3, 4, 5];
1205 /// let mut ptr: *const u8 = data.as_ptr();
1206 /// let start_rounded_down = ptr.wrapping_sub(2);
1207 /// ptr = ptr.wrapping_add(4);
1208 /// let step = 2;
1209 /// // This loop prints "5, 3, 1, "
1210 /// while ptr != start_rounded_down {
1211 /// unsafe {
1212 /// print!("{}, ", *ptr);
1213 /// }
1214 /// ptr = ptr.wrapping_sub(step);
1215 /// }
1216 /// ```
1217 #[stable(feature = "pointer_methods", since = "1.26.0")]
1218 #[must_use = "returns a new pointer rather than modifying its argument"]
1219 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1220 #[inline(always)]
1221 pub const fn wrapping_sub(self, count: usize) -> Self
1222 where
1223 T: Sized,
1224 {
1225 self.wrapping_offset((count as isize).wrapping_neg())
1226 }
1227
1228 /// Subtracts an unsigned offset in bytes from a pointer using wrapping arithmetic.
1229 ///
1230 /// `count` is in units of bytes.
1231 ///
1232 /// This is purely a convenience for casting to a `u8` pointer and
1233 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1234 ///
1235 /// For non-`Sized` pointees this operation changes only the data pointer,
1236 /// leaving the metadata untouched.
1237 #[must_use]
1238 #[inline(always)]
1239 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1240 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1241 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1242 self.cast::<u8>().wrapping_sub(count).with_metadata_of(self)
1243 }
1244
1245 /// Reads the value from `self` without moving it. This leaves the
1246 /// memory in `self` unchanged.
1247 ///
1248 /// # Safety
1249 ///
1250 /// See [`ptr::read`] for safety concerns and examples.
1251 ///
1252 /// [`ptr::read`]: crate::ptr::read()
1253 #[stable(feature = "pointer_methods", since = "1.26.0")]
1254 #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1255 #[inline(always)]
1256 #[track_caller]
1257 pub const unsafe fn read(self) -> T
1258 where
1259 T: Sized,
1260 {
1261 // SAFETY: the caller must uphold the safety contract for ``.
1262 unsafe { read(self) }
1263 }
1264
1265 /// Performs a volatile read of the value from `self` without moving it. This
1266 /// leaves the memory in `self` unchanged.
1267 ///
1268 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1269 /// to not be elided or reordered by the compiler across other volatile
1270 /// operations.
1271 ///
1272 /// # Safety
1273 ///
1274 /// See [`ptr::read_volatile`] for safety concerns and examples.
1275 ///
1276 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1277 #[stable(feature = "pointer_methods", since = "1.26.0")]
1278 #[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
1279 #[inline(always)]
1280 #[track_caller]
1281 pub const unsafe fn read_volatile(self) -> T
1282 where
1283 T: Sized,
1284 {
1285 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1286 unsafe { read_volatile(self) }
1287 }
1288
1289 /// Reads the value from `self` without moving it. This leaves the
1290 /// memory in `self` unchanged.
1291 ///
1292 /// Unlike `read`, the pointer may be unaligned.
1293 ///
1294 /// # Safety
1295 ///
1296 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1297 ///
1298 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1299 #[stable(feature = "pointer_methods", since = "1.26.0")]
1300 #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1301 #[inline(always)]
1302 #[track_caller]
1303 pub const unsafe fn read_unaligned(self) -> T
1304 where
1305 T: Sized,
1306 {
1307 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1308 unsafe { read_unaligned(self) }
1309 }
1310
1311 /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1312 /// and destination may overlap.
1313 ///
1314 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1315 ///
1316 /// # Safety
1317 ///
1318 /// See [`ptr::copy`] for safety concerns and examples.
1319 ///
1320 /// [`ptr::copy`]: crate::ptr::copy()
1321 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1322 #[stable(feature = "pointer_methods", since = "1.26.0")]
1323 #[inline(always)]
1324 #[track_caller]
1325 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1326 where
1327 T: Sized,
1328 {
1329 // SAFETY: the caller must uphold the safety contract for `copy`.
1330 unsafe { copy(self, dest, count) }
1331 }
1332
1333 /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1334 /// and destination may *not* overlap.
1335 ///
1336 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1337 ///
1338 /// # Safety
1339 ///
1340 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1341 ///
1342 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1343 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1344 #[stable(feature = "pointer_methods", since = "1.26.0")]
1345 #[inline(always)]
1346 #[track_caller]
1347 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1348 where
1349 T: Sized,
1350 {
1351 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1352 unsafe { copy_nonoverlapping(self, dest, count) }
1353 }
1354
1355 /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
1356 /// and destination may overlap.
1357 ///
1358 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1359 ///
1360 /// # Safety
1361 ///
1362 /// See [`ptr::copy`] for safety concerns and examples.
1363 ///
1364 /// [`ptr::copy`]: crate::ptr::copy()
1365 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1366 #[stable(feature = "pointer_methods", since = "1.26.0")]
1367 #[inline(always)]
1368 #[track_caller]
1369 pub const unsafe fn copy_from(self, src: *const T, count: usize)
1370 where
1371 T: Sized,
1372 {
1373 // SAFETY: the caller must uphold the safety contract for `copy`.
1374 unsafe { copy(src, self, count) }
1375 }
1376
1377 /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
1378 /// and destination may *not* overlap.
1379 ///
1380 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1381 ///
1382 /// # Safety
1383 ///
1384 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1385 ///
1386 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1387 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1388 #[stable(feature = "pointer_methods", since = "1.26.0")]
1389 #[inline(always)]
1390 #[track_caller]
1391 pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1392 where
1393 T: Sized,
1394 {
1395 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1396 unsafe { copy_nonoverlapping(src, self, count) }
1397 }
1398
1399 /// Executes the destructor (if any) of the pointed-to value.
1400 ///
1401 /// # Safety
1402 ///
1403 /// See [`ptr::drop_in_place`] for safety concerns and examples.
1404 ///
1405 /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1406 #[stable(feature = "pointer_methods", since = "1.26.0")]
1407 #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
1408 #[rustc_diagnostic_item = "ptr_drop_in_place_self"]
1409 #[inline(always)]
1410 pub const unsafe fn drop_in_place(self)
1411 where
1412 T: [const] Destruct,
1413 {
1414 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1415 unsafe { drop_in_place(self) }
1416 }
1417
1418 /// Overwrites a memory location with the given value without reading or
1419 /// dropping the old value.
1420 ///
1421 /// # Safety
1422 ///
1423 /// See [`ptr::write`] for safety concerns and examples.
1424 ///
1425 /// [`ptr::write`]: crate::ptr::write()
1426 #[stable(feature = "pointer_methods", since = "1.26.0")]
1427 #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1428 #[inline(always)]
1429 #[track_caller]
1430 pub const unsafe fn write(self, val: T)
1431 where
1432 T: Sized,
1433 {
1434 // SAFETY: the caller must uphold the safety contract for `write`.
1435 unsafe { write(self, val) }
1436 }
1437
1438 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1439 /// bytes of memory starting at `self` to `val`.
1440 ///
1441 /// # Safety
1442 ///
1443 /// See [`ptr::write_bytes`] for safety concerns and examples.
1444 ///
1445 /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1446 #[doc(alias = "memset")]
1447 #[stable(feature = "pointer_methods", since = "1.26.0")]
1448 #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1449 #[inline(always)]
1450 #[track_caller]
1451 pub const unsafe fn write_bytes(self, val: u8, count: usize)
1452 where
1453 T: Sized,
1454 {
1455 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1456 unsafe { write_bytes(self, val, count) }
1457 }
1458
1459 /// Performs a volatile write of a memory location with the given value without
1460 /// reading or dropping the old value.
1461 ///
1462 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1463 /// to not be elided or reordered by the compiler across other volatile
1464 /// operations.
1465 ///
1466 /// # Safety
1467 ///
1468 /// See [`ptr::write_volatile`] for safety concerns and examples.
1469 ///
1470 /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1471 #[stable(feature = "pointer_methods", since = "1.26.0")]
1472 #[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
1473 #[inline(always)]
1474 #[track_caller]
1475 pub const unsafe fn write_volatile(self, val: T)
1476 where
1477 T: Sized,
1478 {
1479 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1480 unsafe { write_volatile(self, val) }
1481 }
1482
1483 /// Overwrites a memory location with the given value without reading or
1484 /// dropping the old value.
1485 ///
1486 /// Unlike `write`, the pointer may be unaligned.
1487 ///
1488 /// # Safety
1489 ///
1490 /// See [`ptr::write_unaligned`] for safety concerns and examples.
1491 ///
1492 /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1493 #[stable(feature = "pointer_methods", since = "1.26.0")]
1494 #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1495 #[inline(always)]
1496 #[track_caller]
1497 pub const unsafe fn write_unaligned(self, val: T)
1498 where
1499 T: Sized,
1500 {
1501 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1502 unsafe { write_unaligned(self, val) }
1503 }
1504
1505 /// Replaces the value at `self` with `src`, returning the old
1506 /// value, without dropping either.
1507 ///
1508 /// # Safety
1509 ///
1510 /// See [`ptr::replace`] for safety concerns and examples.
1511 ///
1512 /// [`ptr::replace`]: crate::ptr::replace()
1513 #[stable(feature = "pointer_methods", since = "1.26.0")]
1514 #[rustc_const_stable(feature = "const_inherent_ptr_replace", since = "1.88.0")]
1515 #[inline(always)]
1516 pub const unsafe fn replace(self, src: T) -> T
1517 where
1518 T: Sized,
1519 {
1520 // SAFETY: the caller must uphold the safety contract for `replace`.
1521 unsafe { replace(self, src) }
1522 }
1523
1524 /// Swaps the values at two mutable locations of the same type, without
1525 /// deinitializing either. They may overlap, unlike `mem::swap` which is
1526 /// otherwise equivalent.
1527 ///
1528 /// # Safety
1529 ///
1530 /// See [`ptr::swap`] for safety concerns and examples.
1531 ///
1532 /// [`ptr::swap`]: crate::ptr::swap()
1533 #[stable(feature = "pointer_methods", since = "1.26.0")]
1534 #[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
1535 #[inline(always)]
1536 pub const unsafe fn swap(self, with: *mut T)
1537 where
1538 T: Sized,
1539 {
1540 // SAFETY: the caller must uphold the safety contract for `swap`.
1541 unsafe { swap(self, with) }
1542 }
1543
1544 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1545 /// `align`.
1546 ///
1547 /// If it is not possible to align the pointer, the implementation returns
1548 /// `usize::MAX`.
1549 ///
1550 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1551 /// used with the `wrapping_add` method.
1552 ///
1553 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1554 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1555 /// the returned offset is correct in all terms other than alignment.
1556 ///
1557 /// # Panics
1558 ///
1559 /// The function panics if `align` is not a power-of-two.
1560 ///
1561 /// # Examples
1562 ///
1563 /// Accessing adjacent `u8` as `u16`
1564 ///
1565 /// ```
1566 /// # unsafe {
1567 /// let mut x = [5_u8, 6, 7, 8, 9];
1568 /// let ptr = x.as_mut_ptr();
1569 /// let offset = ptr.align_offset(align_of::<u16>());
1570 ///
1571 /// if offset < x.len() - 1 {
1572 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1573 /// *u16_ptr = 0;
1574 ///
1575 /// assert!(x == [0, 0, 7, 8, 9] || x == [5, 0, 0, 8, 9]);
1576 /// } else {
1577 /// // while the pointer can be aligned via `offset`, it would point
1578 /// // outside the allocation
1579 /// }
1580 /// # }
1581 /// ```
1582 #[must_use]
1583 #[inline]
1584 #[stable(feature = "align_offset", since = "1.36.0")]
1585 pub fn align_offset(self, align: usize) -> usize
1586 where
1587 T: Sized,
1588 {
1589 if !align.is_power_of_two() {
1590 panic!("align_offset: align is not a power-of-two");
1591 }
1592
1593 // SAFETY: `align` has been checked to be a power of 2 above
1594 let ret = unsafe { align_offset(self, align) };
1595
1596 // Inform Miri that we want to consider the resulting pointer to be suitably aligned.
1597 #[cfg(miri)]
1598 if ret != usize::MAX {
1599 intrinsics::miri_promise_symbolic_alignment(
1600 self.wrapping_add(ret).cast_const().cast(),
1601 align,
1602 );
1603 }
1604
1605 ret
1606 }
1607
1608 /// Returns whether the pointer is properly aligned for `T`.
1609 ///
1610 /// # Examples
1611 ///
1612 /// ```
1613 /// // On some platforms, the alignment of i32 is less than 4.
1614 /// #[repr(align(4))]
1615 /// struct AlignedI32(i32);
1616 ///
1617 /// let mut data = AlignedI32(42);
1618 /// let ptr = &mut data as *mut AlignedI32;
1619 ///
1620 /// assert!(ptr.is_aligned());
1621 /// assert!(!ptr.wrapping_byte_add(1).is_aligned());
1622 /// ```
1623 #[must_use]
1624 #[inline]
1625 #[stable(feature = "pointer_is_aligned", since = "1.79.0")]
1626 pub fn is_aligned(self) -> bool
1627 where
1628 T: Sized,
1629 {
1630 self.is_aligned_to(align_of::<T>())
1631 }
1632
1633 /// Returns whether the pointer is aligned to `align`.
1634 ///
1635 /// For non-`Sized` pointees this operation considers only the data pointer,
1636 /// ignoring the metadata.
1637 ///
1638 /// # Panics
1639 ///
1640 /// The function panics if `align` is not a power-of-two (this includes 0).
1641 ///
1642 /// # Examples
1643 ///
1644 /// ```
1645 /// #![feature(pointer_is_aligned_to)]
1646 ///
1647 /// // On some platforms, the alignment of i32 is less than 4.
1648 /// #[repr(align(4))]
1649 /// struct AlignedI32(i32);
1650 ///
1651 /// let mut data = AlignedI32(42);
1652 /// let ptr = &mut data as *mut AlignedI32;
1653 ///
1654 /// assert!(ptr.is_aligned_to(1));
1655 /// assert!(ptr.is_aligned_to(2));
1656 /// assert!(ptr.is_aligned_to(4));
1657 ///
1658 /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1659 /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1660 ///
1661 /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1662 /// ```
1663 #[must_use]
1664 #[inline]
1665 #[unstable(feature = "pointer_is_aligned_to", issue = "96284")]
1666 pub fn is_aligned_to(self, align: usize) -> bool {
1667 if !align.is_power_of_two() {
1668 panic!("is_aligned_to: align is not a power-of-two");
1669 }
1670
1671 self.addr() & (align - 1) == 0
1672 }
1673}
1674
1675impl<T> *mut T {
1676 /// Casts from a type to its maybe-uninitialized version.
1677 ///
1678 /// This is always safe, since UB can only occur if the pointer is read
1679 /// before being initialized.
1680 #[must_use]
1681 #[inline(always)]
1682 #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1683 pub const fn cast_uninit(self) -> *mut MaybeUninit<T> {
1684 self as _
1685 }
1686
1687 /// Forms a raw mutable slice from a pointer and a length.
1688 ///
1689 /// The `len` argument is the number of **elements**, not the number of bytes.
1690 ///
1691 /// Performs the same functionality as [`cast_slice`] on a `*const T`, except that a
1692 /// raw mutable slice is returned, as opposed to a raw immutable slice.
1693 ///
1694 /// See [`ptr::slice_from_raw_parts`] for more information.
1695 ///
1696 /// [`ptr::slice_from_raw_parts`]: crate::ptr::slice_from_raw_parts
1697 /// [`cast_slice`]: pointer::cast_slice
1698 ///
1699 /// # Examples
1700 ///
1701 /// ```rust
1702 /// let x = &mut [5, 6, 7];
1703 /// let raw_mut_slice = x.as_mut_ptr().cast_slice(3);
1704 ///
1705 /// unsafe {
1706 /// (*raw_mut_slice)[2] = 99; // assign a value at an index in the slice
1707 /// };
1708 ///
1709 /// assert_eq!(unsafe { &*raw_mut_slice }[2], 99);
1710 /// ```
1711 ///
1712 /// You must ensure that the pointer is valid and not null before dereferencing
1713 /// the raw slice. A slice reference must never have a null pointer, even if it's empty.
1714 ///
1715 /// ```rust,should_panic
1716 /// use std::ptr;
1717 /// let danger: *mut [u8] = ptr::null_mut::<u8>().cast_slice(0);
1718 /// unsafe {
1719 /// danger.as_mut().expect("references must not be null");
1720 /// }
1721 /// ```
1722 #[inline]
1723 #[stable(feature = "ptr_cast_slice", since = "1.101.0")]
1724 #[rustc_const_stable(feature = "ptr_cast_slice", since = "1.101.0")]
1725 pub const fn cast_slice(self, len: usize) -> *mut [T] {
1726 slice_from_raw_parts_mut(self, len)
1727 }
1728}
1729
1730impl<T> *mut MaybeUninit<T> {
1731 /// Casts from a maybe-uninitialized type to its initialized version.
1732 ///
1733 /// This is always safe, since UB can only occur if the pointer is read
1734 /// before being initialized.
1735 #[must_use]
1736 #[inline(always)]
1737 #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1738 pub const fn cast_init(self) -> *mut T {
1739 self as _
1740 }
1741}
1742
1743impl<T> *mut [T] {
1744 /// Returns the length of a raw slice.
1745 ///
1746 /// The returned value is the number of **elements**, not the number of bytes.
1747 ///
1748 /// This function is safe, even when the raw slice cannot be cast to a slice
1749 /// reference because the pointer is null or unaligned.
1750 ///
1751 /// # Examples
1752 ///
1753 /// ```rust
1754 /// use std::ptr;
1755 ///
1756 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1757 /// assert_eq!(slice.len(), 3);
1758 /// ```
1759 #[inline(always)]
1760 #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1761 #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1762 pub const fn len(self) -> usize {
1763 metadata(self)
1764 }
1765
1766 /// Returns `true` if the raw slice has a length of 0.
1767 ///
1768 /// # Examples
1769 ///
1770 /// ```
1771 /// use std::ptr;
1772 ///
1773 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1774 /// assert!(!slice.is_empty());
1775 /// ```
1776 #[inline(always)]
1777 #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1778 #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1779 pub const fn is_empty(self) -> bool {
1780 self.len() == 0
1781 }
1782
1783 /// Gets a raw, mutable pointer to the underlying array.
1784 ///
1785 /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
1786 #[stable(feature = "core_slice_as_array", since = "1.93.0")]
1787 #[rustc_const_stable(feature = "core_slice_as_array", since = "1.93.0")]
1788 #[inline]
1789 #[must_use]
1790 pub const fn as_mut_array<const N: usize>(self) -> Option<*mut [T; N]> {
1791 if self.len() == N {
1792 let me = self.as_mut_ptr() as *mut [T; N];
1793 Some(me)
1794 } else {
1795 None
1796 }
1797 }
1798
1799 /// Divides one mutable raw slice into two at an index.
1800 ///
1801 /// The first will contain all indices from `[0, mid)` (excluding
1802 /// the index `mid` itself) and the second will contain all
1803 /// indices from `[mid, len)` (excluding the index `len` itself).
1804 ///
1805 /// # Panics
1806 ///
1807 /// Panics if `mid > len`.
1808 ///
1809 /// # Safety
1810 ///
1811 /// `mid` must be [in-bounds] of the underlying [allocation].
1812 /// Which means `self` must be dereferenceable and span a single allocation
1813 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1814 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1815 ///
1816 /// Since `len` being in-bounds is not a safety invariant of `*mut [T]` the
1817 /// safety requirements of this method are the same as for [`split_at_mut_unchecked`].
1818 /// The explicit bounds check is only as useful as `len` is correct.
1819 ///
1820 /// [`split_at_mut_unchecked`]: #method.split_at_mut_unchecked
1821 /// [in-bounds]: #method.add
1822 /// [allocation]: crate::ptr#allocation
1823 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1824 ///
1825 /// # Examples
1826 ///
1827 /// ```
1828 /// #![feature(raw_slice_split)]
1829 ///
1830 /// let mut v = [1, 0, 3, 0, 5, 6];
1831 /// let ptr = &mut v as *mut [_];
1832 /// unsafe {
1833 /// let (left, right) = ptr.split_at_mut(2);
1834 /// assert_eq!(&*left, [1, 0]);
1835 /// assert_eq!(&*right, [3, 0, 5, 6]);
1836 /// }
1837 /// ```
1838 #[inline(always)]
1839 #[track_caller]
1840 #[unstable(feature = "raw_slice_split", issue = "95595")]
1841 pub unsafe fn split_at_mut(self, mid: usize) -> (*mut [T], *mut [T]) {
1842 assert!(mid <= self.len());
1843 // SAFETY: The assert above is only a safety-net as long as `self.len()` is correct
1844 // The actual safety requirements of this function are the same as for `split_at_mut_unchecked`
1845 unsafe { self.split_at_mut_unchecked(mid) }
1846 }
1847
1848 /// Divides one mutable raw slice into two at an index, without doing bounds checking.
1849 ///
1850 /// The first will contain all indices from `[0, mid)` (excluding
1851 /// the index `mid` itself) and the second will contain all
1852 /// indices from `[mid, len)` (excluding the index `len` itself).
1853 ///
1854 /// # Safety
1855 ///
1856 /// `mid` must be [in-bounds] of the underlying [allocation].
1857 /// Which means `self` must be dereferenceable and span a single allocation
1858 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1859 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1860 ///
1861 /// [in-bounds]: #method.add
1862 /// [out-of-bounds index]: #method.add
1863 /// [allocation]: crate::ptr#allocation
1864 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1865 ///
1866 /// # Examples
1867 ///
1868 /// ```
1869 /// #![feature(raw_slice_split)]
1870 ///
1871 /// let mut v = [1, 0, 3, 0, 5, 6];
1872 /// // scoped to restrict the lifetime of the borrows
1873 /// unsafe {
1874 /// let ptr = &mut v as *mut [_];
1875 /// let (left, right) = ptr.split_at_mut_unchecked(2);
1876 /// assert_eq!(&*left, [1, 0]);
1877 /// assert_eq!(&*right, [3, 0, 5, 6]);
1878 /// (&mut *left)[1] = 2;
1879 /// (&mut *right)[1] = 4;
1880 /// }
1881 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1882 /// ```
1883 #[inline(always)]
1884 #[unstable(feature = "raw_slice_split", issue = "95595")]
1885 pub unsafe fn split_at_mut_unchecked(self, mid: usize) -> (*mut [T], *mut [T]) {
1886 let len = self.len();
1887 let ptr = self.as_mut_ptr();
1888
1889 // SAFETY: Caller must pass a valid pointer and an index that is in-bounds.
1890 let tail = unsafe { ptr.add(mid) };
1891 (
1892 crate::ptr::slice_from_raw_parts_mut(ptr, mid),
1893 crate::ptr::slice_from_raw_parts_mut(tail, len - mid),
1894 )
1895 }
1896
1897 /// Returns a raw pointer to the slice's buffer.
1898 ///
1899 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
1900 ///
1901 /// # Examples
1902 ///
1903 /// ```rust
1904 /// #![feature(slice_ptr_get)]
1905 /// use std::ptr;
1906 ///
1907 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1908 /// assert_eq!(slice.as_mut_ptr(), ptr::null_mut());
1909 /// ```
1910 #[inline(always)]
1911 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1912 pub const fn as_mut_ptr(self) -> *mut T {
1913 self as *mut T
1914 }
1915
1916 /// Returns a raw pointer to an element or subslice, without doing bounds
1917 /// checking.
1918 ///
1919 /// # Safety
1920 ///
1921 /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
1922 /// is *[undefined behavior]* even if the resulting pointer is not used.
1923 ///
1924 /// [out-of-bounds index]: #method.add
1925 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1926 ///
1927 /// # Examples
1928 ///
1929 /// ```
1930 /// #![feature(slice_ptr_get)]
1931 ///
1932 /// let x = &mut [1, 2, 4] as *mut [i32];
1933 ///
1934 /// unsafe {
1935 /// assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
1936 /// }
1937 /// ```
1938 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1939 #[rustc_const_unstable(feature = "const_index", issue = "143775")]
1940 #[inline(always)]
1941 pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
1942 where
1943 I: [const] SliceIndex<[T]>,
1944 {
1945 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1946 unsafe { index.get_unchecked_mut(self) }
1947 }
1948
1949 #[doc = include_str!("docs/as_uninit_slice.md")]
1950 ///
1951 /// # See Also
1952 /// For the mutable counterpart see [`as_uninit_slice_mut`](pointer::as_uninit_slice_mut).
1953 #[inline]
1954 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1955 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1956 if self.is_null() {
1957 None
1958 } else {
1959 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1960 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1961 }
1962 }
1963
1964 /// Returns `None` if the pointer is null, or else returns a unique slice to
1965 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
1966 /// that the value has to be initialized.
1967 ///
1968 /// For the shared counterpart see [`as_uninit_slice`].
1969 ///
1970 /// [`as_mut`]: #method.as_mut
1971 /// [`as_uninit_slice`]: #method.as_uninit_slice-1
1972 ///
1973 /// # Safety
1974 ///
1975 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1976 /// all of the following is true:
1977 ///
1978 /// * The pointer must be [valid] for reads and writes for `ptr.len() * size_of::<T>()`
1979 /// many bytes, and it must be properly aligned. This means in particular:
1980 ///
1981 /// * The entire memory range of this slice must be contained within a single [allocation]!
1982 /// Slices can never span across multiple allocations.
1983 ///
1984 /// * The pointer must be aligned even for zero-length slices. One
1985 /// reason for this is that enum layout optimizations may rely on references
1986 /// (including slices of any length) being aligned and non-null to distinguish
1987 /// them from other data. You can obtain a pointer that is usable as `data`
1988 /// for zero-length slices using [`NonNull::dangling()`].
1989 ///
1990 /// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1991 /// See the safety documentation of [`pointer::offset`].
1992 ///
1993 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1994 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1995 /// In particular, while this reference exists, the memory the pointer points to must
1996 /// not get accessed (read or written) through any other pointer.
1997 ///
1998 /// This applies even if the result of this method is unused!
1999 ///
2000 /// See also [`slice::from_raw_parts_mut`][].
2001 ///
2002 /// [valid]: crate::ptr#safety
2003 /// [allocation]: crate::ptr#allocation
2004 ///
2005 /// # Panics during const evaluation
2006 ///
2007 /// This method will panic during const evaluation if the pointer cannot be
2008 /// determined to be null or not. See [`is_null`] for more information.
2009 ///
2010 /// [`is_null`]: #method.is_null-1
2011 #[inline]
2012 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
2013 pub const unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
2014 if self.is_null() {
2015 None
2016 } else {
2017 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
2018 Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
2019 }
2020 }
2021}
2022
2023impl<T> *mut T {
2024 /// Casts from a pointer-to-`T` to a pointer-to-`[T; N]`.
2025 #[inline]
2026 #[unstable(feature = "ptr_cast_array", issue = "144514")]
2027 pub const fn cast_array<const N: usize>(self) -> *mut [T; N] {
2028 self.cast()
2029 }
2030}
2031
2032impl<T, const N: usize> *mut [T; N] {
2033 /// Returns a raw pointer to the array's buffer.
2034 ///
2035 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
2036 ///
2037 /// # Examples
2038 ///
2039 /// ```rust
2040 /// #![feature(array_ptr_get)]
2041 /// use std::ptr;
2042 ///
2043 /// let arr: *mut [i8; 3] = ptr::null_mut();
2044 /// assert_eq!(arr.as_mut_ptr(), ptr::null_mut());
2045 /// ```
2046 #[inline]
2047 #[unstable(feature = "array_ptr_get", issue = "119834")]
2048 pub const fn as_mut_ptr(self) -> *mut T {
2049 self as *mut T
2050 }
2051
2052 /// Returns a raw pointer to a mutable slice containing the entire array.
2053 ///
2054 /// # Examples
2055 ///
2056 /// ```
2057 /// #![feature(array_ptr_get)]
2058 ///
2059 /// let mut arr = [1, 2, 5];
2060 /// let ptr: *mut [i32; 3] = &mut arr;
2061 /// unsafe {
2062 /// (&mut *ptr.as_mut_slice())[..2].copy_from_slice(&[3, 4]);
2063 /// }
2064 /// assert_eq!(arr, [3, 4, 5]);
2065 /// ```
2066 #[inline]
2067 #[unstable(feature = "array_ptr_get", issue = "119834")]
2068 pub const fn as_mut_slice(self) -> *mut [T] {
2069 self
2070 }
2071}
2072
2073/// For thin pointers, equality is by address, as produced by the [`<*mut T>::addr`](pointer::addr) method.
2074#[stable(feature = "rust1", since = "1.0.0")]
2075#[diagnostic::on_const(
2076 message = "pointers cannot be reliably compared during const eval",
2077 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2078)]
2079impl<T: PointeeSized> PartialEq for *mut T {
2080 #[inline(always)]
2081 #[allow(ambiguous_wide_pointer_comparisons)]
2082 fn eq(&self, other: &*mut T) -> bool {
2083 *self == *other
2084 }
2085}
2086
2087/// Pointer equality is an equivalence relation.
2088#[stable(feature = "rust1", since = "1.0.0")]
2089#[diagnostic::on_const(
2090 message = "pointers cannot be reliably compared during const eval",
2091 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2092)]
2093impl<T: PointeeSized> Eq for *mut T {}
2094
2095/// For thin pointers, comparison is by address, as produced by the [`<*mut T>::addr`](pointer::addr) method.
2096#[stable(feature = "rust1", since = "1.0.0")]
2097#[diagnostic::on_const(
2098 message = "pointers cannot be reliably compared during const eval",
2099 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2100)]
2101impl<T: PointeeSized> Ord for *mut T {
2102 #[inline]
2103 #[allow(ambiguous_wide_pointer_comparisons)]
2104 fn cmp(&self, other: &*mut T) -> Ordering {
2105 if self < other {
2106 Less
2107 } else if self == other {
2108 Equal
2109 } else {
2110 Greater
2111 }
2112 }
2113}
2114
2115/// For thin pointers, comparison is by address, as produced by the [`<*mut T>::addr`](pointer::addr) method.
2116#[stable(feature = "rust1", since = "1.0.0")]
2117#[diagnostic::on_const(
2118 message = "pointers cannot be reliably compared during const eval",
2119 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2120)]
2121impl<T: PointeeSized> PartialOrd for *mut T {
2122 #[inline(always)]
2123 #[allow(ambiguous_wide_pointer_comparisons)]
2124 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2125 Some(self.cmp(other))
2126 }
2127
2128 #[inline(always)]
2129 #[allow(ambiguous_wide_pointer_comparisons)]
2130 fn lt(&self, other: &*mut T) -> bool {
2131 *self < *other
2132 }
2133
2134 #[inline(always)]
2135 #[allow(ambiguous_wide_pointer_comparisons)]
2136 fn le(&self, other: &*mut T) -> bool {
2137 *self <= *other
2138 }
2139
2140 #[inline(always)]
2141 #[allow(ambiguous_wide_pointer_comparisons)]
2142 fn gt(&self, other: &*mut T) -> bool {
2143 *self > *other
2144 }
2145
2146 #[inline(always)]
2147 #[allow(ambiguous_wide_pointer_comparisons)]
2148 fn ge(&self, other: &*mut T) -> bool {
2149 *self >= *other
2150 }
2151}
2152
2153#[stable(feature = "raw_ptr_default", since = "1.88.0")]
2154impl<T: ?Sized + Thin> Default for *mut T {
2155 /// Returns the default value of [`null_mut()`][crate::ptr::null_mut].
2156 fn default() -> Self {
2157 crate::ptr::null_mut()
2158 }
2159}