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