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