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