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