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