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