core/ptr/const_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: PointeeSized> *const T {
8 #[doc = include_str!("docs/is_null.md")]
9 ///
10 /// # Examples
11 ///
12 /// ```
13 /// let s: &str = "Follow the rabbit";
14 /// let ptr: *const u8 = s.as_ptr();
15 /// assert!(!ptr.is_null());
16 /// ```
17 #[stable(feature = "rust1", since = "1.0.0")]
18 #[rustc_const_stable(feature = "const_ptr_is_null", since = "1.84.0")]
19 #[rustc_diagnostic_item = "ptr_const_is_null"]
20 #[inline]
21 #[rustc_allow_const_fn_unstable(const_eval_select)]
22 pub const fn is_null(self) -> bool {
23 // Compare via a cast to a thin pointer, so fat pointers are only
24 // considering their "data" part for null-ness.
25 let ptr = self as *const u8;
26 const_eval_select!(
27 @capture { ptr: *const u8 } -> bool:
28 // This use of `const_raw_ptr_comparison` has been explicitly blessed by t-lang.
29 if const #[rustc_allow_const_fn_unstable(const_raw_ptr_comparison)] {
30 match (ptr).guaranteed_eq(null_mut()) {
31 Some(res) => res,
32 // To remain maximally conservative, we stop execution when we don't
33 // know whether the pointer is null or not.
34 // We can *not* return `false` here, that would be unsound in `NonNull::new`!
35 None => panic!("null-ness of this pointer cannot be determined in const context"),
36 }
37 } else {
38 ptr.addr() == 0
39 }
40 )
41 }
42
43 /// Casts to a pointer of another type.
44 #[stable(feature = "ptr_cast", since = "1.38.0")]
45 #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
46 #[rustc_diagnostic_item = "const_ptr_cast"]
47 #[inline(always)]
48 pub const fn cast<U>(self) -> *const U {
49 self as _
50 }
51
52 /// Try to cast to a pointer of another type by checking alignment.
53 ///
54 /// If the pointer is properly aligned to the target type, it will be
55 /// cast to the target type. Otherwise, `None` is returned.
56 ///
57 /// # Examples
58 ///
59 /// ```rust
60 /// #![feature(pointer_try_cast_aligned)]
61 ///
62 /// let x = 0u64;
63 ///
64 /// let aligned: *const u64 = &x;
65 /// let unaligned = unsafe { aligned.byte_add(1) };
66 ///
67 /// assert!(aligned.try_cast_aligned::<u32>().is_some());
68 /// assert!(unaligned.try_cast_aligned::<u32>().is_none());
69 /// ```
70 #[unstable(feature = "pointer_try_cast_aligned", issue = "141221")]
71 #[must_use = "this returns the result of the operation, \
72 without modifying the original"]
73 #[inline]
74 pub fn try_cast_aligned<U>(self) -> Option<*const U> {
75 if self.is_aligned_to(align_of::<U>()) { Some(self.cast()) } else { None }
76 }
77
78 /// Uses the address value in a new pointer of another type.
79 ///
80 /// This operation will ignore the address part of its `meta` operand and discard existing
81 /// metadata of `self`. For pointers to a sized types (thin pointers), this has the same effect
82 /// as a simple cast. For pointers to an unsized type (fat pointers) this recombines the address
83 /// with new metadata such as slice lengths or `dyn`-vtable.
84 ///
85 /// The resulting pointer will have provenance of `self`. This operation is semantically the
86 /// same as creating a new pointer with the data pointer value of `self` but the metadata of
87 /// `meta`, being fat or thin depending on the `meta` operand.
88 ///
89 /// # Examples
90 ///
91 /// This function is primarily useful for enabling pointer arithmetic on potentially fat
92 /// pointers. The pointer is cast to a sized pointee to utilize offset operations and then
93 /// recombined with its own original metadata.
94 ///
95 /// ```
96 /// #![feature(set_ptr_value)]
97 /// # use core::fmt::Debug;
98 /// let arr: [i32; 3] = [1, 2, 3];
99 /// let mut ptr = arr.as_ptr() as *const dyn Debug;
100 /// let thin = ptr as *const u8;
101 /// unsafe {
102 /// ptr = thin.add(8).with_metadata_of(ptr);
103 /// # assert_eq!(*(ptr as *const i32), 3);
104 /// println!("{:?}", &*ptr); // will print "3"
105 /// }
106 /// ```
107 ///
108 /// # *Incorrect* usage
109 ///
110 /// The provenance from pointers is *not* combined. The result must only be used to refer to the
111 /// address allowed by `self`.
112 ///
113 /// ```rust,no_run
114 /// #![feature(set_ptr_value)]
115 /// let x = 0u32;
116 /// let y = 1u32;
117 ///
118 /// let x = (&x) as *const u32;
119 /// let y = (&y) as *const u32;
120 ///
121 /// let offset = (x as usize - y as usize) / 4;
122 /// let bad = x.wrapping_add(offset).with_metadata_of(y);
123 ///
124 /// // This dereference is UB. The pointer only has provenance for `x` but points to `y`.
125 /// println!("{:?}", unsafe { &*bad });
126 /// ```
127 #[unstable(feature = "set_ptr_value", issue = "75091")]
128 #[must_use = "returns a new pointer rather than modifying its argument"]
129 #[inline]
130 pub const fn with_metadata_of<U>(self, meta: *const U) -> *const U
131 where
132 U: PointeeSized,
133 {
134 from_raw_parts::<U>(self as *const (), metadata(meta))
135 }
136
137 /// Changes constness without changing the type.
138 ///
139 /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
140 /// refactored.
141 #[stable(feature = "ptr_const_cast", since = "1.65.0")]
142 #[rustc_const_stable(feature = "ptr_const_cast", since = "1.65.0")]
143 #[rustc_diagnostic_item = "ptr_cast_mut"]
144 #[inline(always)]
145 pub const fn cast_mut(self) -> *mut T {
146 self as _
147 }
148
149 #[doc = include_str!("./docs/addr.md")]
150 #[must_use]
151 #[inline(always)]
152 #[stable(feature = "strict_provenance", since = "1.84.0")]
153 pub fn addr(self) -> usize {
154 // A pointer-to-integer transmute currently has exactly the right semantics: it returns the
155 // address without exposing the provenance. Note that this is *not* a stable guarantee about
156 // transmute semantics, it relies on sysroot crates having special status.
157 // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
158 // provenance).
159 unsafe { mem::transmute(self.cast::<()>()) }
160 }
161
162 /// Exposes the ["provenance"][crate::ptr#provenance] part of the pointer for future use in
163 /// [`with_exposed_provenance`] and returns the "address" portion.
164 ///
165 /// This is equivalent to `self as usize`, which semantically discards provenance information.
166 /// Furthermore, this (like the `as` cast) has the implicit side-effect of marking the
167 /// provenance as 'exposed', so on platforms that support it you can later call
168 /// [`with_exposed_provenance`] to reconstitute the original pointer including its provenance.
169 ///
170 /// Due to its inherent ambiguity, [`with_exposed_provenance`] may not be supported by tools
171 /// that help you to stay conformant with the Rust memory model. It is recommended to use
172 /// [Strict Provenance][crate::ptr#strict-provenance] APIs such as [`with_addr`][pointer::with_addr]
173 /// wherever possible, in which case [`addr`][pointer::addr] should be used instead of `expose_provenance`.
174 ///
175 /// On most platforms this will produce a value with the same bytes as the original pointer,
176 /// because all the bytes are dedicated to describing the address. Platforms which need to store
177 /// additional information in the pointer may not support this operation, since the 'expose'
178 /// side-effect which is required for [`with_exposed_provenance`] to work is typically not
179 /// available.
180 ///
181 /// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
182 ///
183 /// [`with_exposed_provenance`]: with_exposed_provenance
184 #[inline(always)]
185 #[stable(feature = "exposed_provenance", since = "1.84.0")]
186 #[expect(implicit_provenance_casts, reason = "this *is* the replacement")]
187 pub fn expose_provenance(self) -> usize {
188 self.cast::<()>() as usize
189 }
190
191 /// Creates a new pointer with the given address and the [provenance][crate::ptr#provenance] of
192 /// `self`.
193 ///
194 /// This is similar to a `addr as *const T` cast, but copies
195 /// the *provenance* of `self` to the new pointer.
196 /// This avoids the inherent ambiguity of the unary cast.
197 ///
198 /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
199 /// `self` to the given address, and therefore has all the same capabilities and restrictions.
200 ///
201 /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
202 #[must_use]
203 #[inline]
204 #[stable(feature = "strict_provenance", since = "1.84.0")]
205 pub fn with_addr(self, addr: usize) -> Self {
206 // This should probably be an intrinsic to avoid doing any sort of arithmetic, but
207 // meanwhile, we can implement it with `wrapping_offset`, which preserves the pointer's
208 // provenance.
209 let self_addr = self.addr() as isize;
210 let dest_addr = addr as isize;
211 let offset = dest_addr.wrapping_sub(self_addr);
212 self.wrapping_byte_offset(offset)
213 }
214
215 /// Creates a new pointer by mapping `self`'s address to a new one, preserving the
216 /// [provenance][crate::ptr#provenance] of `self`.
217 ///
218 /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
219 ///
220 /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
221 #[must_use]
222 #[inline]
223 #[stable(feature = "strict_provenance", since = "1.84.0")]
224 pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self {
225 self.with_addr(f(self.addr()))
226 }
227
228 /// Decompose a (possibly wide) pointer into its data pointer and metadata components.
229 ///
230 /// The pointer can be later reconstructed with [`from_raw_parts`].
231 #[unstable(feature = "ptr_metadata", issue = "81513")]
232 #[inline]
233 pub const fn to_raw_parts(self) -> (*const (), <T as super::Pointee>::Metadata) {
234 (self.cast(), metadata(self))
235 }
236
237 #[doc = include_str!("./docs/as_ref.md")]
238 ///
239 /// ```
240 /// let ptr: *const u8 = &10u8 as *const u8;
241 ///
242 /// unsafe {
243 /// let val_back = ptr.as_ref_unchecked();
244 /// assert_eq!(val_back, &10);
245 /// }
246 /// ```
247 ///
248 /// # Examples
249 ///
250 /// ```
251 /// let ptr: *const u8 = &10u8 as *const u8;
252 ///
253 /// unsafe {
254 /// if let Some(val_back) = ptr.as_ref() {
255 /// assert_eq!(val_back, &10);
256 /// }
257 /// }
258 /// ```
259 ///
260 ///
261 /// [`is_null`]: #method.is_null
262 /// [`as_uninit_ref`]: #method.as_uninit_ref
263 /// [`as_ref_unchecked`]: #method.as_ref_unchecked
264 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
265 #[rustc_const_stable(feature = "const_ptr_is_null", since = "1.84.0")]
266 #[inline]
267 pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
268 // SAFETY: the caller must guarantee that `self` is valid
269 // for a reference if it isn't null.
270 if self.is_null() { None } else { unsafe { Some(&*self) } }
271 }
272
273 /// Returns a shared reference to the value behind the pointer.
274 /// If the pointer may be null or the value may be uninitialized, [`as_uninit_ref`] must be used instead.
275 /// If the pointer may be null, but the value is known to have been initialized, [`as_ref`] must be used instead.
276 ///
277 /// [`as_ref`]: #method.as_ref
278 /// [`as_uninit_ref`]: #method.as_uninit_ref
279 ///
280 /// # Safety
281 ///
282 /// When calling this method, you have to ensure that
283 /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
284 ///
285 /// # Examples
286 ///
287 /// ```
288 /// let ptr: *const u8 = &10u8 as *const u8;
289 ///
290 /// unsafe {
291 /// assert_eq!(ptr.as_ref_unchecked(), &10);
292 /// }
293 /// ```
294 #[stable(feature = "ptr_as_ref_unchecked", since = "1.95.0")]
295 #[rustc_const_stable(feature = "ptr_as_ref_unchecked", since = "1.95.0")]
296 #[inline]
297 #[must_use]
298 pub const unsafe fn as_ref_unchecked<'a>(self) -> &'a T {
299 // SAFETY: the caller must guarantee that `self` is valid for a reference
300 unsafe { &*self }
301 }
302
303 #[doc = include_str!("./docs/as_uninit_ref.md")]
304 ///
305 /// [`is_null`]: #method.is_null
306 /// [`as_ref`]: #method.as_ref
307 ///
308 /// # Examples
309 ///
310 /// ```
311 /// #![feature(ptr_as_uninit)]
312 ///
313 /// let ptr: *const u8 = &10u8 as *const u8;
314 ///
315 /// unsafe {
316 /// if let Some(val_back) = ptr.as_uninit_ref() {
317 /// assert_eq!(val_back.assume_init(), 10);
318 /// }
319 /// }
320 /// ```
321 #[inline]
322 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
323 pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
324 where
325 T: Sized,
326 {
327 // SAFETY: the caller must guarantee that `self` meets all the
328 // requirements for a reference.
329 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
330 }
331
332 #[doc = include_str!("./docs/offset.md")]
333 ///
334 /// Consider using [`wrapping_offset`](#method.wrapping_offset) instead if these constraints are
335 /// difficult to satisfy. The only advantage of this method is that it
336 /// enables more aggressive compiler optimizations.
337 ///
338 /// # Examples
339 ///
340 /// ```
341 /// let s: &str = "123";
342 /// let ptr: *const u8 = s.as_ptr();
343 ///
344 /// unsafe {
345 /// assert_eq!(*ptr.offset(1) as char, '2');
346 /// assert_eq!(*ptr.offset(2) as char, '3');
347 /// }
348 /// ```
349 #[stable(feature = "rust1", since = "1.0.0")]
350 #[must_use = "returns a new pointer rather than modifying its argument"]
351 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
352 #[inline(always)]
353 #[track_caller]
354 pub const unsafe fn offset(self, count: isize) -> *const T
355 where
356 T: Sized,
357 {
358 #[inline]
359 #[rustc_allow_const_fn_unstable(const_eval_select)]
360 const fn runtime_offset_nowrap(this: *const (), count: isize, size: usize) -> bool {
361 // We can use const_eval_select here because this is only for UB checks.
362 const_eval_select!(
363 @capture { this: *const (), count: isize, size: usize } -> bool:
364 if const {
365 true
366 } else {
367 // `size` is the size of a Rust type, so we know that
368 // `size <= isize::MAX` and thus `as` cast here is not lossy.
369 let Some(byte_offset) = count.checked_mul(size as isize) else {
370 return false;
371 };
372 let (_, overflow) = this.addr().overflowing_add_signed(byte_offset);
373 !overflow
374 }
375 )
376 }
377
378 ub_checks::assert_unsafe_precondition!(
379 check_language_ub,
380 "ptr::offset requires the address calculation to not overflow",
381 (
382 this: *const () = self as *const (),
383 count: isize = count,
384 size: usize = size_of::<T>(),
385 ) => runtime_offset_nowrap(this, count, size)
386 );
387
388 // SAFETY: the caller must uphold the safety contract for `offset`.
389 unsafe { intrinsics::offset(self, count) }
390 }
391
392 /// Adds a signed offset in bytes to a pointer.
393 ///
394 /// `count` is in units of **bytes**.
395 ///
396 /// This is purely a convenience for casting to a `u8` pointer and
397 /// using [offset][pointer::offset] on it. See that method for documentation
398 /// and safety requirements.
399 ///
400 /// For non-`Sized` pointees this operation changes only the data pointer,
401 /// leaving the metadata untouched.
402 #[must_use]
403 #[inline(always)]
404 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
405 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
406 #[track_caller]
407 pub const unsafe fn byte_offset(self, count: isize) -> Self {
408 // SAFETY: the caller must uphold the safety contract for `offset`.
409 unsafe { self.cast::<u8>().offset(count).with_metadata_of(self) }
410 }
411
412 /// Adds a signed offset to a pointer using wrapping arithmetic.
413 ///
414 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
415 /// offset of `3 * size_of::<T>()` bytes.
416 ///
417 /// # Safety
418 ///
419 /// This operation itself is always safe, but using the resulting pointer is not.
420 ///
421 /// The resulting pointer "remembers" the [allocation] that `self` points to
422 /// (this is called "[Provenance](ptr/index.html#provenance)").
423 /// The pointer must not be used to read or write other allocations.
424 ///
425 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
426 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
427 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
428 /// `x` and `y` point into the same allocation.
429 ///
430 /// Compared to [`offset`], this method basically delays the requirement of staying within the
431 /// same allocation: [`offset`] is immediate Undefined Behavior when crossing object
432 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
433 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
434 /// can be optimized better and is thus preferable in performance-sensitive code.
435 ///
436 /// The delayed check only considers the value of the pointer that was dereferenced, not the
437 /// intermediate values used during the computation of the final result. For example,
438 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
439 /// words, leaving the allocation and then re-entering it later is permitted.
440 ///
441 /// [`offset`]: #method.offset
442 /// [allocation]: crate::ptr#allocation
443 ///
444 /// # Examples
445 ///
446 /// ```
447 /// # use std::fmt::Write;
448 /// // Iterate using a raw pointer in increments of two elements
449 /// let data = [1u8, 2, 3, 4, 5];
450 /// let mut ptr: *const u8 = data.as_ptr();
451 /// let step = 2;
452 /// let end_rounded_up = ptr.wrapping_offset(6);
453 ///
454 /// let mut out = String::new();
455 /// while ptr != end_rounded_up {
456 /// unsafe {
457 /// write!(&mut out, "{}, ", *ptr)?;
458 /// }
459 /// ptr = ptr.wrapping_offset(step);
460 /// }
461 /// assert_eq!(out.as_str(), "1, 3, 5, ");
462 /// # std::fmt::Result::Ok(())
463 /// ```
464 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
465 #[must_use = "returns a new pointer rather than modifying its argument"]
466 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
467 #[inline(always)]
468 pub const fn wrapping_offset(self, count: isize) -> *const T
469 where
470 T: Sized,
471 {
472 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
473 unsafe { intrinsics::arith_offset(self, count) }
474 }
475
476 /// Adds a signed offset in bytes to a pointer using wrapping arithmetic.
477 ///
478 /// `count` is in units of **bytes**.
479 ///
480 /// This is purely a convenience for casting to a `u8` pointer and
481 /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
482 /// for documentation.
483 ///
484 /// For non-`Sized` pointees this operation changes only the data pointer,
485 /// leaving the metadata untouched.
486 #[must_use]
487 #[inline(always)]
488 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
489 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
490 pub const fn wrapping_byte_offset(self, count: isize) -> Self {
491 self.cast::<u8>().wrapping_offset(count).with_metadata_of(self)
492 }
493
494 /// Masks out bits of the pointer according to a mask.
495 ///
496 /// This is convenience for `ptr.map_addr(|a| a & mask)`.
497 ///
498 /// For non-`Sized` pointees this operation changes only the data pointer,
499 /// leaving the metadata untouched.
500 ///
501 /// ## Examples
502 ///
503 /// ```
504 /// #![feature(ptr_mask)]
505 /// let v = 17_u32;
506 /// let ptr: *const u32 = &v;
507 ///
508 /// // `u32` is 4 bytes aligned,
509 /// // which means that lower 2 bits are always 0.
510 /// let tag_mask = 0b11;
511 /// let ptr_mask = !tag_mask;
512 ///
513 /// // We can store something in these lower bits
514 /// let tagged_ptr = ptr.map_addr(|a| a | 0b10);
515 ///
516 /// // Get the "tag" back
517 /// let tag = tagged_ptr.addr() & tag_mask;
518 /// assert_eq!(tag, 0b10);
519 ///
520 /// // Note that `tagged_ptr` is unaligned, it's UB to read from it.
521 /// // To get original pointer `mask` can be used:
522 /// let masked_ptr = tagged_ptr.mask(ptr_mask);
523 /// assert_eq!(unsafe { *masked_ptr }, 17);
524 /// ```
525 #[unstable(feature = "ptr_mask", issue = "98290")]
526 #[must_use = "returns a new pointer rather than modifying its argument"]
527 #[inline(always)]
528 pub fn mask(self, mask: usize) -> *const T {
529 intrinsics::ptr_mask(self.cast::<()>(), mask).with_metadata_of(self)
530 }
531
532 /// Calculates the distance between two pointers within the same allocation. The returned value is in
533 /// units of T: the distance in bytes divided by `size_of::<T>()`.
534 ///
535 /// This is equivalent to `(self as isize - origin as isize) / (size_of::<T>() as isize)`,
536 /// except that it has a lot more opportunities for UB, in exchange for the compiler
537 /// better understanding what you are doing.
538 ///
539 /// The primary motivation of this method is for computing the `len` of an array/slice
540 /// of `T` that you are currently representing as a "start" and "end" pointer
541 /// (and "end" is "one past the end" of the array).
542 /// In that case, `end.offset_from(start)` gets you the length of the array.
543 ///
544 /// All of the following safety requirements are trivially satisfied for this usecase.
545 ///
546 /// [`offset`]: #method.offset
547 ///
548 /// # Safety
549 ///
550 /// If any of the following conditions are violated, the result is Undefined Behavior:
551 ///
552 /// * `self` and `origin` must either
553 ///
554 /// * point to the same address, or
555 /// * both be [derived from][crate::ptr#provenance] a pointer to the same [allocation], and the memory range between
556 /// the two pointers must be in bounds of that object. (See below for an example.)
557 ///
558 /// * The distance between the pointers, in bytes, must be an exact multiple
559 /// of the size of `T`.
560 ///
561 /// As a consequence, the absolute distance between the pointers, in bytes, computed on
562 /// mathematical integers (without "wrapping around"), cannot overflow an `isize`. This is
563 /// implied by the in-bounds requirement, and the fact that no allocation can be larger
564 /// than `isize::MAX` bytes.
565 ///
566 /// The requirement for pointers to be derived from the same allocation is primarily
567 /// needed for `const`-compatibility: the distance between pointers into *different* allocated
568 /// objects is not known at compile-time. However, the requirement also exists at
569 /// runtime and may be exploited by optimizations. If you wish to compute the difference between
570 /// pointers that are not guaranteed to be from the same allocation, use
571 /// `(self.addr() as isize - origin.addr() as isize) / size_of::<T>()`.
572 ///
573 /// [`add`]: #method.add
574 /// [allocation]: crate::ptr#allocation
575 ///
576 /// # Panics
577 ///
578 /// This function panics if `T` is a Zero-Sized Type ("ZST").
579 ///
580 /// # Examples
581 ///
582 /// Basic usage:
583 ///
584 /// ```
585 /// let a = [0; 5];
586 /// let ptr1: *const i32 = &a[1];
587 /// let ptr2: *const i32 = &a[3];
588 /// unsafe {
589 /// assert_eq!(ptr2.offset_from(ptr1), 2);
590 /// assert_eq!(ptr1.offset_from(ptr2), -2);
591 /// assert_eq!(ptr1.offset(2), ptr2);
592 /// assert_eq!(ptr2.offset(-2), ptr1);
593 /// }
594 /// ```
595 ///
596 /// *Incorrect* usage:
597 ///
598 /// ```rust,no_run
599 /// let ptr1 = Box::into_raw(Box::new(0u8)) as *const u8;
600 /// let ptr2 = Box::into_raw(Box::new(1u8)) as *const u8;
601 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
602 /// // Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.
603 /// let ptr2_other = (ptr1 as *const u8).wrapping_offset(diff).wrapping_offset(1);
604 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
605 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
606 /// // computing their offset is undefined behavior, even though
607 /// // they point to addresses that are in-bounds of the same object!
608 /// unsafe {
609 /// let one = ptr2_other.offset_from(ptr2); // Undefined Behavior! ⚠️
610 /// }
611 /// ```
612 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
613 #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
614 #[inline(always)]
615 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
616 pub const unsafe fn offset_from(self, origin: *const T) -> isize
617 where
618 T: Sized,
619 {
620 let pointee_size = size_of::<T>();
621 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
622 // SAFETY: the caller must uphold the safety contract for `ptr_offset_from`.
623 unsafe { intrinsics::ptr_offset_from(self, origin) }
624 }
625
626 /// Calculates the distance between two pointers within the same allocation. The returned value is in
627 /// units of **bytes**.
628 ///
629 /// This is purely a convenience for casting to a `u8` pointer and
630 /// using [`offset_from`][pointer::offset_from] on it. See that method for
631 /// documentation and safety requirements.
632 ///
633 /// For non-`Sized` pointees this operation considers only the data pointers,
634 /// ignoring the metadata.
635 #[inline(always)]
636 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
637 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
638 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
639 pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: *const U) -> isize {
640 // SAFETY: the caller must uphold the safety contract for `offset_from`.
641 unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
642 }
643
644 /// Calculates the distance between two pointers within the same allocation, *where it's known that
645 /// `self` is equal to or greater than `origin`*. The returned value is in
646 /// units of T: the distance in bytes is divided by `size_of::<T>()`.
647 ///
648 /// This computes the same value that [`offset_from`](#method.offset_from)
649 /// would compute, but with the added precondition that the offset is
650 /// guaranteed to be non-negative. This method is equivalent to
651 /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`,
652 /// but it provides slightly more information to the optimizer, which can
653 /// sometimes allow it to optimize slightly better with some backends.
654 ///
655 /// This method can be thought of as recovering the `count` that was passed
656 /// to [`add`](#method.add) (or, with the parameters in the other order,
657 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
658 /// that their safety preconditions are met:
659 /// ```rust
660 /// # unsafe fn blah(ptr: *const i32, origin: *const i32, count: usize) -> bool { unsafe {
661 /// ptr.offset_from_unsigned(origin) == count
662 /// # &&
663 /// origin.add(count) == ptr
664 /// # &&
665 /// ptr.sub(count) == origin
666 /// # } }
667 /// ```
668 ///
669 /// # Safety
670 ///
671 /// - The distance between the pointers must be non-negative (`self >= origin`)
672 ///
673 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
674 /// apply to this method as well; see it for the full details.
675 ///
676 /// Importantly, despite the return type of this method being able to represent
677 /// a larger offset, it's still *not permitted* to pass pointers which differ
678 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
679 /// always be less than or equal to `isize::MAX as usize`.
680 ///
681 /// # Panics
682 ///
683 /// This function panics if `T` is a Zero-Sized Type ("ZST").
684 ///
685 /// # Examples
686 ///
687 /// ```
688 /// let a = [0; 5];
689 /// let ptr1: *const i32 = &a[1];
690 /// let ptr2: *const i32 = &a[3];
691 /// unsafe {
692 /// assert_eq!(ptr2.offset_from_unsigned(ptr1), 2);
693 /// assert_eq!(ptr1.add(2), ptr2);
694 /// assert_eq!(ptr2.sub(2), ptr1);
695 /// assert_eq!(ptr2.offset_from_unsigned(ptr2), 0);
696 /// }
697 ///
698 /// // This would be incorrect, as the pointers are not correctly ordered:
699 /// // ptr1.offset_from_unsigned(ptr2)
700 /// ```
701 #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
702 #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
703 #[inline]
704 #[track_caller]
705 pub const unsafe fn offset_from_unsigned(self, origin: *const T) -> usize
706 where
707 T: Sized,
708 {
709 #[rustc_allow_const_fn_unstable(const_eval_select)]
710 const fn runtime_ptr_ge(this: *const (), origin: *const ()) -> bool {
711 const_eval_select!(
712 @capture { this: *const (), origin: *const () } -> bool:
713 if const {
714 true
715 } else {
716 this >= origin
717 }
718 )
719 }
720
721 ub_checks::assert_unsafe_precondition!(
722 check_language_ub,
723 "ptr::offset_from_unsigned requires `self >= origin`",
724 (
725 this: *const () = self as *const (),
726 origin: *const () = origin as *const (),
727 ) => runtime_ptr_ge(this, origin)
728 );
729
730 let pointee_size = size_of::<T>();
731 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
732 // SAFETY: the caller must uphold the safety contract for `ptr_offset_from_unsigned`.
733 unsafe { intrinsics::ptr_offset_from_unsigned(self, origin) }
734 }
735
736 /// Calculates the distance between two pointers within the same allocation, *where it's known that
737 /// `self` is equal to or greater than `origin`*. The returned value is in
738 /// units of **bytes**.
739 ///
740 /// This is purely a convenience for casting to a `u8` pointer and
741 /// using [`offset_from_unsigned`][pointer::offset_from_unsigned] on it.
742 /// See that method for documentation and safety requirements.
743 ///
744 /// For non-`Sized` pointees this operation considers only the data pointers,
745 /// ignoring the metadata.
746 #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
747 #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
748 #[inline]
749 #[track_caller]
750 pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: *const U) -> usize {
751 // SAFETY: the caller must uphold the safety contract for `offset_from_unsigned`.
752 unsafe { self.cast::<u8>().offset_from_unsigned(origin.cast::<u8>()) }
753 }
754
755 /// Returns whether two pointers are guaranteed to be equal.
756 ///
757 /// At runtime this function behaves like `Some(self == other)`.
758 /// However, in some contexts (e.g., compile-time evaluation),
759 /// it is not always possible to determine equality of two pointers, so this function may
760 /// spuriously return `None` for pointers that later actually turn out to have its equality known.
761 /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
762 ///
763 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
764 /// version and unsafe code must not
765 /// rely on the result of this function for soundness. It is suggested to only use this function
766 /// for performance optimizations where spurious `None` return values by this function do not
767 /// affect the outcome, but just the performance.
768 /// The consequences of using this method to make runtime and compile-time code behave
769 /// differently have not been explored. This method should not be used to introduce such
770 /// differences, and it should also not be stabilized before we have a better understanding
771 /// of this issue.
772 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
773 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
774 #[inline]
775 pub const fn guaranteed_eq(self, other: *const T) -> Option<bool>
776 where
777 T: Sized,
778 {
779 match intrinsics::ptr_guaranteed_cmp(self, other) {
780 2 => None,
781 other => Some(other == 1),
782 }
783 }
784
785 /// Returns whether two pointers are guaranteed to be inequal.
786 ///
787 /// At runtime this function behaves like `Some(self != other)`.
788 /// However, in some contexts (e.g., compile-time evaluation),
789 /// it is not always possible to determine inequality of two pointers, so this function may
790 /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
791 /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
792 ///
793 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
794 /// version and unsafe code must not
795 /// rely on the result of this function for soundness. It is suggested to only use this function
796 /// for performance optimizations where spurious `None` return values by this function do not
797 /// affect the outcome, but just the performance.
798 /// The consequences of using this method to make runtime and compile-time code behave
799 /// differently have not been explored. This method should not be used to introduce such
800 /// differences, and it should also not be stabilized before we have a better understanding
801 /// of this issue.
802 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
803 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
804 #[inline]
805 pub const fn guaranteed_ne(self, other: *const T) -> Option<bool>
806 where
807 T: Sized,
808 {
809 match self.guaranteed_eq(other) {
810 None => None,
811 Some(eq) => Some(!eq),
812 }
813 }
814
815 #[doc = include_str!("./docs/add.md")]
816 ///
817 /// Consider using [`wrapping_add`](#method.wrapping_add) instead if these constraints are
818 /// difficult to satisfy. The only advantage of this method is that it
819 /// enables more aggressive compiler optimizations.
820 ///
821 /// # Examples
822 ///
823 /// ```
824 /// let s: &str = "123";
825 /// let ptr: *const u8 = s.as_ptr();
826 ///
827 /// unsafe {
828 /// assert_eq!(*ptr.add(1), b'2');
829 /// assert_eq!(*ptr.add(2), b'3');
830 /// }
831 /// ```
832 #[stable(feature = "pointer_methods", since = "1.26.0")]
833 #[must_use = "returns a new pointer rather than modifying its argument"]
834 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
835 #[inline(always)]
836 #[track_caller]
837 pub const unsafe fn add(self, count: usize) -> Self
838 where
839 T: Sized,
840 {
841 #[cfg(debug_assertions)]
842 #[inline]
843 #[rustc_allow_const_fn_unstable(const_eval_select)]
844 const fn runtime_add_nowrap(this: *const (), count: usize, size: usize) -> bool {
845 const_eval_select!(
846 @capture { this: *const (), count: usize, size: usize } -> bool:
847 if const {
848 true
849 } else {
850 let Some(byte_offset) = count.checked_mul(size) else {
851 return false;
852 };
853 let (_, overflow) = this.addr().overflowing_add(byte_offset);
854 byte_offset <= (isize::MAX as usize) && !overflow
855 }
856 )
857 }
858
859 #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
860 ub_checks::assert_unsafe_precondition!(
861 check_language_ub,
862 "ptr::add requires that the address calculation does not overflow",
863 (
864 this: *const () = self as *const (),
865 count: usize = count,
866 size: usize = size_of::<T>(),
867 ) => runtime_add_nowrap(this, count, size)
868 );
869
870 // SAFETY: the caller must uphold the safety contract for `offset`.
871 unsafe { intrinsics::offset(self, count) }
872 }
873
874 /// Adds an unsigned offset in bytes to a pointer.
875 ///
876 /// `count` is in units of bytes.
877 ///
878 /// This is purely a convenience for casting to a `u8` pointer and
879 /// using [add][pointer::add] on it. See that method for documentation
880 /// and safety requirements.
881 ///
882 /// For non-`Sized` pointees this operation changes only the data pointer,
883 /// leaving the metadata untouched.
884 #[must_use]
885 #[inline(always)]
886 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
887 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
888 #[track_caller]
889 pub const unsafe fn byte_add(self, count: usize) -> Self {
890 // SAFETY: the caller must uphold the safety contract for `add`.
891 unsafe { self.cast::<u8>().add(count).with_metadata_of(self) }
892 }
893
894 #[doc = include_str!("./docs/sub.md")]
895 ///
896 /// Consider using [`wrapping_sub`](#method.wrapping_sub) instead if these constraints are
897 /// difficult to satisfy. The only advantage of this method is that it
898 /// enables more aggressive compiler optimizations.
899 ///
900 /// # Examples
901 ///
902 /// ```
903 /// let s: &str = "123";
904 ///
905 /// unsafe {
906 /// let end: *const u8 = s.as_ptr().add(3);
907 /// assert_eq!(*end.sub(1), b'3');
908 /// assert_eq!(*end.sub(2), b'2');
909 /// }
910 /// ```
911 #[stable(feature = "pointer_methods", since = "1.26.0")]
912 #[must_use = "returns a new pointer rather than modifying its argument"]
913 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
914 #[inline(always)]
915 #[track_caller]
916 pub const unsafe fn sub(self, count: usize) -> Self
917 where
918 T: Sized,
919 {
920 #[cfg(debug_assertions)]
921 #[inline]
922 #[rustc_allow_const_fn_unstable(const_eval_select)]
923 const fn runtime_sub_nowrap(this: *const (), count: usize, size: usize) -> bool {
924 const_eval_select!(
925 @capture { this: *const (), count: usize, size: usize } -> bool:
926 if const {
927 true
928 } else {
929 let Some(byte_offset) = count.checked_mul(size) else {
930 return false;
931 };
932 byte_offset <= (isize::MAX as usize) && this.addr() >= byte_offset
933 }
934 )
935 }
936
937 #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
938 ub_checks::assert_unsafe_precondition!(
939 check_language_ub,
940 "ptr::sub requires that the address calculation does not overflow",
941 (
942 this: *const () = self as *const (),
943 count: usize = count,
944 size: usize = size_of::<T>(),
945 ) => runtime_sub_nowrap(this, count, size)
946 );
947
948 if T::IS_ZST {
949 // Pointer arithmetic does nothing when the pointee is a ZST.
950 self
951 } else {
952 // SAFETY: the caller must uphold the safety contract for `offset`.
953 // Because the pointee is *not* a ZST, that means that `count` is
954 // at most `isize::MAX`, and thus the negation cannot overflow.
955 unsafe { intrinsics::offset(self, intrinsics::unchecked_sub(0, count as isize)) }
956 }
957 }
958
959 /// Subtracts an unsigned offset in bytes from a pointer.
960 ///
961 /// `count` is in units of bytes.
962 ///
963 /// This is purely a convenience for casting to a `u8` pointer and
964 /// using [sub][pointer::sub] on it. See that method for documentation
965 /// and safety requirements.
966 ///
967 /// For non-`Sized` pointees this operation changes only the data pointer,
968 /// leaving the metadata untouched.
969 #[must_use]
970 #[inline(always)]
971 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
972 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
973 #[track_caller]
974 pub const unsafe fn byte_sub(self, count: usize) -> Self {
975 // SAFETY: the caller must uphold the safety contract for `sub`.
976 unsafe { self.cast::<u8>().sub(count).with_metadata_of(self) }
977 }
978
979 /// Adds an unsigned offset to a pointer using wrapping arithmetic.
980 ///
981 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
982 /// offset of `3 * size_of::<T>()` bytes.
983 ///
984 /// # Safety
985 ///
986 /// This operation itself is always safe, but using the resulting pointer is not.
987 ///
988 /// The resulting pointer "remembers" the [allocation] that `self` points to; it must not
989 /// be used to read or write other allocations.
990 ///
991 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
992 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
993 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
994 /// `x` and `y` point into the same allocation.
995 ///
996 /// Compared to [`add`], this method basically delays the requirement of staying within the
997 /// same allocation: [`add`] is immediate Undefined Behavior when crossing object
998 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
999 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1000 /// can be optimized better and is thus preferable in performance-sensitive code.
1001 ///
1002 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1003 /// intermediate values used during the computation of the final result. For example,
1004 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1005 /// allocation and then re-entering it later is permitted.
1006 ///
1007 /// [`add`]: #method.add
1008 /// [allocation]: crate::ptr#allocation
1009 ///
1010 /// # Examples
1011 ///
1012 /// ```
1013 /// # use std::fmt::Write;
1014 /// // Iterate using a raw pointer in increments of two elements
1015 /// let data = [1u8, 2, 3, 4, 5];
1016 /// let mut ptr: *const u8 = data.as_ptr();
1017 /// let step = 2;
1018 /// let end_rounded_up = ptr.wrapping_add(6);
1019 ///
1020 /// let mut out = String::new();
1021 /// while ptr != end_rounded_up {
1022 /// unsafe {
1023 /// write!(&mut out, "{}, ", *ptr)?;
1024 /// }
1025 /// ptr = ptr.wrapping_add(step);
1026 /// }
1027 /// assert_eq!(out, "1, 3, 5, ");
1028 /// # std::fmt::Result::Ok(())
1029 /// ```
1030 #[stable(feature = "pointer_methods", since = "1.26.0")]
1031 #[must_use = "returns a new pointer rather than modifying its argument"]
1032 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1033 #[allow(clippy::ptr_offset_with_cast)]
1034 #[inline(always)]
1035 pub const fn wrapping_add(self, count: usize) -> Self
1036 where
1037 T: Sized,
1038 {
1039 self.wrapping_offset(count as isize)
1040 }
1041
1042 /// Adds an unsigned offset in bytes to a pointer using wrapping arithmetic.
1043 ///
1044 /// `count` is in units of bytes.
1045 ///
1046 /// This is purely a convenience for casting to a `u8` pointer and
1047 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1048 ///
1049 /// For non-`Sized` pointees this operation changes only the data pointer,
1050 /// leaving the metadata untouched.
1051 #[must_use]
1052 #[inline(always)]
1053 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1054 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1055 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1056 self.cast::<u8>().wrapping_add(count).with_metadata_of(self)
1057 }
1058
1059 /// Subtracts an unsigned offset from a pointer using wrapping arithmetic.
1060 ///
1061 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1062 /// offset of `3 * size_of::<T>()` bytes.
1063 ///
1064 /// # Safety
1065 ///
1066 /// This operation itself is always safe, but using the resulting pointer is not.
1067 ///
1068 /// The resulting pointer "remembers" the [allocation] that `self` points to; it must not
1069 /// be used to read or write other allocations.
1070 ///
1071 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1072 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1073 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1074 /// `x` and `y` point into the same allocation.
1075 ///
1076 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1077 /// same allocation: [`sub`] is immediate Undefined Behavior when crossing object
1078 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1079 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1080 /// can be optimized better and is thus preferable in performance-sensitive code.
1081 ///
1082 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1083 /// intermediate values used during the computation of the final result. For example,
1084 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1085 /// allocation and then re-entering it later is permitted.
1086 ///
1087 /// [`sub`]: #method.sub
1088 /// [allocation]: crate::ptr#allocation
1089 ///
1090 /// # Examples
1091 ///
1092 /// ```
1093 /// # use std::fmt::Write;
1094 /// // Iterate using a raw pointer in increments of two elements (backwards)
1095 /// let data = [1u8, 2, 3, 4, 5];
1096 /// let mut ptr: *const u8 = data.as_ptr();
1097 /// let start_rounded_down = ptr.wrapping_sub(2);
1098 /// ptr = ptr.wrapping_add(4);
1099 /// let step = 2;
1100 /// let mut out = String::new();
1101 /// while ptr != start_rounded_down {
1102 /// unsafe {
1103 /// write!(&mut out, "{}, ", *ptr)?;
1104 /// }
1105 /// ptr = ptr.wrapping_sub(step);
1106 /// }
1107 /// assert_eq!(out, "5, 3, 1, ");
1108 /// # std::fmt::Result::Ok(())
1109 /// ```
1110 #[stable(feature = "pointer_methods", since = "1.26.0")]
1111 #[must_use = "returns a new pointer rather than modifying its argument"]
1112 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1113 #[inline(always)]
1114 pub const fn wrapping_sub(self, count: usize) -> Self
1115 where
1116 T: Sized,
1117 {
1118 self.wrapping_offset((count as isize).wrapping_neg())
1119 }
1120
1121 /// Subtracts an unsigned offset in bytes from a pointer using wrapping arithmetic.
1122 ///
1123 /// `count` is in units of bytes.
1124 ///
1125 /// This is purely a convenience for casting to a `u8` pointer and
1126 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1127 ///
1128 /// For non-`Sized` pointees this operation changes only the data pointer,
1129 /// leaving the metadata untouched.
1130 #[must_use]
1131 #[inline(always)]
1132 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1133 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1134 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1135 self.cast::<u8>().wrapping_sub(count).with_metadata_of(self)
1136 }
1137
1138 /// Reads the value from `self` without moving it. This leaves the
1139 /// memory in `self` unchanged.
1140 ///
1141 /// See [`ptr::read`] for safety concerns and examples.
1142 ///
1143 /// [`ptr::read`]: crate::ptr::read()
1144 #[stable(feature = "pointer_methods", since = "1.26.0")]
1145 #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1146 #[inline(always)]
1147 #[track_caller]
1148 pub const unsafe fn read(self) -> T
1149 where
1150 T: Sized,
1151 {
1152 // SAFETY: the caller must uphold the safety contract for `read`.
1153 unsafe { read(self) }
1154 }
1155
1156 /// Performs a volatile read of the value from `self` without moving it. This
1157 /// leaves the memory in `self` unchanged.
1158 ///
1159 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1160 /// to not be elided or reordered by the compiler across other volatile
1161 /// operations.
1162 ///
1163 /// See [`ptr::read_volatile`] for safety concerns and examples.
1164 ///
1165 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1166 #[stable(feature = "pointer_methods", since = "1.26.0")]
1167 #[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
1168 #[inline(always)]
1169 #[track_caller]
1170 pub const unsafe fn read_volatile(self) -> T
1171 where
1172 T: Sized,
1173 {
1174 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1175 unsafe { read_volatile(self) }
1176 }
1177
1178 /// Reads the value from `self` without moving it. This leaves the
1179 /// memory in `self` unchanged.
1180 ///
1181 /// Unlike `read`, the pointer may be unaligned.
1182 ///
1183 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1184 ///
1185 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1186 #[stable(feature = "pointer_methods", since = "1.26.0")]
1187 #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1188 #[inline(always)]
1189 #[track_caller]
1190 pub const unsafe fn read_unaligned(self) -> T
1191 where
1192 T: Sized,
1193 {
1194 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1195 unsafe { read_unaligned(self) }
1196 }
1197
1198 /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1199 /// and destination may overlap.
1200 ///
1201 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1202 ///
1203 /// See [`ptr::copy`] for safety concerns and examples.
1204 ///
1205 /// [`ptr::copy`]: crate::ptr::copy()
1206 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1207 #[stable(feature = "pointer_methods", since = "1.26.0")]
1208 #[inline(always)]
1209 #[track_caller]
1210 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1211 where
1212 T: Sized,
1213 {
1214 // SAFETY: the caller must uphold the safety contract for `copy`.
1215 unsafe { copy(self, dest, count) }
1216 }
1217
1218 /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1219 /// and destination may *not* overlap.
1220 ///
1221 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1222 ///
1223 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1224 ///
1225 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1226 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1227 #[stable(feature = "pointer_methods", since = "1.26.0")]
1228 #[inline(always)]
1229 #[track_caller]
1230 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1231 where
1232 T: Sized,
1233 {
1234 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1235 unsafe { copy_nonoverlapping(self, dest, count) }
1236 }
1237
1238 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1239 /// `align`.
1240 ///
1241 /// If it is not possible to align the pointer, the implementation returns
1242 /// `usize::MAX`.
1243 ///
1244 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1245 /// used with the `wrapping_add` method.
1246 ///
1247 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1248 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1249 /// the returned offset is correct in all terms other than alignment.
1250 ///
1251 /// # Panics
1252 ///
1253 /// The function panics if `align` is not a power-of-two.
1254 ///
1255 /// # Examples
1256 ///
1257 /// Accessing adjacent `u8` as `u16`
1258 ///
1259 /// ```
1260 /// # unsafe {
1261 /// let x = [5_u8, 6, 7, 8, 9];
1262 /// let ptr = x.as_ptr();
1263 /// let offset = ptr.align_offset(align_of::<u16>());
1264 ///
1265 /// if offset < x.len() - 1 {
1266 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1267 /// assert!(*u16_ptr == u16::from_ne_bytes([5, 6]) || *u16_ptr == u16::from_ne_bytes([6, 7]));
1268 /// } else {
1269 /// // while the pointer can be aligned via `offset`, it would point
1270 /// // outside the allocation
1271 /// }
1272 /// # }
1273 /// ```
1274 #[must_use]
1275 #[inline]
1276 #[stable(feature = "align_offset", since = "1.36.0")]
1277 pub fn align_offset(self, align: usize) -> usize
1278 where
1279 T: Sized,
1280 {
1281 if !align.is_power_of_two() {
1282 panic!("align_offset: align is not a power-of-two");
1283 }
1284
1285 // SAFETY: `align` has been checked to be a power of 2 above
1286 let ret = unsafe { align_offset(self, align) };
1287
1288 // Inform Miri that we want to consider the resulting pointer to be suitably aligned.
1289 #[cfg(miri)]
1290 if ret != usize::MAX {
1291 intrinsics::miri_promise_symbolic_alignment(self.wrapping_add(ret).cast(), align);
1292 }
1293
1294 ret
1295 }
1296
1297 /// Returns whether the pointer is properly aligned for `T`.
1298 ///
1299 /// # Examples
1300 ///
1301 /// ```
1302 /// // On some platforms, the alignment of i32 is less than 4.
1303 /// #[repr(align(4))]
1304 /// struct AlignedI32(i32);
1305 ///
1306 /// let data = AlignedI32(42);
1307 /// let ptr = &data as *const AlignedI32;
1308 ///
1309 /// assert!(ptr.is_aligned());
1310 /// assert!(!ptr.wrapping_byte_add(1).is_aligned());
1311 /// ```
1312 #[must_use]
1313 #[inline]
1314 #[stable(feature = "pointer_is_aligned", since = "1.79.0")]
1315 pub fn is_aligned(self) -> bool
1316 where
1317 T: Sized,
1318 {
1319 self.is_aligned_to(align_of::<T>())
1320 }
1321
1322 /// Returns whether the pointer is aligned to `align`.
1323 ///
1324 /// For non-`Sized` pointees this operation considers only the data pointer,
1325 /// ignoring the metadata.
1326 ///
1327 /// # Panics
1328 ///
1329 /// The function panics if `align` is not a power-of-two (this includes 0).
1330 ///
1331 /// # Examples
1332 ///
1333 /// ```
1334 /// #![feature(pointer_is_aligned_to)]
1335 ///
1336 /// // On some platforms, the alignment of i32 is less than 4.
1337 /// #[repr(align(4))]
1338 /// struct AlignedI32(i32);
1339 ///
1340 /// let data = AlignedI32(42);
1341 /// let ptr = &data as *const AlignedI32;
1342 ///
1343 /// assert!(ptr.is_aligned_to(1));
1344 /// assert!(ptr.is_aligned_to(2));
1345 /// assert!(ptr.is_aligned_to(4));
1346 ///
1347 /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1348 /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1349 ///
1350 /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1351 /// ```
1352 #[must_use]
1353 #[inline]
1354 #[unstable(feature = "pointer_is_aligned_to", issue = "96284")]
1355 pub fn is_aligned_to(self, align: usize) -> bool {
1356 if !align.is_power_of_two() {
1357 panic!("is_aligned_to: align is not a power-of-two");
1358 }
1359
1360 self.addr() & (align - 1) == 0
1361 }
1362}
1363
1364impl<T> *const T {
1365 /// Casts from a type to its maybe-uninitialized version.
1366 #[must_use]
1367 #[inline(always)]
1368 #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1369 pub const fn cast_uninit(self) -> *const MaybeUninit<T> {
1370 self as _
1371 }
1372
1373 /// Forms a raw slice from a pointer and a length.
1374 ///
1375 /// The `len` argument is the number of **elements**, not the number of bytes.
1376 ///
1377 /// This function is safe, but actually using the return value is unsafe.
1378 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
1379 ///
1380 /// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
1381 ///
1382 /// # Examples
1383 ///
1384 /// ```rust
1385 /// #![feature(ptr_cast_slice)]
1386 ///
1387 /// // create a slice pointer when starting out with a pointer to the first element
1388 /// let x = [5, 6, 7];
1389 /// let raw_slice = x.as_ptr().cast_slice(3);
1390 /// assert_eq!(unsafe { &*raw_slice }[2], 7);
1391 /// ```
1392 ///
1393 /// You must ensure that the pointer is valid and not null before dereferencing
1394 /// the raw slice. A slice reference must never have a null pointer, even if it's empty.
1395 ///
1396 /// ```rust,should_panic
1397 /// #![feature(ptr_cast_slice)]
1398 /// use std::ptr;
1399 /// let danger: *const [u8] = ptr::null::<u8>().cast_slice(0);
1400 /// unsafe {
1401 /// danger.as_ref().expect("references must not be null");
1402 /// }
1403 /// ```
1404 #[inline]
1405 #[unstable(feature = "ptr_cast_slice", issue = "149103")]
1406 pub const fn cast_slice(self, len: usize) -> *const [T] {
1407 slice_from_raw_parts(self, len)
1408 }
1409}
1410impl<T> *const MaybeUninit<T> {
1411 /// Casts from a maybe-uninitialized type to its initialized version.
1412 ///
1413 /// This is always safe, since UB can only occur if the pointer is read
1414 /// before being initialized.
1415 #[must_use]
1416 #[inline(always)]
1417 #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1418 pub const fn cast_init(self) -> *const T {
1419 self as _
1420 }
1421}
1422
1423impl<T> *const [T] {
1424 /// Returns the length of a raw slice.
1425 ///
1426 /// The returned value is the number of **elements**, not the number of bytes.
1427 ///
1428 /// This function is safe, even when the raw slice cannot be cast to a slice
1429 /// reference because the pointer is null or unaligned.
1430 ///
1431 /// # Examples
1432 ///
1433 /// ```rust
1434 /// use std::ptr;
1435 ///
1436 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1437 /// assert_eq!(slice.len(), 3);
1438 /// ```
1439 #[inline(always)]
1440 #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1441 #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1442 pub const fn len(self) -> usize {
1443 metadata(self)
1444 }
1445
1446 /// Returns `true` if the raw slice has a length of 0.
1447 ///
1448 /// # Examples
1449 ///
1450 /// ```
1451 /// use std::ptr;
1452 ///
1453 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1454 /// assert!(!slice.is_empty());
1455 /// ```
1456 #[inline(always)]
1457 #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1458 #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1459 pub const fn is_empty(self) -> bool {
1460 self.len() == 0
1461 }
1462
1463 /// Returns a raw pointer to the slice's buffer.
1464 ///
1465 /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1466 ///
1467 /// # Examples
1468 ///
1469 /// ```rust
1470 /// #![feature(slice_ptr_get)]
1471 /// use std::ptr;
1472 ///
1473 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1474 /// assert_eq!(slice.as_ptr(), ptr::null());
1475 /// ```
1476 #[inline(always)]
1477 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1478 pub const fn as_ptr(self) -> *const T {
1479 self as *const T
1480 }
1481
1482 /// Gets a raw pointer to the underlying array.
1483 ///
1484 /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
1485 #[stable(feature = "core_slice_as_array", since = "1.93.0")]
1486 #[rustc_const_stable(feature = "core_slice_as_array", since = "1.93.0")]
1487 #[inline]
1488 #[must_use]
1489 pub const fn as_array<const N: usize>(self) -> Option<*const [T; N]> {
1490 if self.len() == N {
1491 let me = self.as_ptr() as *const [T; N];
1492 Some(me)
1493 } else {
1494 None
1495 }
1496 }
1497
1498 /// Returns a raw pointer to an element or subslice, without doing bounds
1499 /// checking.
1500 ///
1501 /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
1502 /// is *[undefined behavior]* even if the resulting pointer is not used.
1503 ///
1504 /// [out-of-bounds index]: #method.add
1505 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1506 ///
1507 /// # Examples
1508 ///
1509 /// ```
1510 /// #![feature(slice_ptr_get)]
1511 ///
1512 /// let x = &[1, 2, 4] as *const [i32];
1513 ///
1514 /// unsafe {
1515 /// assert_eq!(x.get_unchecked(1), x.as_ptr().add(1));
1516 /// }
1517 /// ```
1518 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1519 #[rustc_const_unstable(feature = "const_index", issue = "143775")]
1520 #[inline(always)]
1521 pub const unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output
1522 where
1523 I: [const] SliceIndex<[T]>,
1524 {
1525 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1526 unsafe { index.get_unchecked(self) }
1527 }
1528
1529 #[doc = include_str!("docs/as_uninit_slice.md")]
1530 #[inline]
1531 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1532 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1533 if self.is_null() {
1534 None
1535 } else {
1536 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1537 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1538 }
1539 }
1540}
1541
1542impl<T> *const T {
1543 /// Casts from a pointer-to-`T` to a pointer-to-`[T; N]`.
1544 #[inline]
1545 #[unstable(feature = "ptr_cast_array", issue = "144514")]
1546 pub const fn cast_array<const N: usize>(self) -> *const [T; N] {
1547 self.cast()
1548 }
1549}
1550
1551impl<T, const N: usize> *const [T; N] {
1552 /// Returns a raw pointer to the array's buffer.
1553 ///
1554 /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1555 ///
1556 /// # Examples
1557 ///
1558 /// ```rust
1559 /// #![feature(array_ptr_get)]
1560 /// use std::ptr;
1561 ///
1562 /// let arr: *const [i8; 3] = ptr::null();
1563 /// assert_eq!(arr.as_ptr(), ptr::null());
1564 /// ```
1565 #[inline(always)]
1566 #[unstable(feature = "array_ptr_get", issue = "119834")]
1567 pub const fn as_ptr(self) -> *const T {
1568 self as *const T
1569 }
1570
1571 /// Returns a raw pointer to a slice containing the entire array.
1572 ///
1573 /// # Examples
1574 ///
1575 /// ```
1576 /// #![feature(array_ptr_get)]
1577 ///
1578 /// let arr: *const [i32; 3] = &[1, 2, 4] as *const [i32; 3];
1579 /// let slice: *const [i32] = arr.as_slice();
1580 /// assert_eq!(slice.len(), 3);
1581 /// ```
1582 #[inline]
1583 #[unstable(feature = "array_ptr_get", issue = "119834")]
1584 pub const fn as_slice(self) -> *const [T] {
1585 self
1586 }
1587}
1588
1589/// Pointer equality is by address, as produced by the [`<*const T>::addr`](pointer::addr) method.
1590#[stable(feature = "rust1", since = "1.0.0")]
1591#[diagnostic::on_const(
1592 message = "pointers cannot be reliably compared during const eval",
1593 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1594)]
1595impl<T: PointeeSized> PartialEq for *const T {
1596 #[inline(always)]
1597 #[allow(ambiguous_wide_pointer_comparisons)]
1598 fn eq(&self, other: &*const T) -> bool {
1599 *self == *other
1600 }
1601}
1602
1603/// Pointer equality is an equivalence relation.
1604#[stable(feature = "rust1", since = "1.0.0")]
1605#[diagnostic::on_const(
1606 message = "pointers cannot be reliably compared during const eval",
1607 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1608)]
1609impl<T: PointeeSized> Eq for *const T {}
1610
1611/// Pointer comparison is by address, as produced by the `[`<*const T>::addr`](pointer::addr)` method.
1612#[stable(feature = "rust1", since = "1.0.0")]
1613#[diagnostic::on_const(
1614 message = "pointers cannot be reliably compared during const eval",
1615 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1616)]
1617impl<T: PointeeSized> Ord for *const T {
1618 #[inline]
1619 #[allow(ambiguous_wide_pointer_comparisons)]
1620 fn cmp(&self, other: &*const T) -> Ordering {
1621 if self < other {
1622 Less
1623 } else if self == other {
1624 Equal
1625 } else {
1626 Greater
1627 }
1628 }
1629}
1630
1631/// Pointer comparison is by address, as produced by the `[`<*const T>::addr`](pointer::addr)` method.
1632#[stable(feature = "rust1", since = "1.0.0")]
1633#[diagnostic::on_const(
1634 message = "pointers cannot be reliably compared during const eval",
1635 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1636)]
1637impl<T: PointeeSized> PartialOrd for *const T {
1638 #[inline(always)]
1639 #[allow(ambiguous_wide_pointer_comparisons)]
1640 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
1641 Some(self.cmp(other))
1642 }
1643
1644 #[inline(always)]
1645 #[allow(ambiguous_wide_pointer_comparisons)]
1646 fn lt(&self, other: &*const T) -> bool {
1647 *self < *other
1648 }
1649
1650 #[inline(always)]
1651 #[allow(ambiguous_wide_pointer_comparisons)]
1652 fn le(&self, other: &*const T) -> bool {
1653 *self <= *other
1654 }
1655
1656 #[inline(always)]
1657 #[allow(ambiguous_wide_pointer_comparisons)]
1658 fn gt(&self, other: &*const T) -> bool {
1659 *self > *other
1660 }
1661
1662 #[inline(always)]
1663 #[allow(ambiguous_wide_pointer_comparisons)]
1664 fn ge(&self, other: &*const T) -> bool {
1665 *self >= *other
1666 }
1667}
1668
1669#[stable(feature = "raw_ptr_default", since = "1.88.0")]
1670impl<T: ?Sized + Thin> Default for *const T {
1671 /// Returns the default value of [`null()`][crate::ptr::null].
1672 fn default() -> Self {
1673 crate::ptr::null()
1674 }
1675}