]> git.proxmox.com Git - rustc.git/blob - library/core/src/ptr/const_ptr.rs
New upstream version 1.64.0+dfsg1
[rustc.git] / library / core / src / ptr / const_ptr.rs
1 use super::*;
2 use crate::cmp::Ordering::{self, Equal, Greater, Less};
3 use crate::intrinsics;
4 use crate::mem;
5 use crate::slice::{self, SliceIndex};
6
7 impl<T: ?Sized> *const T {
8 /// Returns `true` if the pointer is null.
9 ///
10 /// Note that unsized types have many possible null pointers, as only the
11 /// raw data pointer is considered, not their length, vtable, etc.
12 /// Therefore, two pointers that are null may still not compare equal to
13 /// each other.
14 ///
15 /// ## Behavior during const evaluation
16 ///
17 /// When this function is used during const evaluation, it may return `false` for pointers
18 /// that turn out to be null at runtime. Specifically, when a pointer to some memory
19 /// is offset beyond its bounds in such a way that the resulting pointer is null,
20 /// the function will still return `false`. There is no way for CTFE to know
21 /// the absolute position of that memory, so we cannot tell if the pointer is
22 /// null or not.
23 ///
24 /// # Examples
25 ///
26 /// Basic usage:
27 ///
28 /// ```
29 /// let s: &str = "Follow the rabbit";
30 /// let ptr: *const u8 = s.as_ptr();
31 /// assert!(!ptr.is_null());
32 /// ```
33 #[stable(feature = "rust1", since = "1.0.0")]
34 #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")]
35 #[inline]
36 pub const fn is_null(self) -> bool {
37 // Compare via a cast to a thin pointer, so fat pointers are only
38 // considering their "data" part for null-ness.
39 (self as *const u8).guaranteed_eq(null())
40 }
41
42 /// Casts to a pointer of another type.
43 #[stable(feature = "ptr_cast", since = "1.38.0")]
44 #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
45 #[inline]
46 pub const fn cast<U>(self) -> *const U {
47 self as _
48 }
49
50 /// Use the pointer value in a new pointer of another type.
51 ///
52 /// In case `val` is a (fat) pointer to an unsized type, this operation
53 /// will ignore the pointer part, whereas for (thin) pointers to sized
54 /// types, this has the same effect as a simple cast.
55 ///
56 /// The resulting pointer will have provenance of `self`, i.e., for a fat
57 /// pointer, this operation is semantically the same as creating a new
58 /// fat pointer with the data pointer value of `self` but the metadata of
59 /// `val`.
60 ///
61 /// # Examples
62 ///
63 /// This function is primarily useful for allowing byte-wise pointer
64 /// arithmetic on potentially fat pointers:
65 ///
66 /// ```
67 /// #![feature(set_ptr_value)]
68 /// # use core::fmt::Debug;
69 /// let arr: [i32; 3] = [1, 2, 3];
70 /// let mut ptr = arr.as_ptr() as *const dyn Debug;
71 /// let thin = ptr as *const u8;
72 /// unsafe {
73 /// ptr = thin.add(8).with_metadata_of(ptr);
74 /// # assert_eq!(*(ptr as *const i32), 3);
75 /// println!("{:?}", &*ptr); // will print "3"
76 /// }
77 /// ```
78 #[unstable(feature = "set_ptr_value", issue = "75091")]
79 #[must_use = "returns a new pointer rather than modifying its argument"]
80 #[inline]
81 pub fn with_metadata_of<U>(self, mut val: *const U) -> *const U
82 where
83 U: ?Sized,
84 {
85 let target = &mut val as *mut *const U as *mut *const u8;
86 // SAFETY: In case of a thin pointer, this operations is identical
87 // to a simple assignment. In case of a fat pointer, with the current
88 // fat pointer layout implementation, the first field of such a
89 // pointer is always the data pointer, which is likewise assigned.
90 unsafe { *target = self as *const u8 };
91 val
92 }
93
94 /// Changes constness without changing the type.
95 ///
96 /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
97 /// refactored.
98 #[unstable(feature = "ptr_const_cast", issue = "92675")]
99 #[rustc_const_unstable(feature = "ptr_const_cast", issue = "92675")]
100 pub const fn cast_mut(self) -> *mut T {
101 self as _
102 }
103
104 /// Casts a pointer to its raw bits.
105 ///
106 /// This is equivalent to `as usize`, but is more specific to enhance readability.
107 /// The inverse method is [`from_bits`](#method.from_bits).
108 ///
109 /// In particular, `*p as usize` and `p as usize` will both compile for
110 /// pointers to numeric types but do very different things, so using this
111 /// helps emphasize that reading the bits was intentional.
112 ///
113 /// # Examples
114 ///
115 /// ```
116 /// #![feature(ptr_to_from_bits)]
117 /// let array = [13, 42];
118 /// let p0: *const i32 = &array[0];
119 /// assert_eq!(<*const _>::from_bits(p0.to_bits()), p0);
120 /// let p1: *const i32 = &array[1];
121 /// assert_eq!(p1.to_bits() - p0.to_bits(), 4);
122 /// ```
123 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
124 pub fn to_bits(self) -> usize
125 where
126 T: Sized,
127 {
128 self as usize
129 }
130
131 /// Creates a pointer from its raw bits.
132 ///
133 /// This is equivalent to `as *const T`, but is more specific to enhance readability.
134 /// The inverse method is [`to_bits`](#method.to_bits).
135 ///
136 /// # Examples
137 ///
138 /// ```
139 /// #![feature(ptr_to_from_bits)]
140 /// use std::ptr::NonNull;
141 /// let dangling: *const u8 = NonNull::dangling().as_ptr();
142 /// assert_eq!(<*const u8>::from_bits(1), dangling);
143 /// ```
144 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
145 pub fn from_bits(bits: usize) -> Self
146 where
147 T: Sized,
148 {
149 bits as Self
150 }
151
152 /// Gets the "address" portion of the pointer.
153 ///
154 /// This is similar to `self as usize`, which semantically discards *provenance* and
155 /// *address-space* information. However, unlike `self as usize`, casting the returned address
156 /// back to a pointer yields [`invalid`][], which is undefined behavior to dereference. To
157 /// properly restore the lost information and obtain a dereferencable pointer, use
158 /// [`with_addr`][pointer::with_addr] or [`map_addr`][pointer::map_addr].
159 ///
160 /// If using those APIs is not possible because there is no way to preserve a pointer with the
161 /// required provenance, use [`expose_addr`][pointer::expose_addr] and
162 /// [`from_exposed_addr`][from_exposed_addr] instead. However, note that this makes
163 /// your code less portable and less amenable to tools that check for compliance with the Rust
164 /// memory model.
165 ///
166 /// On most platforms this will produce a value with the same bytes as the original
167 /// pointer, because all the bytes are dedicated to describing the address.
168 /// Platforms which need to store additional information in the pointer may
169 /// perform a change of representation to produce a value containing only the address
170 /// portion of the pointer. What that means is up to the platform to define.
171 ///
172 /// This API and its claimed semantics are part of the Strict Provenance experiment, and as such
173 /// might change in the future (including possibly weakening this so it becomes wholly
174 /// equivalent to `self as usize`). See the [module documentation][crate::ptr] for details.
175 #[must_use]
176 #[inline]
177 #[unstable(feature = "strict_provenance", issue = "95228")]
178 pub fn addr(self) -> usize
179 where
180 T: Sized,
181 {
182 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
183 // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
184 // provenance).
185 unsafe { mem::transmute(self) }
186 }
187
188 /// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future
189 /// use in [`from_exposed_addr`][].
190 ///
191 /// This is equivalent to `self as usize`, which semantically discards *provenance* and
192 /// *address-space* information. Furthermore, this (like the `as` cast) has the implicit
193 /// side-effect of marking the provenance as 'exposed', so on platforms that support it you can
194 /// later call [`from_exposed_addr`][] to reconstitute the original pointer including its
195 /// provenance. (Reconstructing address space information, if required, is your responsibility.)
196 ///
197 /// Using this method means that code is *not* following Strict Provenance rules. Supporting
198 /// [`from_exposed_addr`][] complicates specification and reasoning and may not be supported by
199 /// tools that help you to stay conformant with the Rust memory model, so it is recommended to
200 /// use [`addr`][pointer::addr] wherever possible.
201 ///
202 /// On most platforms this will produce a value with the same bytes as the original pointer,
203 /// because all the bytes are dedicated to describing the address. Platforms which need to store
204 /// additional information in the pointer may not support this operation, since the 'expose'
205 /// side-effect which is required for [`from_exposed_addr`][] to work is typically not
206 /// available.
207 ///
208 /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
209 /// [module documentation][crate::ptr] for details.
210 ///
211 /// [`from_exposed_addr`]: from_exposed_addr
212 #[must_use]
213 #[inline]
214 #[unstable(feature = "strict_provenance", issue = "95228")]
215 pub fn expose_addr(self) -> usize
216 where
217 T: Sized,
218 {
219 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
220 self as usize
221 }
222
223 /// Creates a new pointer with the given address.
224 ///
225 /// This performs the same operation as an `addr as ptr` cast, but copies
226 /// the *address-space* and *provenance* of `self` to the new pointer.
227 /// This allows us to dynamically preserve and propagate this important
228 /// information in a way that is otherwise impossible with a unary cast.
229 ///
230 /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
231 /// `self` to the given address, and therefore has all the same capabilities and restrictions.
232 ///
233 /// This API and its claimed semantics are part of the Strict Provenance experiment,
234 /// see the [module documentation][crate::ptr] for details.
235 #[must_use]
236 #[inline]
237 #[unstable(feature = "strict_provenance", issue = "95228")]
238 pub fn with_addr(self, addr: usize) -> Self
239 where
240 T: Sized,
241 {
242 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
243 //
244 // In the mean-time, this operation is defined to be "as if" it was
245 // a wrapping_offset, so we can emulate it as such. This should properly
246 // restore pointer provenance even under today's compiler.
247 let self_addr = self.addr() as isize;
248 let dest_addr = addr as isize;
249 let offset = dest_addr.wrapping_sub(self_addr);
250
251 // This is the canonical desugarring of this operation
252 self.cast::<u8>().wrapping_offset(offset).cast::<T>()
253 }
254
255 /// Creates a new pointer by mapping `self`'s address to a new one.
256 ///
257 /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
258 ///
259 /// This API and its claimed semantics are part of the Strict Provenance experiment,
260 /// see the [module documentation][crate::ptr] for details.
261 #[must_use]
262 #[inline]
263 #[unstable(feature = "strict_provenance", issue = "95228")]
264 pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self
265 where
266 T: Sized,
267 {
268 self.with_addr(f(self.addr()))
269 }
270
271 /// Decompose a (possibly wide) pointer into its address and metadata components.
272 ///
273 /// The pointer can be later reconstructed with [`from_raw_parts`].
274 #[unstable(feature = "ptr_metadata", issue = "81513")]
275 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
276 #[inline]
277 pub const fn to_raw_parts(self) -> (*const (), <T as super::Pointee>::Metadata) {
278 (self.cast(), metadata(self))
279 }
280
281 /// Returns `None` if the pointer is null, or else returns a shared reference to
282 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
283 /// must be used instead.
284 ///
285 /// [`as_uninit_ref`]: #method.as_uninit_ref
286 ///
287 /// # Safety
288 ///
289 /// When calling this method, you have to ensure that *either* the pointer is null *or*
290 /// all of the following is true:
291 ///
292 /// * The pointer must be properly aligned.
293 ///
294 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
295 ///
296 /// * The pointer must point to an initialized instance of `T`.
297 ///
298 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
299 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
300 /// In particular, while this reference exists, the memory the pointer points to must
301 /// not get mutated (except inside `UnsafeCell`).
302 ///
303 /// This applies even if the result of this method is unused!
304 /// (The part about being initialized is not yet fully decided, but until
305 /// it is, the only safe approach is to ensure that they are indeed initialized.)
306 ///
307 /// [the module documentation]: crate::ptr#safety
308 ///
309 /// # Examples
310 ///
311 /// Basic usage:
312 ///
313 /// ```
314 /// let ptr: *const u8 = &10u8 as *const u8;
315 ///
316 /// unsafe {
317 /// if let Some(val_back) = ptr.as_ref() {
318 /// println!("We got back the value: {val_back}!");
319 /// }
320 /// }
321 /// ```
322 ///
323 /// # Null-unchecked version
324 ///
325 /// If you are sure the pointer can never be null and are looking for some kind of
326 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
327 /// dereference the pointer directly.
328 ///
329 /// ```
330 /// let ptr: *const u8 = &10u8 as *const u8;
331 ///
332 /// unsafe {
333 /// let val_back = &*ptr;
334 /// println!("We got back the value: {val_back}!");
335 /// }
336 /// ```
337 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
338 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
339 #[inline]
340 pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
341 // SAFETY: the caller must guarantee that `self` is valid
342 // for a reference if it isn't null.
343 if self.is_null() { None } else { unsafe { Some(&*self) } }
344 }
345
346 /// Returns `None` if the pointer is null, or else returns a shared reference to
347 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
348 /// that the value has to be initialized.
349 ///
350 /// [`as_ref`]: #method.as_ref
351 ///
352 /// # Safety
353 ///
354 /// When calling this method, you have to ensure that *either* the pointer is null *or*
355 /// all of the following is true:
356 ///
357 /// * The pointer must be properly aligned.
358 ///
359 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
360 ///
361 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
362 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
363 /// In particular, while this reference exists, the memory the pointer points to must
364 /// not get mutated (except inside `UnsafeCell`).
365 ///
366 /// This applies even if the result of this method is unused!
367 ///
368 /// [the module documentation]: crate::ptr#safety
369 ///
370 /// # Examples
371 ///
372 /// Basic usage:
373 ///
374 /// ```
375 /// #![feature(ptr_as_uninit)]
376 ///
377 /// let ptr: *const u8 = &10u8 as *const u8;
378 ///
379 /// unsafe {
380 /// if let Some(val_back) = ptr.as_uninit_ref() {
381 /// println!("We got back the value: {}!", val_back.assume_init());
382 /// }
383 /// }
384 /// ```
385 #[inline]
386 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
387 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
388 pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
389 where
390 T: Sized,
391 {
392 // SAFETY: the caller must guarantee that `self` meets all the
393 // requirements for a reference.
394 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
395 }
396
397 /// Calculates the offset from a pointer.
398 ///
399 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
400 /// offset of `3 * size_of::<T>()` bytes.
401 ///
402 /// # Safety
403 ///
404 /// If any of the following conditions are violated, the result is Undefined
405 /// Behavior:
406 ///
407 /// * Both the starting and resulting pointer must be either in bounds or one
408 /// byte past the end of the same [allocated object].
409 ///
410 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
411 ///
412 /// * The offset being in bounds cannot rely on "wrapping around" the address
413 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
414 ///
415 /// The compiler and standard library generally tries to ensure allocations
416 /// never reach a size where an offset is a concern. For instance, `Vec`
417 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
418 /// `vec.as_ptr().add(vec.len())` is always safe.
419 ///
420 /// Most platforms fundamentally can't even construct such an allocation.
421 /// For instance, no known 64-bit platform can ever serve a request
422 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
423 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
424 /// more than `isize::MAX` bytes with things like Physical Address
425 /// Extension. As such, memory acquired directly from allocators or memory
426 /// mapped files *may* be too large to handle with this function.
427 ///
428 /// Consider using [`wrapping_offset`] instead if these constraints are
429 /// difficult to satisfy. The only advantage of this method is that it
430 /// enables more aggressive compiler optimizations.
431 ///
432 /// [`wrapping_offset`]: #method.wrapping_offset
433 /// [allocated object]: crate::ptr#allocated-object
434 ///
435 /// # Examples
436 ///
437 /// Basic usage:
438 ///
439 /// ```
440 /// let s: &str = "123";
441 /// let ptr: *const u8 = s.as_ptr();
442 ///
443 /// unsafe {
444 /// println!("{}", *ptr.offset(1) as char);
445 /// println!("{}", *ptr.offset(2) as char);
446 /// }
447 /// ```
448 #[stable(feature = "rust1", since = "1.0.0")]
449 #[must_use = "returns a new pointer rather than modifying its argument"]
450 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
451 #[inline(always)]
452 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
453 pub const unsafe fn offset(self, count: isize) -> *const T
454 where
455 T: Sized,
456 {
457 // SAFETY: the caller must uphold the safety contract for `offset`.
458 unsafe { intrinsics::offset(self, count) }
459 }
460
461 /// Calculates the offset from a pointer in bytes.
462 ///
463 /// `count` is in units of **bytes**.
464 ///
465 /// This is purely a convenience for casting to a `u8` pointer and
466 /// using [offset][pointer::offset] on it. See that method for documentation
467 /// and safety requirements.
468 ///
469 /// For non-`Sized` pointees this operation changes only the data pointer,
470 /// leaving the metadata untouched.
471 #[must_use]
472 #[inline(always)]
473 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
474 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
475 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
476 pub const unsafe fn byte_offset(self, count: isize) -> Self {
477 // SAFETY: the caller must uphold the safety contract for `offset`.
478 let this = unsafe { self.cast::<u8>().offset(count).cast::<()>() };
479 from_raw_parts::<T>(this, metadata(self))
480 }
481
482 /// Calculates the offset from a pointer using wrapping arithmetic.
483 ///
484 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
485 /// offset of `3 * size_of::<T>()` bytes.
486 ///
487 /// # Safety
488 ///
489 /// This operation itself is always safe, but using the resulting pointer is not.
490 ///
491 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
492 /// be used to read or write other allocated objects.
493 ///
494 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
495 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
496 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
497 /// `x` and `y` point into the same allocated object.
498 ///
499 /// Compared to [`offset`], this method basically delays the requirement of staying within the
500 /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
501 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
502 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
503 /// can be optimized better and is thus preferable in performance-sensitive code.
504 ///
505 /// The delayed check only considers the value of the pointer that was dereferenced, not the
506 /// intermediate values used during the computation of the final result. For example,
507 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
508 /// words, leaving the allocated object and then re-entering it later is permitted.
509 ///
510 /// [`offset`]: #method.offset
511 /// [allocated object]: crate::ptr#allocated-object
512 ///
513 /// # Examples
514 ///
515 /// Basic usage:
516 ///
517 /// ```
518 /// // Iterate using a raw pointer in increments of two elements
519 /// let data = [1u8, 2, 3, 4, 5];
520 /// let mut ptr: *const u8 = data.as_ptr();
521 /// let step = 2;
522 /// let end_rounded_up = ptr.wrapping_offset(6);
523 ///
524 /// // This loop prints "1, 3, 5, "
525 /// while ptr != end_rounded_up {
526 /// unsafe {
527 /// print!("{}, ", *ptr);
528 /// }
529 /// ptr = ptr.wrapping_offset(step);
530 /// }
531 /// ```
532 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
533 #[must_use = "returns a new pointer rather than modifying its argument"]
534 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
535 #[inline(always)]
536 pub const fn wrapping_offset(self, count: isize) -> *const T
537 where
538 T: Sized,
539 {
540 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
541 unsafe { intrinsics::arith_offset(self, count) }
542 }
543
544 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
545 ///
546 /// `count` is in units of **bytes**.
547 ///
548 /// This is purely a convenience for casting to a `u8` pointer and
549 /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
550 /// for documentation.
551 ///
552 /// For non-`Sized` pointees this operation changes only the data pointer,
553 /// leaving the metadata untouched.
554 #[must_use]
555 #[inline(always)]
556 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
557 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
558 pub const fn wrapping_byte_offset(self, count: isize) -> Self {
559 from_raw_parts::<T>(self.cast::<u8>().wrapping_offset(count).cast::<()>(), metadata(self))
560 }
561
562 /// Calculates the distance between two pointers. The returned value is in
563 /// units of T: the distance in bytes divided by `mem::size_of::<T>()`.
564 ///
565 /// This function is the inverse of [`offset`].
566 ///
567 /// [`offset`]: #method.offset
568 ///
569 /// # Safety
570 ///
571 /// If any of the following conditions are violated, the result is Undefined
572 /// Behavior:
573 ///
574 /// * Both the starting and other pointer must be either in bounds or one
575 /// byte past the end of the same [allocated object].
576 ///
577 /// * Both pointers must be *derived from* a pointer to the same object.
578 /// (See below for an example.)
579 ///
580 /// * The distance between the pointers, in bytes, must be an exact multiple
581 /// of the size of `T`.
582 ///
583 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
584 ///
585 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
586 ///
587 /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
588 /// address space, so two pointers within some value of any Rust type `T` will always satisfy
589 /// the last two conditions. The standard library also generally ensures that allocations
590 /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
591 /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
592 /// always satisfies the last two conditions.
593 ///
594 /// Most platforms fundamentally can't even construct such a large allocation.
595 /// For instance, no known 64-bit platform can ever serve a request
596 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
597 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
598 /// more than `isize::MAX` bytes with things like Physical Address
599 /// Extension. As such, memory acquired directly from allocators or memory
600 /// mapped files *may* be too large to handle with this function.
601 /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
602 /// such large allocations either.)
603 ///
604 /// [`add`]: #method.add
605 /// [allocated object]: crate::ptr#allocated-object
606 ///
607 /// # Panics
608 ///
609 /// This function panics if `T` is a Zero-Sized Type ("ZST").
610 ///
611 /// # Examples
612 ///
613 /// Basic usage:
614 ///
615 /// ```
616 /// let a = [0; 5];
617 /// let ptr1: *const i32 = &a[1];
618 /// let ptr2: *const i32 = &a[3];
619 /// unsafe {
620 /// assert_eq!(ptr2.offset_from(ptr1), 2);
621 /// assert_eq!(ptr1.offset_from(ptr2), -2);
622 /// assert_eq!(ptr1.offset(2), ptr2);
623 /// assert_eq!(ptr2.offset(-2), ptr1);
624 /// }
625 /// ```
626 ///
627 /// *Incorrect* usage:
628 ///
629 /// ```rust,no_run
630 /// let ptr1 = Box::into_raw(Box::new(0u8)) as *const u8;
631 /// let ptr2 = Box::into_raw(Box::new(1u8)) as *const u8;
632 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
633 /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
634 /// let ptr2_other = (ptr1 as *const u8).wrapping_offset(diff);
635 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
636 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
637 /// // computing their offset is undefined behavior, even though
638 /// // they point to the same address!
639 /// unsafe {
640 /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
641 /// }
642 /// ```
643 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
644 #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "92980")]
645 #[inline]
646 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
647 pub const unsafe fn offset_from(self, origin: *const T) -> isize
648 where
649 T: Sized,
650 {
651 let pointee_size = mem::size_of::<T>();
652 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
653 // SAFETY: the caller must uphold the safety contract for `ptr_offset_from`.
654 unsafe { intrinsics::ptr_offset_from(self, origin) }
655 }
656
657 /// Calculates the distance between two pointers. The returned value is in
658 /// units of **bytes**.
659 ///
660 /// This is purely a convenience for casting to a `u8` pointer and
661 /// using [offset_from][pointer::offset_from] on it. See that method for
662 /// documentation and safety requirements.
663 ///
664 /// For non-`Sized` pointees this operation considers only the data pointers,
665 /// ignoring the metadata.
666 #[inline(always)]
667 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
668 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
669 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
670 pub const unsafe fn byte_offset_from(self, origin: *const T) -> isize {
671 // SAFETY: the caller must uphold the safety contract for `offset_from`.
672 unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
673 }
674
675 /// Calculates the distance between two pointers, *where it's known that
676 /// `self` is equal to or greater than `origin`*. The returned value is in
677 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
678 ///
679 /// This computes the same value that [`offset_from`](#method.offset_from)
680 /// would compute, but with the added precondition that that the offset is
681 /// guaranteed to be non-negative. This method is equivalent to
682 /// `usize::from(self.offset_from(origin)).unwrap_unchecked()`,
683 /// but it provides slightly more information to the optimizer, which can
684 /// sometimes allow it to optimize slightly better with some backends.
685 ///
686 /// This method can be though of as recovering the `count` that was passed
687 /// to [`add`](#method.add) (or, with the parameters in the other order,
688 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
689 /// that their safety preconditions are met:
690 /// ```rust
691 /// # #![feature(ptr_sub_ptr)]
692 /// # unsafe fn blah(ptr: *const i32, origin: *const i32, count: usize) -> bool {
693 /// ptr.sub_ptr(origin) == count
694 /// # &&
695 /// origin.add(count) == ptr
696 /// # &&
697 /// ptr.sub(count) == origin
698 /// # }
699 /// ```
700 ///
701 /// # Safety
702 ///
703 /// - The distance between the pointers must be non-negative (`self >= origin`)
704 ///
705 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
706 /// apply to this method as well; see it for the full details.
707 ///
708 /// Importantly, despite the return type of this method being able to represent
709 /// a larger offset, it's still *not permitted* to pass pointers which differ
710 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
711 /// always be less than or equal to `isize::MAX as usize`.
712 ///
713 /// # Panics
714 ///
715 /// This function panics if `T` is a Zero-Sized Type ("ZST").
716 ///
717 /// # Examples
718 ///
719 /// ```
720 /// #![feature(ptr_sub_ptr)]
721 ///
722 /// let a = [0; 5];
723 /// let ptr1: *const i32 = &a[1];
724 /// let ptr2: *const i32 = &a[3];
725 /// unsafe {
726 /// assert_eq!(ptr2.sub_ptr(ptr1), 2);
727 /// assert_eq!(ptr1.add(2), ptr2);
728 /// assert_eq!(ptr2.sub(2), ptr1);
729 /// assert_eq!(ptr2.sub_ptr(ptr2), 0);
730 /// }
731 ///
732 /// // This would be incorrect, as the pointers are not correctly ordered:
733 /// // ptr1.sub_ptr(ptr2)
734 /// ```
735 #[unstable(feature = "ptr_sub_ptr", issue = "95892")]
736 #[rustc_const_unstable(feature = "const_ptr_sub_ptr", issue = "95892")]
737 #[inline]
738 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
739 pub const unsafe fn sub_ptr(self, origin: *const T) -> usize
740 where
741 T: Sized,
742 {
743 // SAFETY: The comparison has no side-effects, and the intrinsic
744 // does this check internally in the CTFE implementation.
745 unsafe { assert_unsafe_precondition!(self >= origin) };
746
747 let pointee_size = mem::size_of::<T>();
748 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
749 // SAFETY: the caller must uphold the safety contract for `ptr_offset_from_unsigned`.
750 unsafe { intrinsics::ptr_offset_from_unsigned(self, origin) }
751 }
752
753 /// Returns whether two pointers are guaranteed to be equal.
754 ///
755 /// At runtime this function behaves like `self == other`.
756 /// However, in some contexts (e.g., compile-time evaluation),
757 /// it is not always possible to determine equality of two pointers, so this function may
758 /// spuriously return `false` for pointers that later actually turn out to be equal.
759 /// But when it returns `true`, the pointers are guaranteed to be equal.
760 ///
761 /// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
762 /// comparisons for which both functions return `false`.
763 ///
764 /// [`guaranteed_ne`]: #method.guaranteed_ne
765 ///
766 /// The return value may change depending on the compiler version and unsafe code must not
767 /// rely on the result of this function for soundness. It is suggested to only use this function
768 /// for performance optimizations where spurious `false` return values by this function do not
769 /// affect the outcome, but just the performance.
770 /// The consequences of using this method to make runtime and compile-time code behave
771 /// differently have not been explored. This method should not be used to introduce such
772 /// differences, and it should also not be stabilized before we have a better understanding
773 /// of this issue.
774 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
775 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
776 #[inline]
777 pub const fn guaranteed_eq(self, other: *const T) -> bool
778 where
779 T: Sized,
780 {
781 intrinsics::ptr_guaranteed_eq(self, other)
782 }
783
784 /// Returns whether two pointers are guaranteed to be unequal.
785 ///
786 /// At runtime this function behaves like `self != other`.
787 /// However, in some contexts (e.g., compile-time evaluation),
788 /// it is not always possible to determine the inequality of two pointers, so this function may
789 /// spuriously return `false` for pointers that later actually turn out to be unequal.
790 /// But when it returns `true`, the pointers are guaranteed to be unequal.
791 ///
792 /// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
793 /// comparisons for which both functions return `false`.
794 ///
795 /// [`guaranteed_eq`]: #method.guaranteed_eq
796 ///
797 /// The return value may change depending on the compiler version and unsafe code must not
798 /// rely on the result of this function for soundness. It is suggested to only use this function
799 /// for performance optimizations where spurious `false` return values by this function do not
800 /// affect the outcome, but just the performance.
801 /// The consequences of using this method to make runtime and compile-time code behave
802 /// differently have not been explored. This method should not be used to introduce such
803 /// differences, and it should also not be stabilized before we have a better understanding
804 /// of this issue.
805 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
806 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
807 #[inline]
808 pub const fn guaranteed_ne(self, other: *const T) -> bool
809 where
810 T: Sized,
811 {
812 intrinsics::ptr_guaranteed_ne(self, other)
813 }
814
815 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
816 ///
817 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
818 /// offset of `3 * size_of::<T>()` bytes.
819 ///
820 /// # Safety
821 ///
822 /// If any of the following conditions are violated, the result is Undefined
823 /// Behavior:
824 ///
825 /// * Both the starting and resulting pointer must be either in bounds or one
826 /// byte past the end of the same [allocated object].
827 ///
828 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
829 ///
830 /// * The offset being in bounds cannot rely on "wrapping around" the address
831 /// space. That is, the infinite-precision sum must fit in a `usize`.
832 ///
833 /// The compiler and standard library generally tries to ensure allocations
834 /// never reach a size where an offset is a concern. For instance, `Vec`
835 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
836 /// `vec.as_ptr().add(vec.len())` is always safe.
837 ///
838 /// Most platforms fundamentally can't even construct such an allocation.
839 /// For instance, no known 64-bit platform can ever serve a request
840 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
841 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
842 /// more than `isize::MAX` bytes with things like Physical Address
843 /// Extension. As such, memory acquired directly from allocators or memory
844 /// mapped files *may* be too large to handle with this function.
845 ///
846 /// Consider using [`wrapping_add`] instead if these constraints are
847 /// difficult to satisfy. The only advantage of this method is that it
848 /// enables more aggressive compiler optimizations.
849 ///
850 /// [`wrapping_add`]: #method.wrapping_add
851 /// [allocated object]: crate::ptr#allocated-object
852 ///
853 /// # Examples
854 ///
855 /// Basic usage:
856 ///
857 /// ```
858 /// let s: &str = "123";
859 /// let ptr: *const u8 = s.as_ptr();
860 ///
861 /// unsafe {
862 /// println!("{}", *ptr.add(1) as char);
863 /// println!("{}", *ptr.add(2) as char);
864 /// }
865 /// ```
866 #[stable(feature = "pointer_methods", since = "1.26.0")]
867 #[must_use = "returns a new pointer rather than modifying its argument"]
868 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
869 #[inline(always)]
870 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
871 pub const unsafe fn add(self, count: usize) -> Self
872 where
873 T: Sized,
874 {
875 // SAFETY: the caller must uphold the safety contract for `offset`.
876 unsafe { self.offset(count as isize) }
877 }
878
879 /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
880 ///
881 /// `count` is in units of bytes.
882 ///
883 /// This is purely a convenience for casting to a `u8` pointer and
884 /// using [add][pointer::add] on it. See that method for documentation
885 /// and safety requirements.
886 ///
887 /// For non-`Sized` pointees this operation changes only the data pointer,
888 /// leaving the metadata untouched.
889 #[must_use]
890 #[inline(always)]
891 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
892 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
893 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
894 pub const unsafe fn byte_add(self, count: usize) -> Self {
895 // SAFETY: the caller must uphold the safety contract for `add`.
896 let this = unsafe { self.cast::<u8>().add(count).cast::<()>() };
897 from_raw_parts::<T>(this, metadata(self))
898 }
899
900 /// Calculates the offset from a pointer (convenience for
901 /// `.offset((count as isize).wrapping_neg())`).
902 ///
903 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
904 /// offset of `3 * size_of::<T>()` bytes.
905 ///
906 /// # Safety
907 ///
908 /// If any of the following conditions are violated, the result is Undefined
909 /// Behavior:
910 ///
911 /// * Both the starting and resulting pointer must be either in bounds or one
912 /// byte past the end of the same [allocated object].
913 ///
914 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
915 ///
916 /// * The offset being in bounds cannot rely on "wrapping around" the address
917 /// space. That is, the infinite-precision sum must fit in a usize.
918 ///
919 /// The compiler and standard library generally tries to ensure allocations
920 /// never reach a size where an offset is a concern. For instance, `Vec`
921 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
922 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
923 ///
924 /// Most platforms fundamentally can't even construct such an allocation.
925 /// For instance, no known 64-bit platform can ever serve a request
926 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
927 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
928 /// more than `isize::MAX` bytes with things like Physical Address
929 /// Extension. As such, memory acquired directly from allocators or memory
930 /// mapped files *may* be too large to handle with this function.
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 /// [allocated object]: crate::ptr#allocated-object
938 ///
939 /// # Examples
940 ///
941 /// Basic usage:
942 ///
943 /// ```
944 /// let s: &str = "123";
945 ///
946 /// unsafe {
947 /// let end: *const u8 = s.as_ptr().add(3);
948 /// println!("{}", *end.sub(1) as char);
949 /// println!("{}", *end.sub(2) as char);
950 /// }
951 /// ```
952 #[stable(feature = "pointer_methods", since = "1.26.0")]
953 #[must_use = "returns a new pointer rather than modifying its argument"]
954 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
955 #[inline]
956 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
957 pub const unsafe fn sub(self, count: usize) -> Self
958 where
959 T: Sized,
960 {
961 // SAFETY: the caller must uphold the safety contract for `offset`.
962 unsafe { self.offset((count as isize).wrapping_neg()) }
963 }
964
965 /// Calculates the offset from a pointer in bytes (convenience for
966 /// `.byte_offset((count as isize).wrapping_neg())`).
967 ///
968 /// `count` is in units of bytes.
969 ///
970 /// This is purely a convenience for casting to a `u8` pointer and
971 /// using [sub][pointer::sub] on it. See that method for documentation
972 /// and safety requirements.
973 ///
974 /// For non-`Sized` pointees this operation changes only the data pointer,
975 /// leaving the metadata untouched.
976 #[must_use]
977 #[inline(always)]
978 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
979 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
980 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
981 pub const unsafe fn byte_sub(self, count: usize) -> Self {
982 // SAFETY: the caller must uphold the safety contract for `sub`.
983 let this = unsafe { self.cast::<u8>().sub(count).cast::<()>() };
984 from_raw_parts::<T>(this, metadata(self))
985 }
986
987 /// Calculates the offset from a pointer using wrapping arithmetic.
988 /// (convenience for `.wrapping_offset(count as isize)`)
989 ///
990 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
991 /// offset of `3 * size_of::<T>()` bytes.
992 ///
993 /// # Safety
994 ///
995 /// This operation itself is always safe, but using the resulting pointer is not.
996 ///
997 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
998 /// be used to read or write other allocated objects.
999 ///
1000 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1001 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1002 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1003 /// `x` and `y` point into the same allocated object.
1004 ///
1005 /// Compared to [`add`], this method basically delays the requirement of staying within the
1006 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
1007 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1008 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1009 /// can be optimized better and is thus preferable in performance-sensitive code.
1010 ///
1011 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1012 /// intermediate values used during the computation of the final result. For example,
1013 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1014 /// allocated object and then re-entering it later is permitted.
1015 ///
1016 /// [`add`]: #method.add
1017 /// [allocated object]: crate::ptr#allocated-object
1018 ///
1019 /// # Examples
1020 ///
1021 /// Basic usage:
1022 ///
1023 /// ```
1024 /// // Iterate using a raw pointer in increments of two elements
1025 /// let data = [1u8, 2, 3, 4, 5];
1026 /// let mut ptr: *const u8 = data.as_ptr();
1027 /// let step = 2;
1028 /// let end_rounded_up = ptr.wrapping_add(6);
1029 ///
1030 /// // This loop prints "1, 3, 5, "
1031 /// while ptr != end_rounded_up {
1032 /// unsafe {
1033 /// print!("{}, ", *ptr);
1034 /// }
1035 /// ptr = ptr.wrapping_add(step);
1036 /// }
1037 /// ```
1038 #[stable(feature = "pointer_methods", since = "1.26.0")]
1039 #[must_use = "returns a new pointer rather than modifying its argument"]
1040 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1041 #[inline(always)]
1042 pub const fn wrapping_add(self, count: usize) -> Self
1043 where
1044 T: Sized,
1045 {
1046 self.wrapping_offset(count as isize)
1047 }
1048
1049 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1050 /// (convenience for `.wrapping_byte_offset(count as isize)`)
1051 ///
1052 /// `count` is in units of bytes.
1053 ///
1054 /// This is purely a convenience for casting to a `u8` pointer and
1055 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1056 ///
1057 /// For non-`Sized` pointees this operation changes only the data pointer,
1058 /// leaving the metadata untouched.
1059 #[must_use]
1060 #[inline(always)]
1061 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1062 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1063 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1064 from_raw_parts::<T>(self.cast::<u8>().wrapping_add(count).cast::<()>(), metadata(self))
1065 }
1066
1067 /// Calculates the offset from a pointer using wrapping arithmetic.
1068 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1069 ///
1070 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1071 /// offset of `3 * size_of::<T>()` bytes.
1072 ///
1073 /// # Safety
1074 ///
1075 /// This operation itself is always safe, but using the resulting pointer is not.
1076 ///
1077 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1078 /// be used to read or write other allocated objects.
1079 ///
1080 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1081 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1082 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1083 /// `x` and `y` point into the same allocated object.
1084 ///
1085 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1086 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
1087 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1088 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1089 /// can be optimized better and is thus preferable in performance-sensitive code.
1090 ///
1091 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1092 /// intermediate values used during the computation of the final result. For example,
1093 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1094 /// allocated object and then re-entering it later is permitted.
1095 ///
1096 /// [`sub`]: #method.sub
1097 /// [allocated object]: crate::ptr#allocated-object
1098 ///
1099 /// # Examples
1100 ///
1101 /// Basic usage:
1102 ///
1103 /// ```
1104 /// // Iterate using a raw pointer in increments of two elements (backwards)
1105 /// let data = [1u8, 2, 3, 4, 5];
1106 /// let mut ptr: *const u8 = data.as_ptr();
1107 /// let start_rounded_down = ptr.wrapping_sub(2);
1108 /// ptr = ptr.wrapping_add(4);
1109 /// let step = 2;
1110 /// // This loop prints "5, 3, 1, "
1111 /// while ptr != start_rounded_down {
1112 /// unsafe {
1113 /// print!("{}, ", *ptr);
1114 /// }
1115 /// ptr = ptr.wrapping_sub(step);
1116 /// }
1117 /// ```
1118 #[stable(feature = "pointer_methods", since = "1.26.0")]
1119 #[must_use = "returns a new pointer rather than modifying its argument"]
1120 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1121 #[inline]
1122 pub const fn wrapping_sub(self, count: usize) -> Self
1123 where
1124 T: Sized,
1125 {
1126 self.wrapping_offset((count as isize).wrapping_neg())
1127 }
1128
1129 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1130 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1131 ///
1132 /// `count` is in units of bytes.
1133 ///
1134 /// This is purely a convenience for casting to a `u8` pointer and
1135 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1136 ///
1137 /// For non-`Sized` pointees this operation changes only the data pointer,
1138 /// leaving the metadata untouched.
1139 #[must_use]
1140 #[inline(always)]
1141 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1142 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1143 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1144 from_raw_parts::<T>(self.cast::<u8>().wrapping_sub(count).cast::<()>(), metadata(self))
1145 }
1146
1147 /// Reads the value from `self` without moving it. This leaves the
1148 /// memory in `self` unchanged.
1149 ///
1150 /// See [`ptr::read`] for safety concerns and examples.
1151 ///
1152 /// [`ptr::read`]: crate::ptr::read()
1153 #[stable(feature = "pointer_methods", since = "1.26.0")]
1154 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1155 #[inline]
1156 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1157 pub const unsafe fn read(self) -> T
1158 where
1159 T: Sized,
1160 {
1161 // SAFETY: the caller must uphold the safety contract for `read`.
1162 unsafe { read(self) }
1163 }
1164
1165 /// Performs a volatile read of the value from `self` without moving it. This
1166 /// leaves the memory in `self` unchanged.
1167 ///
1168 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1169 /// to not be elided or reordered by the compiler across other volatile
1170 /// operations.
1171 ///
1172 /// See [`ptr::read_volatile`] for safety concerns and examples.
1173 ///
1174 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1175 #[stable(feature = "pointer_methods", since = "1.26.0")]
1176 #[inline]
1177 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1178 pub unsafe fn read_volatile(self) -> T
1179 where
1180 T: Sized,
1181 {
1182 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1183 unsafe { read_volatile(self) }
1184 }
1185
1186 /// Reads the value from `self` without moving it. This leaves the
1187 /// memory in `self` unchanged.
1188 ///
1189 /// Unlike `read`, the pointer may be unaligned.
1190 ///
1191 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1192 ///
1193 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1194 #[stable(feature = "pointer_methods", since = "1.26.0")]
1195 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1196 #[inline]
1197 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1198 pub const unsafe fn read_unaligned(self) -> T
1199 where
1200 T: Sized,
1201 {
1202 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1203 unsafe { read_unaligned(self) }
1204 }
1205
1206 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1207 /// and destination may overlap.
1208 ///
1209 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1210 ///
1211 /// See [`ptr::copy`] for safety concerns and examples.
1212 ///
1213 /// [`ptr::copy`]: crate::ptr::copy()
1214 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1215 #[stable(feature = "pointer_methods", since = "1.26.0")]
1216 #[inline]
1217 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1218 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1219 where
1220 T: Sized,
1221 {
1222 // SAFETY: the caller must uphold the safety contract for `copy`.
1223 unsafe { copy(self, dest, count) }
1224 }
1225
1226 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1227 /// and destination may *not* overlap.
1228 ///
1229 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1230 ///
1231 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1232 ///
1233 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1234 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1235 #[stable(feature = "pointer_methods", since = "1.26.0")]
1236 #[inline]
1237 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1238 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1239 where
1240 T: Sized,
1241 {
1242 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1243 unsafe { copy_nonoverlapping(self, dest, count) }
1244 }
1245
1246 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1247 /// `align`.
1248 ///
1249 /// If it is not possible to align the pointer, the implementation returns
1250 /// `usize::MAX`. It is permissible for the implementation to *always*
1251 /// return `usize::MAX`. Only your algorithm's performance can depend
1252 /// on getting a usable offset here, not its correctness.
1253 ///
1254 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1255 /// used with the `wrapping_add` method.
1256 ///
1257 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1258 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1259 /// the returned offset is correct in all terms other than alignment.
1260 ///
1261 /// # Panics
1262 ///
1263 /// The function panics if `align` is not a power-of-two.
1264 ///
1265 /// # Examples
1266 ///
1267 /// Accessing adjacent `u8` as `u16`
1268 ///
1269 /// ```
1270 /// # fn foo(n: usize) {
1271 /// # use std::mem::align_of;
1272 /// # unsafe {
1273 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1274 /// let ptr = x.as_ptr().add(n) as *const u8;
1275 /// let offset = ptr.align_offset(align_of::<u16>());
1276 /// if offset < x.len() - n - 1 {
1277 /// let u16_ptr = ptr.add(offset) as *const u16;
1278 /// assert_ne!(*u16_ptr, 500);
1279 /// } else {
1280 /// // while the pointer can be aligned via `offset`, it would point
1281 /// // outside the allocation
1282 /// }
1283 /// # } }
1284 /// ```
1285 #[stable(feature = "align_offset", since = "1.36.0")]
1286 #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1287 pub const fn align_offset(self, align: usize) -> usize
1288 where
1289 T: Sized,
1290 {
1291 if !align.is_power_of_two() {
1292 panic!("align_offset: align is not a power-of-two");
1293 }
1294
1295 fn rt_impl<T>(p: *const T, align: usize) -> usize {
1296 // SAFETY: `align` has been checked to be a power of 2 above
1297 unsafe { align_offset(p, align) }
1298 }
1299
1300 const fn ctfe_impl<T>(_: *const T, _: usize) -> usize {
1301 usize::MAX
1302 }
1303
1304 // SAFETY:
1305 // It is permissible for `align_offset` to always return `usize::MAX`,
1306 // algorithm correctness can not depend on `align_offset` returning non-max values.
1307 //
1308 // As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
1309 unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
1310 }
1311
1312 /// Returns whether the pointer is properly aligned for `T`.
1313 #[must_use]
1314 #[inline]
1315 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1316 pub fn is_aligned(self) -> bool
1317 where
1318 T: Sized,
1319 {
1320 self.is_aligned_to(core::mem::align_of::<T>())
1321 }
1322
1323 /// Returns whether the pointer is aligned to `align`.
1324 ///
1325 /// For non-`Sized` pointees this operation considers only the data pointer,
1326 /// ignoring the metadata.
1327 ///
1328 /// # Panics
1329 ///
1330 /// The function panics if `align` is not a power-of-two (this includes 0).
1331 #[must_use]
1332 #[inline]
1333 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1334 pub fn is_aligned_to(self, align: usize) -> bool {
1335 if !align.is_power_of_two() {
1336 panic!("is_aligned_to: align is not a power-of-two");
1337 }
1338
1339 // SAFETY: `is_power_of_two()` will return `false` for zero.
1340 unsafe { core::intrinsics::assume(align != 0) };
1341
1342 // Cast is needed for `T: !Sized`
1343 self.cast::<u8>().addr() % align == 0
1344 }
1345 }
1346
1347 impl<T> *const [T] {
1348 /// Returns the length of a raw slice.
1349 ///
1350 /// The returned value is the number of **elements**, not the number of bytes.
1351 ///
1352 /// This function is safe, even when the raw slice cannot be cast to a slice
1353 /// reference because the pointer is null or unaligned.
1354 ///
1355 /// # Examples
1356 ///
1357 /// ```rust
1358 /// #![feature(slice_ptr_len)]
1359 ///
1360 /// use std::ptr;
1361 ///
1362 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1363 /// assert_eq!(slice.len(), 3);
1364 /// ```
1365 #[inline]
1366 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1367 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1368 pub const fn len(self) -> usize {
1369 metadata(self)
1370 }
1371
1372 /// Returns a raw pointer to the slice's buffer.
1373 ///
1374 /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1375 ///
1376 /// # Examples
1377 ///
1378 /// ```rust
1379 /// #![feature(slice_ptr_get)]
1380 /// use std::ptr;
1381 ///
1382 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1383 /// assert_eq!(slice.as_ptr(), ptr::null());
1384 /// ```
1385 #[inline]
1386 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1387 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
1388 pub const fn as_ptr(self) -> *const T {
1389 self as *const T
1390 }
1391
1392 /// Returns a raw pointer to an element or subslice, without doing bounds
1393 /// checking.
1394 ///
1395 /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
1396 /// is *[undefined behavior]* even if the resulting pointer is not used.
1397 ///
1398 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1399 ///
1400 /// # Examples
1401 ///
1402 /// ```
1403 /// #![feature(slice_ptr_get)]
1404 ///
1405 /// let x = &[1, 2, 4] as *const [i32];
1406 ///
1407 /// unsafe {
1408 /// assert_eq!(x.get_unchecked(1), x.as_ptr().add(1));
1409 /// }
1410 /// ```
1411 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1412 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
1413 #[inline]
1414 pub const unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output
1415 where
1416 I: ~const SliceIndex<[T]>,
1417 {
1418 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1419 unsafe { index.get_unchecked(self) }
1420 }
1421
1422 /// Returns `None` if the pointer is null, or else returns a shared slice to
1423 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1424 /// that the value has to be initialized.
1425 ///
1426 /// [`as_ref`]: #method.as_ref
1427 ///
1428 /// # Safety
1429 ///
1430 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1431 /// all of the following is true:
1432 ///
1433 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1434 /// and it must be properly aligned. This means in particular:
1435 ///
1436 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1437 /// Slices can never span across multiple allocated objects.
1438 ///
1439 /// * The pointer must be aligned even for zero-length slices. One
1440 /// reason for this is that enum layout optimizations may rely on references
1441 /// (including slices of any length) being aligned and non-null to distinguish
1442 /// them from other data. You can obtain a pointer that is usable as `data`
1443 /// for zero-length slices using [`NonNull::dangling()`].
1444 ///
1445 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1446 /// See the safety documentation of [`pointer::offset`].
1447 ///
1448 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1449 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1450 /// In particular, while this reference exists, the memory the pointer points to must
1451 /// not get mutated (except inside `UnsafeCell`).
1452 ///
1453 /// This applies even if the result of this method is unused!
1454 ///
1455 /// See also [`slice::from_raw_parts`][].
1456 ///
1457 /// [valid]: crate::ptr#safety
1458 /// [allocated object]: crate::ptr#allocated-object
1459 #[inline]
1460 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1461 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1462 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1463 if self.is_null() {
1464 None
1465 } else {
1466 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1467 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1468 }
1469 }
1470 }
1471
1472 // Equality for pointers
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<T: ?Sized> PartialEq for *const T {
1475 #[inline]
1476 fn eq(&self, other: &*const T) -> bool {
1477 *self == *other
1478 }
1479 }
1480
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl<T: ?Sized> Eq for *const T {}
1483
1484 // Comparison for pointers
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl<T: ?Sized> Ord for *const T {
1487 #[inline]
1488 fn cmp(&self, other: &*const T) -> Ordering {
1489 if self < other {
1490 Less
1491 } else if self == other {
1492 Equal
1493 } else {
1494 Greater
1495 }
1496 }
1497 }
1498
1499 #[stable(feature = "rust1", since = "1.0.0")]
1500 impl<T: ?Sized> PartialOrd for *const T {
1501 #[inline]
1502 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
1503 Some(self.cmp(other))
1504 }
1505
1506 #[inline]
1507 fn lt(&self, other: &*const T) -> bool {
1508 *self < *other
1509 }
1510
1511 #[inline]
1512 fn le(&self, other: &*const T) -> bool {
1513 *self <= *other
1514 }
1515
1516 #[inline]
1517 fn gt(&self, other: &*const T) -> bool {
1518 *self > *other
1519 }
1520
1521 #[inline]
1522 fn ge(&self, other: &*const T) -> bool {
1523 *self >= *other
1524 }
1525 }