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]
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 #[inline(always)]
1034 pub const fn wrapping_add(self, count: usize) -> Self
1035 where
1036 T: Sized,
1037 {
1038 self.wrapping_offset(count as isize)
1039 }
1040
1041 /// Adds an unsigned offset in bytes to a pointer using wrapping arithmetic.
1042 ///
1043 /// `count` is in units of bytes.
1044 ///
1045 /// This is purely a convenience for casting to a `u8` pointer and
1046 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1047 ///
1048 /// For non-`Sized` pointees this operation changes only the data pointer,
1049 /// leaving the metadata untouched.
1050 #[must_use]
1051 #[inline(always)]
1052 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1053 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1054 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1055 self.cast::<u8>().wrapping_add(count).with_metadata_of(self)
1056 }
1057
1058 /// Subtracts an unsigned offset from a pointer using wrapping arithmetic.
1059 ///
1060 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1061 /// offset of `3 * size_of::<T>()` bytes.
1062 ///
1063 /// # Safety
1064 ///
1065 /// This operation itself is always safe, but using the resulting pointer is not.
1066 ///
1067 /// The resulting pointer "remembers" the [allocation] that `self` points to; it must not
1068 /// be used to read or write other allocations.
1069 ///
1070 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1071 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1072 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1073 /// `x` and `y` point into the same allocation.
1074 ///
1075 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1076 /// same allocation: [`sub`] is immediate Undefined Behavior when crossing object
1077 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1078 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1079 /// can be optimized better and is thus preferable in performance-sensitive code.
1080 ///
1081 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1082 /// intermediate values used during the computation of the final result. For example,
1083 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1084 /// allocation and then re-entering it later is permitted.
1085 ///
1086 /// [`sub`]: #method.sub
1087 /// [allocation]: crate::ptr#allocation
1088 ///
1089 /// # Examples
1090 ///
1091 /// ```
1092 /// # use std::fmt::Write;
1093 /// // Iterate using a raw pointer in increments of two elements (backwards)
1094 /// let data = [1u8, 2, 3, 4, 5];
1095 /// let mut ptr: *const u8 = data.as_ptr();
1096 /// let start_rounded_down = ptr.wrapping_sub(2);
1097 /// ptr = ptr.wrapping_add(4);
1098 /// let step = 2;
1099 /// let mut out = String::new();
1100 /// while ptr != start_rounded_down {
1101 /// unsafe {
1102 /// write!(&mut out, "{}, ", *ptr)?;
1103 /// }
1104 /// ptr = ptr.wrapping_sub(step);
1105 /// }
1106 /// assert_eq!(out, "5, 3, 1, ");
1107 /// # std::fmt::Result::Ok(())
1108 /// ```
1109 #[stable(feature = "pointer_methods", since = "1.26.0")]
1110 #[must_use = "returns a new pointer rather than modifying its argument"]
1111 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1112 #[inline(always)]
1113 pub const fn wrapping_sub(self, count: usize) -> Self
1114 where
1115 T: Sized,
1116 {
1117 self.wrapping_offset((count as isize).wrapping_neg())
1118 }
1119
1120 /// Subtracts an unsigned offset in bytes from a pointer using wrapping arithmetic.
1121 ///
1122 /// `count` is in units of bytes.
1123 ///
1124 /// This is purely a convenience for casting to a `u8` pointer and
1125 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1126 ///
1127 /// For non-`Sized` pointees this operation changes only the data pointer,
1128 /// leaving the metadata untouched.
1129 #[must_use]
1130 #[inline(always)]
1131 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1132 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1133 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1134 self.cast::<u8>().wrapping_sub(count).with_metadata_of(self)
1135 }
1136
1137 /// Reads the value from `self` without moving it. This leaves the
1138 /// memory in `self` unchanged.
1139 ///
1140 /// See [`ptr::read`] for safety concerns and examples.
1141 ///
1142 /// [`ptr::read`]: crate::ptr::read()
1143 #[stable(feature = "pointer_methods", since = "1.26.0")]
1144 #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1145 #[inline]
1146 #[track_caller]
1147 pub const unsafe fn read(self) -> T
1148 where
1149 T: Sized,
1150 {
1151 // SAFETY: the caller must uphold the safety contract for `read`.
1152 unsafe { read(self) }
1153 }
1154
1155 /// Performs a volatile read of the value from `self` without moving it. This
1156 /// leaves the memory in `self` unchanged.
1157 ///
1158 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1159 /// to not be elided or reordered by the compiler across other volatile
1160 /// operations.
1161 ///
1162 /// See [`ptr::read_volatile`] for safety concerns and examples.
1163 ///
1164 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1165 #[stable(feature = "pointer_methods", since = "1.26.0")]
1166 #[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
1167 #[inline]
1168 #[track_caller]
1169 pub const unsafe fn read_volatile(self) -> T
1170 where
1171 T: Sized,
1172 {
1173 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1174 unsafe { read_volatile(self) }
1175 }
1176
1177 /// Reads the value from `self` without moving it. This leaves the
1178 /// memory in `self` unchanged.
1179 ///
1180 /// Unlike `read`, the pointer may be unaligned.
1181 ///
1182 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1183 ///
1184 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1185 #[stable(feature = "pointer_methods", since = "1.26.0")]
1186 #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1187 #[inline]
1188 #[track_caller]
1189 pub const unsafe fn read_unaligned(self) -> T
1190 where
1191 T: Sized,
1192 {
1193 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1194 unsafe { read_unaligned(self) }
1195 }
1196
1197 /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1198 /// and destination may overlap.
1199 ///
1200 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1201 ///
1202 /// See [`ptr::copy`] for safety concerns and examples.
1203 ///
1204 /// [`ptr::copy`]: crate::ptr::copy()
1205 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1206 #[stable(feature = "pointer_methods", since = "1.26.0")]
1207 #[inline]
1208 #[track_caller]
1209 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1210 where
1211 T: Sized,
1212 {
1213 // SAFETY: the caller must uphold the safety contract for `copy`.
1214 unsafe { copy(self, dest, count) }
1215 }
1216
1217 /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1218 /// and destination may *not* overlap.
1219 ///
1220 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1221 ///
1222 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1223 ///
1224 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1225 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1226 #[stable(feature = "pointer_methods", since = "1.26.0")]
1227 #[inline]
1228 #[track_caller]
1229 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1230 where
1231 T: Sized,
1232 {
1233 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1234 unsafe { copy_nonoverlapping(self, dest, count) }
1235 }
1236
1237 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1238 /// `align`.
1239 ///
1240 /// If it is not possible to align the pointer, the implementation returns
1241 /// `usize::MAX`.
1242 ///
1243 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1244 /// used with the `wrapping_add` method.
1245 ///
1246 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1247 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1248 /// the returned offset is correct in all terms other than alignment.
1249 ///
1250 /// # Panics
1251 ///
1252 /// The function panics if `align` is not a power-of-two.
1253 ///
1254 /// # Examples
1255 ///
1256 /// Accessing adjacent `u8` as `u16`
1257 ///
1258 /// ```
1259 /// # unsafe {
1260 /// let x = [5_u8, 6, 7, 8, 9];
1261 /// let ptr = x.as_ptr();
1262 /// let offset = ptr.align_offset(align_of::<u16>());
1263 ///
1264 /// if offset < x.len() - 1 {
1265 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1266 /// assert!(*u16_ptr == u16::from_ne_bytes([5, 6]) || *u16_ptr == u16::from_ne_bytes([6, 7]));
1267 /// } else {
1268 /// // while the pointer can be aligned via `offset`, it would point
1269 /// // outside the allocation
1270 /// }
1271 /// # }
1272 /// ```
1273 #[must_use]
1274 #[inline]
1275 #[stable(feature = "align_offset", since = "1.36.0")]
1276 pub fn align_offset(self, align: usize) -> usize
1277 where
1278 T: Sized,
1279 {
1280 if !align.is_power_of_two() {
1281 panic!("align_offset: align is not a power-of-two");
1282 }
1283
1284 // SAFETY: `align` has been checked to be a power of 2 above
1285 let ret = unsafe { align_offset(self, align) };
1286
1287 // Inform Miri that we want to consider the resulting pointer to be suitably aligned.
1288 #[cfg(miri)]
1289 if ret != usize::MAX {
1290 intrinsics::miri_promise_symbolic_alignment(self.wrapping_add(ret).cast(), align);
1291 }
1292
1293 ret
1294 }
1295
1296 /// Returns whether the pointer is properly aligned for `T`.
1297 ///
1298 /// # Examples
1299 ///
1300 /// ```
1301 /// // On some platforms, the alignment of i32 is less than 4.
1302 /// #[repr(align(4))]
1303 /// struct AlignedI32(i32);
1304 ///
1305 /// let data = AlignedI32(42);
1306 /// let ptr = &data as *const AlignedI32;
1307 ///
1308 /// assert!(ptr.is_aligned());
1309 /// assert!(!ptr.wrapping_byte_add(1).is_aligned());
1310 /// ```
1311 #[must_use]
1312 #[inline]
1313 #[stable(feature = "pointer_is_aligned", since = "1.79.0")]
1314 pub fn is_aligned(self) -> bool
1315 where
1316 T: Sized,
1317 {
1318 self.is_aligned_to(align_of::<T>())
1319 }
1320
1321 /// Returns whether the pointer is aligned to `align`.
1322 ///
1323 /// For non-`Sized` pointees this operation considers only the data pointer,
1324 /// ignoring the metadata.
1325 ///
1326 /// # Panics
1327 ///
1328 /// The function panics if `align` is not a power-of-two (this includes 0).
1329 ///
1330 /// # Examples
1331 ///
1332 /// ```
1333 /// #![feature(pointer_is_aligned_to)]
1334 ///
1335 /// // On some platforms, the alignment of i32 is less than 4.
1336 /// #[repr(align(4))]
1337 /// struct AlignedI32(i32);
1338 ///
1339 /// let data = AlignedI32(42);
1340 /// let ptr = &data as *const AlignedI32;
1341 ///
1342 /// assert!(ptr.is_aligned_to(1));
1343 /// assert!(ptr.is_aligned_to(2));
1344 /// assert!(ptr.is_aligned_to(4));
1345 ///
1346 /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1347 /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1348 ///
1349 /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1350 /// ```
1351 #[must_use]
1352 #[inline]
1353 #[unstable(feature = "pointer_is_aligned_to", issue = "96284")]
1354 pub fn is_aligned_to(self, align: usize) -> bool {
1355 if !align.is_power_of_two() {
1356 panic!("is_aligned_to: align is not a power-of-two");
1357 }
1358
1359 self.addr() & (align - 1) == 0
1360 }
1361}
1362
1363impl<T> *const T {
1364 /// Casts from a type to its maybe-uninitialized version.
1365 #[must_use]
1366 #[inline(always)]
1367 #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1368 pub const fn cast_uninit(self) -> *const MaybeUninit<T> {
1369 self as _
1370 }
1371
1372 /// Forms a raw slice from a pointer and a length.
1373 ///
1374 /// The `len` argument is the number of **elements**, not the number of bytes.
1375 ///
1376 /// This function is safe, but actually using the return value is unsafe.
1377 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
1378 ///
1379 /// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
1380 ///
1381 /// # Examples
1382 ///
1383 /// ```rust
1384 /// #![feature(ptr_cast_slice)]
1385 ///
1386 /// // create a slice pointer when starting out with a pointer to the first element
1387 /// let x = [5, 6, 7];
1388 /// let raw_slice = x.as_ptr().cast_slice(3);
1389 /// assert_eq!(unsafe { &*raw_slice }[2], 7);
1390 /// ```
1391 ///
1392 /// You must ensure that the pointer is valid and not null before dereferencing
1393 /// the raw slice. A slice reference must never have a null pointer, even if it's empty.
1394 ///
1395 /// ```rust,should_panic
1396 /// #![feature(ptr_cast_slice)]
1397 /// use std::ptr;
1398 /// let danger: *const [u8] = ptr::null::<u8>().cast_slice(0);
1399 /// unsafe {
1400 /// danger.as_ref().expect("references must not be null");
1401 /// }
1402 /// ```
1403 #[inline]
1404 #[unstable(feature = "ptr_cast_slice", issue = "149103")]
1405 pub const fn cast_slice(self, len: usize) -> *const [T] {
1406 slice_from_raw_parts(self, len)
1407 }
1408}
1409impl<T> *const MaybeUninit<T> {
1410 /// Casts from a maybe-uninitialized type to its initialized version.
1411 ///
1412 /// This is always safe, since UB can only occur if the pointer is read
1413 /// before being initialized.
1414 #[must_use]
1415 #[inline(always)]
1416 #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1417 pub const fn cast_init(self) -> *const T {
1418 self as _
1419 }
1420}
1421
1422impl<T> *const [T] {
1423 /// Returns the length of a raw slice.
1424 ///
1425 /// The returned value is the number of **elements**, not the number of bytes.
1426 ///
1427 /// This function is safe, even when the raw slice cannot be cast to a slice
1428 /// reference because the pointer is null or unaligned.
1429 ///
1430 /// # Examples
1431 ///
1432 /// ```rust
1433 /// use std::ptr;
1434 ///
1435 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1436 /// assert_eq!(slice.len(), 3);
1437 /// ```
1438 #[inline]
1439 #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1440 #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1441 pub const fn len(self) -> usize {
1442 metadata(self)
1443 }
1444
1445 /// Returns `true` if the raw slice has a length of 0.
1446 ///
1447 /// # Examples
1448 ///
1449 /// ```
1450 /// use std::ptr;
1451 ///
1452 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1453 /// assert!(!slice.is_empty());
1454 /// ```
1455 #[inline(always)]
1456 #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1457 #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1458 pub const fn is_empty(self) -> bool {
1459 self.len() == 0
1460 }
1461
1462 /// Returns a raw pointer to the slice's buffer.
1463 ///
1464 /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1465 ///
1466 /// # Examples
1467 ///
1468 /// ```rust
1469 /// #![feature(slice_ptr_get)]
1470 /// use std::ptr;
1471 ///
1472 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1473 /// assert_eq!(slice.as_ptr(), ptr::null());
1474 /// ```
1475 #[inline]
1476 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1477 pub const fn as_ptr(self) -> *const T {
1478 self as *const T
1479 }
1480
1481 /// Gets a raw pointer to the underlying array.
1482 ///
1483 /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
1484 #[stable(feature = "core_slice_as_array", since = "1.93.0")]
1485 #[rustc_const_stable(feature = "core_slice_as_array", since = "1.93.0")]
1486 #[inline]
1487 #[must_use]
1488 pub const fn as_array<const N: usize>(self) -> Option<*const [T; N]> {
1489 if self.len() == N {
1490 let me = self.as_ptr() as *const [T; N];
1491 Some(me)
1492 } else {
1493 None
1494 }
1495 }
1496
1497 /// Returns a raw pointer to an element or subslice, without doing bounds
1498 /// checking.
1499 ///
1500 /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
1501 /// is *[undefined behavior]* even if the resulting pointer is not used.
1502 ///
1503 /// [out-of-bounds index]: #method.add
1504 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1505 ///
1506 /// # Examples
1507 ///
1508 /// ```
1509 /// #![feature(slice_ptr_get)]
1510 ///
1511 /// let x = &[1, 2, 4] as *const [i32];
1512 ///
1513 /// unsafe {
1514 /// assert_eq!(x.get_unchecked(1), x.as_ptr().add(1));
1515 /// }
1516 /// ```
1517 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1518 #[rustc_const_unstable(feature = "const_index", issue = "143775")]
1519 #[inline]
1520 pub const unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output
1521 where
1522 I: [const] SliceIndex<[T]>,
1523 {
1524 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1525 unsafe { index.get_unchecked(self) }
1526 }
1527
1528 #[doc = include_str!("docs/as_uninit_slice.md")]
1529 #[inline]
1530 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1531 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1532 if self.is_null() {
1533 None
1534 } else {
1535 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1536 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1537 }
1538 }
1539}
1540
1541impl<T> *const T {
1542 /// Casts from a pointer-to-`T` to a pointer-to-`[T; N]`.
1543 #[inline]
1544 #[unstable(feature = "ptr_cast_array", issue = "144514")]
1545 pub const fn cast_array<const N: usize>(self) -> *const [T; N] {
1546 self.cast()
1547 }
1548}
1549
1550impl<T, const N: usize> *const [T; N] {
1551 /// Returns a raw pointer to the array's buffer.
1552 ///
1553 /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1554 ///
1555 /// # Examples
1556 ///
1557 /// ```rust
1558 /// #![feature(array_ptr_get)]
1559 /// use std::ptr;
1560 ///
1561 /// let arr: *const [i8; 3] = ptr::null();
1562 /// assert_eq!(arr.as_ptr(), ptr::null());
1563 /// ```
1564 #[inline]
1565 #[unstable(feature = "array_ptr_get", issue = "119834")]
1566 pub const fn as_ptr(self) -> *const T {
1567 self as *const T
1568 }
1569
1570 /// Returns a raw pointer to a slice containing the entire array.
1571 ///
1572 /// # Examples
1573 ///
1574 /// ```
1575 /// #![feature(array_ptr_get)]
1576 ///
1577 /// let arr: *const [i32; 3] = &[1, 2, 4] as *const [i32; 3];
1578 /// let slice: *const [i32] = arr.as_slice();
1579 /// assert_eq!(slice.len(), 3);
1580 /// ```
1581 #[inline]
1582 #[unstable(feature = "array_ptr_get", issue = "119834")]
1583 pub const fn as_slice(self) -> *const [T] {
1584 self
1585 }
1586}
1587
1588/// Pointer equality is by address, as produced by the [`<*const T>::addr`](pointer::addr) method.
1589#[stable(feature = "rust1", since = "1.0.0")]
1590#[diagnostic::on_const(
1591 message = "pointers cannot be reliably compared during const eval",
1592 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1593)]
1594impl<T: PointeeSized> PartialEq for *const T {
1595 #[inline]
1596 #[allow(ambiguous_wide_pointer_comparisons)]
1597 fn eq(&self, other: &*const T) -> bool {
1598 *self == *other
1599 }
1600}
1601
1602/// Pointer equality is an equivalence relation.
1603#[stable(feature = "rust1", since = "1.0.0")]
1604#[diagnostic::on_const(
1605 message = "pointers cannot be reliably compared during const eval",
1606 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1607)]
1608impl<T: PointeeSized> Eq for *const T {}
1609
1610/// Pointer comparison is by address, as produced by the `[`<*const T>::addr`](pointer::addr)` method.
1611#[stable(feature = "rust1", since = "1.0.0")]
1612#[diagnostic::on_const(
1613 message = "pointers cannot be reliably compared during const eval",
1614 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1615)]
1616impl<T: PointeeSized> Ord for *const T {
1617 #[inline]
1618 #[allow(ambiguous_wide_pointer_comparisons)]
1619 fn cmp(&self, other: &*const T) -> Ordering {
1620 if self < other {
1621 Less
1622 } else if self == other {
1623 Equal
1624 } else {
1625 Greater
1626 }
1627 }
1628}
1629
1630/// Pointer comparison is by address, as produced by the `[`<*const T>::addr`](pointer::addr)` method.
1631#[stable(feature = "rust1", since = "1.0.0")]
1632#[diagnostic::on_const(
1633 message = "pointers cannot be reliably compared during const eval",
1634 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
1635)]
1636impl<T: PointeeSized> PartialOrd for *const T {
1637 #[inline]
1638 #[allow(ambiguous_wide_pointer_comparisons)]
1639 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
1640 Some(self.cmp(other))
1641 }
1642
1643 #[inline]
1644 #[allow(ambiguous_wide_pointer_comparisons)]
1645 fn lt(&self, other: &*const T) -> bool {
1646 *self < *other
1647 }
1648
1649 #[inline]
1650 #[allow(ambiguous_wide_pointer_comparisons)]
1651 fn le(&self, other: &*const T) -> bool {
1652 *self <= *other
1653 }
1654
1655 #[inline]
1656 #[allow(ambiguous_wide_pointer_comparisons)]
1657 fn gt(&self, other: &*const T) -> bool {
1658 *self > *other
1659 }
1660
1661 #[inline]
1662 #[allow(ambiguous_wide_pointer_comparisons)]
1663 fn ge(&self, other: &*const T) -> bool {
1664 *self >= *other
1665 }
1666}
1667
1668#[stable(feature = "raw_ptr_default", since = "1.88.0")]
1669impl<T: ?Sized + Thin> Default for *const T {
1670 /// Returns the default value of [`null()`][crate::ptr::null].
1671 fn default() -> Self {
1672 crate::ptr::null()
1673 }
1674}