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