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