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