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