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