core/ptr/mut_ptr.rs
1use super::*;
2use crate::cmp::Ordering::{Equal, Greater, Less};
3use crate::intrinsics::const_eval_select;
4use crate::mem::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 `mem::size_of::<T>()`.
773 ///
774 /// This is equivalent to `(self as isize - origin as isize) / (mem::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) / mem::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 `mem::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 /// # #![feature(ptr_sub_ptr)]
899 /// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool {
900 /// ptr.sub_ptr(origin) == count
901 /// # &&
902 /// origin.add(count) == ptr
903 /// # &&
904 /// ptr.sub(count) == origin
905 /// # }
906 /// ```
907 ///
908 /// # Safety
909 ///
910 /// - The distance between the pointers must be non-negative (`self >= origin`)
911 ///
912 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
913 /// apply to this method as well; see it for the full details.
914 ///
915 /// Importantly, despite the return type of this method being able to represent
916 /// a larger offset, it's still *not permitted* to pass pointers which differ
917 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
918 /// always be less than or equal to `isize::MAX as usize`.
919 ///
920 /// # Panics
921 ///
922 /// This function panics if `T` is a Zero-Sized Type ("ZST").
923 ///
924 /// # Examples
925 ///
926 /// ```
927 /// #![feature(ptr_sub_ptr)]
928 ///
929 /// let mut a = [0; 5];
930 /// let p: *mut i32 = a.as_mut_ptr();
931 /// unsafe {
932 /// let ptr1: *mut i32 = p.add(1);
933 /// let ptr2: *mut i32 = p.add(3);
934 ///
935 /// assert_eq!(ptr2.sub_ptr(ptr1), 2);
936 /// assert_eq!(ptr1.add(2), ptr2);
937 /// assert_eq!(ptr2.sub(2), ptr1);
938 /// assert_eq!(ptr2.sub_ptr(ptr2), 0);
939 /// }
940 ///
941 /// // This would be incorrect, as the pointers are not correctly ordered:
942 /// // ptr1.offset_from(ptr2)
943 #[unstable(feature = "ptr_sub_ptr", issue = "95892")]
944 #[rustc_const_unstable(feature = "const_ptr_sub_ptr", issue = "95892")]
945 #[inline]
946 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
947 pub const unsafe fn sub_ptr(self, origin: *const T) -> usize
948 where
949 T: Sized,
950 {
951 // SAFETY: the caller must uphold the safety contract for `sub_ptr`.
952 unsafe { (self as *const T).sub_ptr(origin) }
953 }
954
955 /// Calculates the distance between two pointers within the same allocation, *where it's known that
956 /// `self` is equal to or greater than `origin`*. The returned value is in
957 /// units of **bytes**.
958 ///
959 /// This is purely a convenience for casting to a `u8` pointer and
960 /// using [`sub_ptr`][pointer::sub_ptr] on it. See that method for
961 /// documentation and safety requirements.
962 ///
963 /// For non-`Sized` pointees this operation considers only the data pointers,
964 /// ignoring the metadata.
965 #[unstable(feature = "ptr_sub_ptr", issue = "95892")]
966 #[rustc_const_unstable(feature = "const_ptr_sub_ptr", issue = "95892")]
967 #[inline]
968 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
969 pub const unsafe fn byte_sub_ptr<U: ?Sized>(self, origin: *mut U) -> usize {
970 // SAFETY: the caller must uphold the safety contract for `byte_sub_ptr`.
971 unsafe { (self as *const T).byte_sub_ptr(origin) }
972 }
973
974 /// Adds an unsigned offset to a pointer.
975 ///
976 /// This can only move the pointer forward (or not move it). If you need to move forward or
977 /// backward depending on the value, then you might want [`offset`](#method.offset) instead
978 /// which takes a signed offset.
979 ///
980 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
981 /// offset of `3 * size_of::<T>()` bytes.
982 ///
983 /// # Safety
984 ///
985 /// If any of the following conditions are violated, the result is Undefined Behavior:
986 ///
987 /// * The offset in bytes, `count * size_of::<T>()`, computed on mathematical integers (without
988 /// "wrapping around"), must fit in an `isize`.
989 ///
990 /// * If the computed offset is non-zero, then `self` must be [derived from][crate::ptr#provenance] a pointer to some
991 /// [allocated object], and the entire memory range between `self` and the result must be in
992 /// bounds of that allocated object. In particular, this range must not "wrap around" the edge
993 /// of the address space.
994 ///
995 /// Allocated objects can never be larger than `isize::MAX` bytes, so if the computed offset
996 /// stays in bounds of the allocated object, it is guaranteed to satisfy the first requirement.
997 /// This implies, for instance, that `vec.as_ptr().add(vec.len())` (for `vec: Vec<T>`) is always
998 /// safe.
999 ///
1000 /// Consider using [`wrapping_add`] instead if these constraints are
1001 /// difficult to satisfy. The only advantage of this method is that it
1002 /// enables more aggressive compiler optimizations.
1003 ///
1004 /// [`wrapping_add`]: #method.wrapping_add
1005 /// [allocated object]: crate::ptr#allocated-object
1006 ///
1007 /// # Examples
1008 ///
1009 /// ```
1010 /// let s: &str = "123";
1011 /// let ptr: *const u8 = s.as_ptr();
1012 ///
1013 /// unsafe {
1014 /// assert_eq!('2', *ptr.add(1) as char);
1015 /// assert_eq!('3', *ptr.add(2) as char);
1016 /// }
1017 /// ```
1018 #[stable(feature = "pointer_methods", since = "1.26.0")]
1019 #[must_use = "returns a new pointer rather than modifying its argument"]
1020 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1021 #[inline(always)]
1022 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1023 pub const unsafe fn add(self, count: usize) -> Self
1024 where
1025 T: Sized,
1026 {
1027 #[cfg(debug_assertions)]
1028 #[inline]
1029 #[rustc_allow_const_fn_unstable(const_eval_select)]
1030 const fn runtime_add_nowrap(this: *const (), count: usize, size: usize) -> bool {
1031 const_eval_select!(
1032 @capture { this: *const (), count: usize, size: usize } -> bool:
1033 if const {
1034 true
1035 } else {
1036 let Some(byte_offset) = count.checked_mul(size) else {
1037 return false;
1038 };
1039 let (_, overflow) = this.addr().overflowing_add(byte_offset);
1040 byte_offset <= (isize::MAX as usize) && !overflow
1041 }
1042 )
1043 }
1044
1045 #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
1046 ub_checks::assert_unsafe_precondition!(
1047 check_language_ub,
1048 "ptr::add requires that the address calculation does not overflow",
1049 (
1050 this: *const () = self as *const (),
1051 count: usize = count,
1052 size: usize = size_of::<T>(),
1053 ) => runtime_add_nowrap(this, count, size)
1054 );
1055
1056 // SAFETY: the caller must uphold the safety contract for `offset`.
1057 unsafe { intrinsics::offset(self, count) }
1058 }
1059
1060 /// Adds an unsigned offset in bytes to a pointer.
1061 ///
1062 /// `count` is in units of bytes.
1063 ///
1064 /// This is purely a convenience for casting to a `u8` pointer and
1065 /// using [add][pointer::add] on it. See that method for documentation
1066 /// and safety requirements.
1067 ///
1068 /// For non-`Sized` pointees this operation changes only the data pointer,
1069 /// leaving the metadata untouched.
1070 #[must_use]
1071 #[inline(always)]
1072 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1073 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1074 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1075 pub const unsafe fn byte_add(self, count: usize) -> Self {
1076 // SAFETY: the caller must uphold the safety contract for `add`.
1077 unsafe { self.cast::<u8>().add(count).with_metadata_of(self) }
1078 }
1079
1080 /// Subtracts an unsigned offset from a pointer.
1081 ///
1082 /// This can only move the pointer backward (or not move it). If you need to move forward or
1083 /// backward depending on the value, then you might want [`offset`](#method.offset) instead
1084 /// which takes a signed offset.
1085 ///
1086 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1087 /// offset of `3 * size_of::<T>()` bytes.
1088 ///
1089 /// # Safety
1090 ///
1091 /// If any of the following conditions are violated, the result is Undefined Behavior:
1092 ///
1093 /// * The offset in bytes, `count * size_of::<T>()`, computed on mathematical integers (without
1094 /// "wrapping around"), must fit in an `isize`.
1095 ///
1096 /// * If the computed offset is non-zero, then `self` must be [derived from][crate::ptr#provenance] a pointer to some
1097 /// [allocated object], and the entire memory range between `self` and the result must be in
1098 /// bounds of that allocated object. In particular, this range must not "wrap around" the edge
1099 /// of the address space.
1100 ///
1101 /// Allocated objects can never be larger than `isize::MAX` bytes, so if the computed offset
1102 /// stays in bounds of the allocated object, it is guaranteed to satisfy the first requirement.
1103 /// This implies, for instance, that `vec.as_ptr().add(vec.len())` (for `vec: Vec<T>`) is always
1104 /// safe.
1105 ///
1106 /// Consider using [`wrapping_sub`] instead if these constraints are
1107 /// difficult to satisfy. The only advantage of this method is that it
1108 /// enables more aggressive compiler optimizations.
1109 ///
1110 /// [`wrapping_sub`]: #method.wrapping_sub
1111 /// [allocated object]: crate::ptr#allocated-object
1112 ///
1113 /// # Examples
1114 ///
1115 /// ```
1116 /// let s: &str = "123";
1117 ///
1118 /// unsafe {
1119 /// let end: *const u8 = s.as_ptr().add(3);
1120 /// assert_eq!('3', *end.sub(1) as char);
1121 /// assert_eq!('2', *end.sub(2) as char);
1122 /// }
1123 /// ```
1124 #[stable(feature = "pointer_methods", since = "1.26.0")]
1125 #[must_use = "returns a new pointer rather than modifying its argument"]
1126 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1127 #[inline(always)]
1128 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1129 pub const unsafe fn sub(self, count: usize) -> Self
1130 where
1131 T: Sized,
1132 {
1133 #[cfg(debug_assertions)]
1134 #[inline]
1135 #[rustc_allow_const_fn_unstable(const_eval_select)]
1136 const fn runtime_sub_nowrap(this: *const (), count: usize, size: usize) -> bool {
1137 const_eval_select!(
1138 @capture { this: *const (), count: usize, size: usize } -> bool:
1139 if const {
1140 true
1141 } else {
1142 let Some(byte_offset) = count.checked_mul(size) else {
1143 return false;
1144 };
1145 byte_offset <= (isize::MAX as usize) && this.addr() >= byte_offset
1146 }
1147 )
1148 }
1149
1150 #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
1151 ub_checks::assert_unsafe_precondition!(
1152 check_language_ub,
1153 "ptr::sub requires that the address calculation does not overflow",
1154 (
1155 this: *const () = self as *const (),
1156 count: usize = count,
1157 size: usize = size_of::<T>(),
1158 ) => runtime_sub_nowrap(this, count, size)
1159 );
1160
1161 if T::IS_ZST {
1162 // Pointer arithmetic does nothing when the pointee is a ZST.
1163 self
1164 } else {
1165 // SAFETY: the caller must uphold the safety contract for `offset`.
1166 // Because the pointee is *not* a ZST, that means that `count` is
1167 // at most `isize::MAX`, and thus the negation cannot overflow.
1168 unsafe { intrinsics::offset(self, intrinsics::unchecked_sub(0, count as isize)) }
1169 }
1170 }
1171
1172 /// Subtracts an unsigned offset in bytes from a pointer.
1173 ///
1174 /// `count` is in units of bytes.
1175 ///
1176 /// This is purely a convenience for casting to a `u8` pointer and
1177 /// using [sub][pointer::sub] on it. See that method for documentation
1178 /// and safety requirements.
1179 ///
1180 /// For non-`Sized` pointees this operation changes only the data pointer,
1181 /// leaving the metadata untouched.
1182 #[must_use]
1183 #[inline(always)]
1184 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1185 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1186 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1187 pub const unsafe fn byte_sub(self, count: usize) -> Self {
1188 // SAFETY: the caller must uphold the safety contract for `sub`.
1189 unsafe { self.cast::<u8>().sub(count).with_metadata_of(self) }
1190 }
1191
1192 /// Adds an unsigned offset to a pointer using wrapping arithmetic.
1193 ///
1194 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1195 /// offset of `3 * size_of::<T>()` bytes.
1196 ///
1197 /// # Safety
1198 ///
1199 /// This operation itself is always safe, but using the resulting pointer is not.
1200 ///
1201 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1202 /// be used to read or write other allocated objects.
1203 ///
1204 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1205 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1206 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1207 /// `x` and `y` point into the same allocated object.
1208 ///
1209 /// Compared to [`add`], this method basically delays the requirement of staying within the
1210 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
1211 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1212 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1213 /// can be optimized better and is thus preferable in performance-sensitive code.
1214 ///
1215 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1216 /// intermediate values used during the computation of the final result. For example,
1217 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1218 /// allocated object and then re-entering it later is permitted.
1219 ///
1220 /// [`add`]: #method.add
1221 /// [allocated object]: crate::ptr#allocated-object
1222 ///
1223 /// # Examples
1224 ///
1225 /// ```
1226 /// // Iterate using a raw pointer in increments of two elements
1227 /// let data = [1u8, 2, 3, 4, 5];
1228 /// let mut ptr: *const u8 = data.as_ptr();
1229 /// let step = 2;
1230 /// let end_rounded_up = ptr.wrapping_add(6);
1231 ///
1232 /// // This loop prints "1, 3, 5, "
1233 /// while ptr != end_rounded_up {
1234 /// unsafe {
1235 /// print!("{}, ", *ptr);
1236 /// }
1237 /// ptr = ptr.wrapping_add(step);
1238 /// }
1239 /// ```
1240 #[stable(feature = "pointer_methods", since = "1.26.0")]
1241 #[must_use = "returns a new pointer rather than modifying its argument"]
1242 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1243 #[inline(always)]
1244 pub const fn wrapping_add(self, count: usize) -> Self
1245 where
1246 T: Sized,
1247 {
1248 self.wrapping_offset(count as isize)
1249 }
1250
1251 /// Adds an unsigned offset in bytes to a pointer using wrapping arithmetic.
1252 ///
1253 /// `count` is in units of bytes.
1254 ///
1255 /// This is purely a convenience for casting to a `u8` pointer and
1256 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1257 ///
1258 /// For non-`Sized` pointees this operation changes only the data pointer,
1259 /// leaving the metadata untouched.
1260 #[must_use]
1261 #[inline(always)]
1262 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1263 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1264 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1265 self.cast::<u8>().wrapping_add(count).with_metadata_of(self)
1266 }
1267
1268 /// Subtracts an unsigned offset from a pointer using wrapping arithmetic.
1269 ///
1270 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1271 /// offset of `3 * size_of::<T>()` bytes.
1272 ///
1273 /// # Safety
1274 ///
1275 /// This operation itself is always safe, but using the resulting pointer is not.
1276 ///
1277 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1278 /// be used to read or write other allocated objects.
1279 ///
1280 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1281 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1282 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1283 /// `x` and `y` point into the same allocated object.
1284 ///
1285 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1286 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
1287 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1288 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1289 /// can be optimized better and is thus preferable in performance-sensitive code.
1290 ///
1291 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1292 /// intermediate values used during the computation of the final result. For example,
1293 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1294 /// allocated object and then re-entering it later is permitted.
1295 ///
1296 /// [`sub`]: #method.sub
1297 /// [allocated object]: crate::ptr#allocated-object
1298 ///
1299 /// # Examples
1300 ///
1301 /// ```
1302 /// // Iterate using a raw pointer in increments of two elements (backwards)
1303 /// let data = [1u8, 2, 3, 4, 5];
1304 /// let mut ptr: *const u8 = data.as_ptr();
1305 /// let start_rounded_down = ptr.wrapping_sub(2);
1306 /// ptr = ptr.wrapping_add(4);
1307 /// let step = 2;
1308 /// // This loop prints "5, 3, 1, "
1309 /// while ptr != start_rounded_down {
1310 /// unsafe {
1311 /// print!("{}, ", *ptr);
1312 /// }
1313 /// ptr = ptr.wrapping_sub(step);
1314 /// }
1315 /// ```
1316 #[stable(feature = "pointer_methods", since = "1.26.0")]
1317 #[must_use = "returns a new pointer rather than modifying its argument"]
1318 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1319 #[inline(always)]
1320 pub const fn wrapping_sub(self, count: usize) -> Self
1321 where
1322 T: Sized,
1323 {
1324 self.wrapping_offset((count as isize).wrapping_neg())
1325 }
1326
1327 /// Subtracts an unsigned offset in bytes from a pointer using wrapping arithmetic.
1328 ///
1329 /// `count` is in units of bytes.
1330 ///
1331 /// This is purely a convenience for casting to a `u8` pointer and
1332 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1333 ///
1334 /// For non-`Sized` pointees this operation changes only the data pointer,
1335 /// leaving the metadata untouched.
1336 #[must_use]
1337 #[inline(always)]
1338 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1339 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1340 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1341 self.cast::<u8>().wrapping_sub(count).with_metadata_of(self)
1342 }
1343
1344 /// Reads the value from `self` without moving it. This leaves the
1345 /// memory in `self` unchanged.
1346 ///
1347 /// See [`ptr::read`] for safety concerns and examples.
1348 ///
1349 /// [`ptr::read`]: crate::ptr::read()
1350 #[stable(feature = "pointer_methods", since = "1.26.0")]
1351 #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1352 #[inline(always)]
1353 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1354 pub const unsafe fn read(self) -> T
1355 where
1356 T: Sized,
1357 {
1358 // SAFETY: the caller must uphold the safety contract for ``.
1359 unsafe { read(self) }
1360 }
1361
1362 /// Performs a volatile read of the value from `self` without moving it. This
1363 /// leaves the memory in `self` unchanged.
1364 ///
1365 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1366 /// to not be elided or reordered by the compiler across other volatile
1367 /// operations.
1368 ///
1369 /// See [`ptr::read_volatile`] for safety concerns and examples.
1370 ///
1371 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1372 #[stable(feature = "pointer_methods", since = "1.26.0")]
1373 #[inline(always)]
1374 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1375 pub unsafe fn read_volatile(self) -> T
1376 where
1377 T: Sized,
1378 {
1379 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1380 unsafe { read_volatile(self) }
1381 }
1382
1383 /// Reads the value from `self` without moving it. This leaves the
1384 /// memory in `self` unchanged.
1385 ///
1386 /// Unlike `read`, the pointer may be unaligned.
1387 ///
1388 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1389 ///
1390 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1391 #[stable(feature = "pointer_methods", since = "1.26.0")]
1392 #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1393 #[inline(always)]
1394 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1395 pub const unsafe fn read_unaligned(self) -> T
1396 where
1397 T: Sized,
1398 {
1399 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1400 unsafe { read_unaligned(self) }
1401 }
1402
1403 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1404 /// and destination may overlap.
1405 ///
1406 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1407 ///
1408 /// See [`ptr::copy`] for safety concerns and examples.
1409 ///
1410 /// [`ptr::copy`]: crate::ptr::copy()
1411 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1412 #[stable(feature = "pointer_methods", since = "1.26.0")]
1413 #[inline(always)]
1414 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1415 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1416 where
1417 T: Sized,
1418 {
1419 // SAFETY: the caller must uphold the safety contract for `copy`.
1420 unsafe { copy(self, dest, count) }
1421 }
1422
1423 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1424 /// and destination may *not* overlap.
1425 ///
1426 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1427 ///
1428 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1429 ///
1430 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1431 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1432 #[stable(feature = "pointer_methods", since = "1.26.0")]
1433 #[inline(always)]
1434 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1435 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1436 where
1437 T: Sized,
1438 {
1439 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1440 unsafe { copy_nonoverlapping(self, dest, count) }
1441 }
1442
1443 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1444 /// and destination may overlap.
1445 ///
1446 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1447 ///
1448 /// See [`ptr::copy`] for safety concerns and examples.
1449 ///
1450 /// [`ptr::copy`]: crate::ptr::copy()
1451 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1452 #[stable(feature = "pointer_methods", since = "1.26.0")]
1453 #[inline(always)]
1454 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1455 pub const unsafe fn copy_from(self, src: *const T, count: usize)
1456 where
1457 T: Sized,
1458 {
1459 // SAFETY: the caller must uphold the safety contract for `copy`.
1460 unsafe { copy(src, self, count) }
1461 }
1462
1463 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1464 /// and destination may *not* overlap.
1465 ///
1466 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1467 ///
1468 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1469 ///
1470 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1471 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1472 #[stable(feature = "pointer_methods", since = "1.26.0")]
1473 #[inline(always)]
1474 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1475 pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1476 where
1477 T: Sized,
1478 {
1479 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1480 unsafe { copy_nonoverlapping(src, self, count) }
1481 }
1482
1483 /// Executes the destructor (if any) of the pointed-to value.
1484 ///
1485 /// See [`ptr::drop_in_place`] for safety concerns and examples.
1486 ///
1487 /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1488 #[stable(feature = "pointer_methods", since = "1.26.0")]
1489 #[inline(always)]
1490 pub unsafe fn drop_in_place(self) {
1491 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1492 unsafe { drop_in_place(self) }
1493 }
1494
1495 /// Overwrites a memory location with the given value without reading or
1496 /// dropping the old value.
1497 ///
1498 /// See [`ptr::write`] for safety concerns and examples.
1499 ///
1500 /// [`ptr::write`]: crate::ptr::write()
1501 #[stable(feature = "pointer_methods", since = "1.26.0")]
1502 #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1503 #[inline(always)]
1504 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1505 pub const unsafe fn write(self, val: T)
1506 where
1507 T: Sized,
1508 {
1509 // SAFETY: the caller must uphold the safety contract for `write`.
1510 unsafe { write(self, val) }
1511 }
1512
1513 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1514 /// bytes of memory starting at `self` to `val`.
1515 ///
1516 /// See [`ptr::write_bytes`] for safety concerns and examples.
1517 ///
1518 /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1519 #[doc(alias = "memset")]
1520 #[stable(feature = "pointer_methods", since = "1.26.0")]
1521 #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1522 #[inline(always)]
1523 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1524 pub const unsafe fn write_bytes(self, val: u8, count: usize)
1525 where
1526 T: Sized,
1527 {
1528 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1529 unsafe { write_bytes(self, val, count) }
1530 }
1531
1532 /// Performs a volatile write of a memory location with the given value without
1533 /// reading or dropping the old value.
1534 ///
1535 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1536 /// to not be elided or reordered by the compiler across other volatile
1537 /// operations.
1538 ///
1539 /// See [`ptr::write_volatile`] for safety concerns and examples.
1540 ///
1541 /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1542 #[stable(feature = "pointer_methods", since = "1.26.0")]
1543 #[inline(always)]
1544 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1545 pub unsafe fn write_volatile(self, val: T)
1546 where
1547 T: Sized,
1548 {
1549 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1550 unsafe { write_volatile(self, val) }
1551 }
1552
1553 /// Overwrites a memory location with the given value without reading or
1554 /// dropping the old value.
1555 ///
1556 /// Unlike `write`, the pointer may be unaligned.
1557 ///
1558 /// See [`ptr::write_unaligned`] for safety concerns and examples.
1559 ///
1560 /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1561 #[stable(feature = "pointer_methods", since = "1.26.0")]
1562 #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1563 #[inline(always)]
1564 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1565 pub const unsafe fn write_unaligned(self, val: T)
1566 where
1567 T: Sized,
1568 {
1569 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1570 unsafe { write_unaligned(self, val) }
1571 }
1572
1573 /// Replaces the value at `self` with `src`, returning the old
1574 /// value, without dropping either.
1575 ///
1576 /// See [`ptr::replace`] for safety concerns and examples.
1577 ///
1578 /// [`ptr::replace`]: crate::ptr::replace()
1579 #[stable(feature = "pointer_methods", since = "1.26.0")]
1580 #[inline(always)]
1581 pub unsafe fn replace(self, src: T) -> T
1582 where
1583 T: Sized,
1584 {
1585 // SAFETY: the caller must uphold the safety contract for `replace`.
1586 unsafe { replace(self, src) }
1587 }
1588
1589 /// Swaps the values at two mutable locations of the same type, without
1590 /// deinitializing either. They may overlap, unlike `mem::swap` which is
1591 /// otherwise equivalent.
1592 ///
1593 /// See [`ptr::swap`] for safety concerns and examples.
1594 ///
1595 /// [`ptr::swap`]: crate::ptr::swap()
1596 #[stable(feature = "pointer_methods", since = "1.26.0")]
1597 #[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
1598 #[inline(always)]
1599 pub const unsafe fn swap(self, with: *mut T)
1600 where
1601 T: Sized,
1602 {
1603 // SAFETY: the caller must uphold the safety contract for `swap`.
1604 unsafe { swap(self, with) }
1605 }
1606
1607 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1608 /// `align`.
1609 ///
1610 /// If it is not possible to align the pointer, the implementation returns
1611 /// `usize::MAX`.
1612 ///
1613 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1614 /// used with the `wrapping_add` method.
1615 ///
1616 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1617 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1618 /// the returned offset is correct in all terms other than alignment.
1619 ///
1620 /// # Panics
1621 ///
1622 /// The function panics if `align` is not a power-of-two.
1623 ///
1624 /// # Examples
1625 ///
1626 /// Accessing adjacent `u8` as `u16`
1627 ///
1628 /// ```
1629 /// use std::mem::align_of;
1630 ///
1631 /// # unsafe {
1632 /// let mut x = [5_u8, 6, 7, 8, 9];
1633 /// let ptr = x.as_mut_ptr();
1634 /// let offset = ptr.align_offset(align_of::<u16>());
1635 ///
1636 /// if offset < x.len() - 1 {
1637 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1638 /// *u16_ptr = 0;
1639 ///
1640 /// assert!(x == [0, 0, 7, 8, 9] || x == [5, 0, 0, 8, 9]);
1641 /// } else {
1642 /// // while the pointer can be aligned via `offset`, it would point
1643 /// // outside the allocation
1644 /// }
1645 /// # }
1646 /// ```
1647 #[must_use]
1648 #[inline]
1649 #[stable(feature = "align_offset", since = "1.36.0")]
1650 pub fn align_offset(self, align: usize) -> usize
1651 where
1652 T: Sized,
1653 {
1654 if !align.is_power_of_two() {
1655 panic!("align_offset: align is not a power-of-two");
1656 }
1657
1658 // SAFETY: `align` has been checked to be a power of 2 above
1659 let ret = unsafe { align_offset(self, align) };
1660
1661 // Inform Miri that we want to consider the resulting pointer to be suitably aligned.
1662 #[cfg(miri)]
1663 if ret != usize::MAX {
1664 intrinsics::miri_promise_symbolic_alignment(
1665 self.wrapping_add(ret).cast_const().cast(),
1666 align,
1667 );
1668 }
1669
1670 ret
1671 }
1672
1673 /// Returns whether the pointer is properly aligned for `T`.
1674 ///
1675 /// # Examples
1676 ///
1677 /// ```
1678 /// // On some platforms, the alignment of i32 is less than 4.
1679 /// #[repr(align(4))]
1680 /// struct AlignedI32(i32);
1681 ///
1682 /// let mut data = AlignedI32(42);
1683 /// let ptr = &mut data as *mut AlignedI32;
1684 ///
1685 /// assert!(ptr.is_aligned());
1686 /// assert!(!ptr.wrapping_byte_add(1).is_aligned());
1687 /// ```
1688 #[must_use]
1689 #[inline]
1690 #[stable(feature = "pointer_is_aligned", since = "1.79.0")]
1691 pub fn is_aligned(self) -> bool
1692 where
1693 T: Sized,
1694 {
1695 self.is_aligned_to(mem::align_of::<T>())
1696 }
1697
1698 /// Returns whether the pointer is aligned to `align`.
1699 ///
1700 /// For non-`Sized` pointees this operation considers only the data pointer,
1701 /// ignoring the metadata.
1702 ///
1703 /// # Panics
1704 ///
1705 /// The function panics if `align` is not a power-of-two (this includes 0).
1706 ///
1707 /// # Examples
1708 ///
1709 /// ```
1710 /// #![feature(pointer_is_aligned_to)]
1711 ///
1712 /// // On some platforms, the alignment of i32 is less than 4.
1713 /// #[repr(align(4))]
1714 /// struct AlignedI32(i32);
1715 ///
1716 /// let mut data = AlignedI32(42);
1717 /// let ptr = &mut data as *mut AlignedI32;
1718 ///
1719 /// assert!(ptr.is_aligned_to(1));
1720 /// assert!(ptr.is_aligned_to(2));
1721 /// assert!(ptr.is_aligned_to(4));
1722 ///
1723 /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1724 /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1725 ///
1726 /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1727 /// ```
1728 #[must_use]
1729 #[inline]
1730 #[unstable(feature = "pointer_is_aligned_to", issue = "96284")]
1731 pub fn is_aligned_to(self, align: usize) -> bool {
1732 if !align.is_power_of_two() {
1733 panic!("is_aligned_to: align is not a power-of-two");
1734 }
1735
1736 self.addr() & (align - 1) == 0
1737 }
1738}
1739
1740impl<T> *mut [T] {
1741 /// Returns the length of a raw slice.
1742 ///
1743 /// The returned value is the number of **elements**, not the number of bytes.
1744 ///
1745 /// This function is safe, even when the raw slice cannot be cast to a slice
1746 /// reference because the pointer is null or unaligned.
1747 ///
1748 /// # Examples
1749 ///
1750 /// ```rust
1751 /// use std::ptr;
1752 ///
1753 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1754 /// assert_eq!(slice.len(), 3);
1755 /// ```
1756 #[inline(always)]
1757 #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1758 #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1759 pub const fn len(self) -> usize {
1760 metadata(self)
1761 }
1762
1763 /// Returns `true` if the raw slice has a length of 0.
1764 ///
1765 /// # Examples
1766 ///
1767 /// ```
1768 /// use std::ptr;
1769 ///
1770 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1771 /// assert!(!slice.is_empty());
1772 /// ```
1773 #[inline(always)]
1774 #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1775 #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1776 pub const fn is_empty(self) -> bool {
1777 self.len() == 0
1778 }
1779
1780 /// Gets a raw, mutable pointer to the underlying array.
1781 ///
1782 /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
1783 #[unstable(feature = "slice_as_array", issue = "133508")]
1784 #[inline]
1785 #[must_use]
1786 pub const fn as_mut_array<const N: usize>(self) -> Option<*mut [T; N]> {
1787 if self.len() == N {
1788 let me = self.as_mut_ptr() as *mut [T; N];
1789 Some(me)
1790 } else {
1791 None
1792 }
1793 }
1794
1795 /// Divides one mutable raw slice into two at an index.
1796 ///
1797 /// The first will contain all indices from `[0, mid)` (excluding
1798 /// the index `mid` itself) and the second will contain all
1799 /// indices from `[mid, len)` (excluding the index `len` itself).
1800 ///
1801 /// # Panics
1802 ///
1803 /// Panics if `mid > len`.
1804 ///
1805 /// # Safety
1806 ///
1807 /// `mid` must be [in-bounds] of the underlying [allocated object].
1808 /// Which means `self` must be dereferenceable and span a single allocation
1809 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1810 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1811 ///
1812 /// Since `len` being in-bounds it is not a safety invariant of `*mut [T]` the
1813 /// safety requirements of this method are the same as for [`split_at_mut_unchecked`].
1814 /// The explicit bounds check is only as useful as `len` is correct.
1815 ///
1816 /// [`split_at_mut_unchecked`]: #method.split_at_mut_unchecked
1817 /// [in-bounds]: #method.add
1818 /// [allocated object]: crate::ptr#allocated-object
1819 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1820 ///
1821 /// # Examples
1822 ///
1823 /// ```
1824 /// #![feature(raw_slice_split)]
1825 /// #![feature(slice_ptr_get)]
1826 ///
1827 /// let mut v = [1, 0, 3, 0, 5, 6];
1828 /// let ptr = &mut v as *mut [_];
1829 /// unsafe {
1830 /// let (left, right) = ptr.split_at_mut(2);
1831 /// assert_eq!(&*left, [1, 0]);
1832 /// assert_eq!(&*right, [3, 0, 5, 6]);
1833 /// }
1834 /// ```
1835 #[inline(always)]
1836 #[track_caller]
1837 #[unstable(feature = "raw_slice_split", issue = "95595")]
1838 pub unsafe fn split_at_mut(self, mid: usize) -> (*mut [T], *mut [T]) {
1839 assert!(mid <= self.len());
1840 // SAFETY: The assert above is only a safety-net as long as `self.len()` is correct
1841 // The actual safety requirements of this function are the same as for `split_at_mut_unchecked`
1842 unsafe { self.split_at_mut_unchecked(mid) }
1843 }
1844
1845 /// Divides one mutable raw slice into two at an index, without doing bounds checking.
1846 ///
1847 /// The first will contain all indices from `[0, mid)` (excluding
1848 /// the index `mid` itself) and the second will contain all
1849 /// indices from `[mid, len)` (excluding the index `len` itself).
1850 ///
1851 /// # Safety
1852 ///
1853 /// `mid` must be [in-bounds] of the underlying [allocated object].
1854 /// Which means `self` must be dereferenceable and span a single allocation
1855 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1856 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1857 ///
1858 /// [in-bounds]: #method.add
1859 /// [out-of-bounds index]: #method.add
1860 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1861 ///
1862 /// # Examples
1863 ///
1864 /// ```
1865 /// #![feature(raw_slice_split)]
1866 ///
1867 /// let mut v = [1, 0, 3, 0, 5, 6];
1868 /// // scoped to restrict the lifetime of the borrows
1869 /// unsafe {
1870 /// let ptr = &mut v as *mut [_];
1871 /// let (left, right) = ptr.split_at_mut_unchecked(2);
1872 /// assert_eq!(&*left, [1, 0]);
1873 /// assert_eq!(&*right, [3, 0, 5, 6]);
1874 /// (&mut *left)[1] = 2;
1875 /// (&mut *right)[1] = 4;
1876 /// }
1877 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1878 /// ```
1879 #[inline(always)]
1880 #[unstable(feature = "raw_slice_split", issue = "95595")]
1881 pub unsafe fn split_at_mut_unchecked(self, mid: usize) -> (*mut [T], *mut [T]) {
1882 let len = self.len();
1883 let ptr = self.as_mut_ptr();
1884
1885 // SAFETY: Caller must pass a valid pointer and an index that is in-bounds.
1886 let tail = unsafe { ptr.add(mid) };
1887 (
1888 crate::ptr::slice_from_raw_parts_mut(ptr, mid),
1889 crate::ptr::slice_from_raw_parts_mut(tail, len - mid),
1890 )
1891 }
1892
1893 /// Returns a raw pointer to the slice's buffer.
1894 ///
1895 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
1896 ///
1897 /// # Examples
1898 ///
1899 /// ```rust
1900 /// #![feature(slice_ptr_get)]
1901 /// use std::ptr;
1902 ///
1903 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1904 /// assert_eq!(slice.as_mut_ptr(), ptr::null_mut());
1905 /// ```
1906 #[inline(always)]
1907 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1908 pub const fn as_mut_ptr(self) -> *mut T {
1909 self as *mut T
1910 }
1911
1912 /// Returns a raw pointer to an element or subslice, without doing bounds
1913 /// checking.
1914 ///
1915 /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
1916 /// is *[undefined behavior]* even if the resulting pointer is not used.
1917 ///
1918 /// [out-of-bounds index]: #method.add
1919 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1920 ///
1921 /// # Examples
1922 ///
1923 /// ```
1924 /// #![feature(slice_ptr_get)]
1925 ///
1926 /// let x = &mut [1, 2, 4] as *mut [i32];
1927 ///
1928 /// unsafe {
1929 /// assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
1930 /// }
1931 /// ```
1932 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1933 #[inline(always)]
1934 pub unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
1935 where
1936 I: SliceIndex<[T]>,
1937 {
1938 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1939 unsafe { index.get_unchecked_mut(self) }
1940 }
1941
1942 /// Returns `None` if the pointer is null, or else returns a shared slice to
1943 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1944 /// that the value has to be initialized.
1945 ///
1946 /// For the mutable counterpart see [`as_uninit_slice_mut`].
1947 ///
1948 /// [`as_ref`]: pointer#method.as_ref-1
1949 /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
1950 ///
1951 /// # Safety
1952 ///
1953 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1954 /// all of the following is true:
1955 ///
1956 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1957 /// and it must be properly aligned. This means in particular:
1958 ///
1959 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1960 /// Slices can never span across multiple allocated objects.
1961 ///
1962 /// * The pointer must be aligned even for zero-length slices. One
1963 /// reason for this is that enum layout optimizations may rely on references
1964 /// (including slices of any length) being aligned and non-null to distinguish
1965 /// them from other data. You can obtain a pointer that is usable as `data`
1966 /// for zero-length slices using [`NonNull::dangling()`].
1967 ///
1968 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1969 /// See the safety documentation of [`pointer::offset`].
1970 ///
1971 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1972 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1973 /// In particular, while this reference exists, the memory the pointer points to must
1974 /// not get mutated (except inside `UnsafeCell`).
1975 ///
1976 /// This applies even if the result of this method is unused!
1977 ///
1978 /// See also [`slice::from_raw_parts`][].
1979 ///
1980 /// [valid]: crate::ptr#safety
1981 /// [allocated object]: crate::ptr#allocated-object
1982 ///
1983 /// # Panics during const evaluation
1984 ///
1985 /// This method will panic during const evaluation if the pointer cannot be
1986 /// determined to be null or not. See [`is_null`] for more information.
1987 ///
1988 /// [`is_null`]: #method.is_null-1
1989 #[inline]
1990 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1991 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1992 if self.is_null() {
1993 None
1994 } else {
1995 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1996 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1997 }
1998 }
1999
2000 /// Returns `None` if the pointer is null, or else returns a unique slice to
2001 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
2002 /// that the value has to be initialized.
2003 ///
2004 /// For the shared counterpart see [`as_uninit_slice`].
2005 ///
2006 /// [`as_mut`]: #method.as_mut
2007 /// [`as_uninit_slice`]: #method.as_uninit_slice-1
2008 ///
2009 /// # Safety
2010 ///
2011 /// When calling this method, you have to ensure that *either* the pointer is null *or*
2012 /// all of the following is true:
2013 ///
2014 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
2015 /// many bytes, and it must be properly aligned. This means in particular:
2016 ///
2017 /// * The entire memory range of this slice must be contained within a single [allocated object]!
2018 /// Slices can never span across multiple allocated objects.
2019 ///
2020 /// * The pointer must be aligned even for zero-length slices. One
2021 /// reason for this is that enum layout optimizations may rely on references
2022 /// (including slices of any length) being aligned and non-null to distinguish
2023 /// them from other data. You can obtain a pointer that is usable as `data`
2024 /// for zero-length slices using [`NonNull::dangling()`].
2025 ///
2026 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
2027 /// See the safety documentation of [`pointer::offset`].
2028 ///
2029 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
2030 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
2031 /// In particular, while this reference exists, the memory the pointer points to must
2032 /// not get accessed (read or written) through any other pointer.
2033 ///
2034 /// This applies even if the result of this method is unused!
2035 ///
2036 /// See also [`slice::from_raw_parts_mut`][].
2037 ///
2038 /// [valid]: crate::ptr#safety
2039 /// [allocated object]: crate::ptr#allocated-object
2040 ///
2041 /// # Panics during const evaluation
2042 ///
2043 /// This method will panic during const evaluation if the pointer cannot be
2044 /// determined to be null or not. See [`is_null`] for more information.
2045 ///
2046 /// [`is_null`]: #method.is_null-1
2047 #[inline]
2048 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
2049 pub const unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
2050 if self.is_null() {
2051 None
2052 } else {
2053 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
2054 Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
2055 }
2056 }
2057}
2058
2059impl<T, const N: usize> *mut [T; N] {
2060 /// Returns a raw pointer to the array's buffer.
2061 ///
2062 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
2063 ///
2064 /// # Examples
2065 ///
2066 /// ```rust
2067 /// #![feature(array_ptr_get)]
2068 /// use std::ptr;
2069 ///
2070 /// let arr: *mut [i8; 3] = ptr::null_mut();
2071 /// assert_eq!(arr.as_mut_ptr(), ptr::null_mut());
2072 /// ```
2073 #[inline]
2074 #[unstable(feature = "array_ptr_get", issue = "119834")]
2075 pub const fn as_mut_ptr(self) -> *mut T {
2076 self as *mut T
2077 }
2078
2079 /// Returns a raw pointer to a mutable slice containing the entire array.
2080 ///
2081 /// # Examples
2082 ///
2083 /// ```
2084 /// #![feature(array_ptr_get)]
2085 ///
2086 /// let mut arr = [1, 2, 5];
2087 /// let ptr: *mut [i32; 3] = &mut arr;
2088 /// unsafe {
2089 /// (&mut *ptr.as_mut_slice())[..2].copy_from_slice(&[3, 4]);
2090 /// }
2091 /// assert_eq!(arr, [3, 4, 5]);
2092 /// ```
2093 #[inline]
2094 #[unstable(feature = "array_ptr_get", issue = "119834")]
2095 pub const fn as_mut_slice(self) -> *mut [T] {
2096 self
2097 }
2098}
2099
2100/// Pointer equality is by address, as produced by the [`<*mut T>::addr`](pointer::addr) method.
2101#[stable(feature = "rust1", since = "1.0.0")]
2102impl<T: ?Sized> PartialEq for *mut T {
2103 #[inline(always)]
2104 #[allow(ambiguous_wide_pointer_comparisons)]
2105 fn eq(&self, other: &*mut T) -> bool {
2106 *self == *other
2107 }
2108}
2109
2110/// Pointer equality is an equivalence relation.
2111#[stable(feature = "rust1", since = "1.0.0")]
2112impl<T: ?Sized> Eq for *mut T {}
2113
2114/// Pointer comparison is by address, as produced by the [`<*mut T>::addr`](pointer::addr) method.
2115#[stable(feature = "rust1", since = "1.0.0")]
2116impl<T: ?Sized> Ord for *mut T {
2117 #[inline]
2118 #[allow(ambiguous_wide_pointer_comparisons)]
2119 fn cmp(&self, other: &*mut T) -> Ordering {
2120 if self < other {
2121 Less
2122 } else if self == other {
2123 Equal
2124 } else {
2125 Greater
2126 }
2127 }
2128}
2129
2130/// Pointer comparison is by address, as produced by the [`<*mut T>::addr`](pointer::addr) method.
2131#[stable(feature = "rust1", since = "1.0.0")]
2132impl<T: ?Sized> PartialOrd for *mut T {
2133 #[inline(always)]
2134 #[allow(ambiguous_wide_pointer_comparisons)]
2135 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
2136 Some(self.cmp(other))
2137 }
2138
2139 #[inline(always)]
2140 #[allow(ambiguous_wide_pointer_comparisons)]
2141 fn lt(&self, other: &*mut T) -> bool {
2142 *self < *other
2143 }
2144
2145 #[inline(always)]
2146 #[allow(ambiguous_wide_pointer_comparisons)]
2147 fn le(&self, other: &*mut T) -> bool {
2148 *self <= *other
2149 }
2150
2151 #[inline(always)]
2152 #[allow(ambiguous_wide_pointer_comparisons)]
2153 fn gt(&self, other: &*mut T) -> bool {
2154 *self > *other
2155 }
2156
2157 #[inline(always)]
2158 #[allow(ambiguous_wide_pointer_comparisons)]
2159 fn ge(&self, other: &*mut T) -> bool {
2160 *self >= *other
2161 }
2162}