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