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