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