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