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