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