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