2 use crate::cmp::Ordering::{self, Equal, Greater, Less};
5 use crate::slice::{self, SliceIndex};
7 impl<T: ?Sized> *const T {
8 /// Returns `true` if the pointer is null.
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
15 /// ## Behavior during const evaluation
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
29 /// let s: &str = "Follow the rabbit";
30 /// let ptr: *const u8 = s.as_ptr();
31 /// assert!(!ptr.is_null());
33 #[stable(feature = "rust1", since = "1.0.0")]
34 #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")]
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 match (self as *const u8).guaranteed_eq(null()) {
45 /// Casts to a pointer of another type.
46 #[stable(feature = "ptr_cast", since = "1.38.0")]
47 #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
49 pub const fn cast<U>(self) -> *const U {
53 /// Use the pointer value in a new pointer of another type.
55 /// In case `val` is a (fat) pointer to an unsized type, this operation
56 /// will ignore the pointer part, whereas for (thin) pointers to sized
57 /// types, this has the same effect as a simple cast.
59 /// The resulting pointer will have provenance of `self`, i.e., for a fat
60 /// pointer, this operation is semantically the same as creating a new
61 /// fat pointer with the data pointer value of `self` but the metadata of
66 /// This function is primarily useful for allowing byte-wise pointer
67 /// arithmetic on potentially fat pointers:
70 /// #![feature(set_ptr_value)]
71 /// # use core::fmt::Debug;
72 /// let arr: [i32; 3] = [1, 2, 3];
73 /// let mut ptr = arr.as_ptr() as *const dyn Debug;
74 /// let thin = ptr as *const u8;
76 /// ptr = thin.add(8).with_metadata_of(ptr);
77 /// # assert_eq!(*(ptr as *const i32), 3);
78 /// println!("{:?}", &*ptr); // will print "3"
81 #[unstable(feature = "set_ptr_value", issue = "75091")]
82 #[rustc_const_unstable(feature = "set_ptr_value", issue = "75091")]
83 #[must_use = "returns a new pointer rather than modifying its argument"]
85 pub const fn with_metadata_of<U>(self, meta: *const U) -> *const U
89 from_raw_parts::<U>(self as *const (), metadata(meta))
92 /// Changes constness without changing the type.
94 /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
96 #[stable(feature = "ptr_const_cast", since = "1.65.0")]
97 #[rustc_const_stable(feature = "ptr_const_cast", since = "1.65.0")]
98 pub const fn cast_mut(self) -> *mut T {
102 /// Casts a pointer to its raw bits.
104 /// This is equivalent to `as usize`, but is more specific to enhance readability.
105 /// The inverse method is [`from_bits`](#method.from_bits).
107 /// In particular, `*p as usize` and `p as usize` will both compile for
108 /// pointers to numeric types but do very different things, so using this
109 /// helps emphasize that reading the bits was intentional.
114 /// #![feature(ptr_to_from_bits)]
115 /// let array = [13, 42];
116 /// let p0: *const i32 = &array[0];
117 /// assert_eq!(<*const _>::from_bits(p0.to_bits()), p0);
118 /// let p1: *const i32 = &array[1];
119 /// assert_eq!(p1.to_bits() - p0.to_bits(), 4);
121 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
122 pub fn to_bits(self) -> usize
129 /// Creates a pointer from its raw bits.
131 /// This is equivalent to `as *const T`, but is more specific to enhance readability.
132 /// The inverse method is [`to_bits`](#method.to_bits).
137 /// #![feature(ptr_to_from_bits)]
138 /// use std::ptr::NonNull;
139 /// let dangling: *const u8 = NonNull::dangling().as_ptr();
140 /// assert_eq!(<*const u8>::from_bits(1), dangling);
142 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
143 #[allow(fuzzy_provenance_casts)] // this is an unstable and semi-deprecated cast function
144 pub fn from_bits(bits: usize) -> Self
151 /// Gets the "address" portion of the pointer.
153 /// This is similar to `self as usize`, which semantically discards *provenance* and
154 /// *address-space* information. However, unlike `self as usize`, casting the returned address
155 /// back to a pointer yields [`invalid`][], which is undefined behavior to dereference. To
156 /// properly restore the lost information and obtain a dereferenceable pointer, use
157 /// [`with_addr`][pointer::with_addr] or [`map_addr`][pointer::map_addr].
159 /// If using those APIs is not possible because there is no way to preserve a pointer with the
160 /// required provenance, use [`expose_addr`][pointer::expose_addr] and
161 /// [`from_exposed_addr`][from_exposed_addr] instead. However, note that this makes
162 /// your code less portable and less amenable to tools that check for compliance with the Rust
165 /// On most platforms this will produce a value with the same bytes as the original
166 /// pointer, because all the bytes are dedicated to describing the address.
167 /// Platforms which need to store additional information in the pointer may
168 /// perform a change of representation to produce a value containing only the address
169 /// portion of the pointer. What that means is up to the platform to define.
171 /// This API and its claimed semantics are part of the Strict Provenance experiment, and as such
172 /// might change in the future (including possibly weakening this so it becomes wholly
173 /// equivalent to `self as usize`). See the [module documentation][crate::ptr] for details.
176 #[unstable(feature = "strict_provenance", issue = "95228")]
177 pub fn addr(self) -> usize
181 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
182 // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
184 unsafe { mem::transmute(self) }
187 /// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future
188 /// use in [`from_exposed_addr`][].
190 /// This is equivalent to `self as usize`, which semantically discards *provenance* and
191 /// *address-space* information. Furthermore, this (like the `as` cast) has the implicit
192 /// side-effect of marking the provenance as 'exposed', so on platforms that support it you can
193 /// later call [`from_exposed_addr`][] to reconstitute the original pointer including its
194 /// provenance. (Reconstructing address space information, if required, is your responsibility.)
196 /// Using this method means that code is *not* following Strict Provenance rules. Supporting
197 /// [`from_exposed_addr`][] complicates specification and reasoning and may not be supported by
198 /// tools that help you to stay conformant with the Rust memory model, so it is recommended to
199 /// use [`addr`][pointer::addr] wherever possible.
201 /// On most platforms this will produce a value with the same bytes as the original pointer,
202 /// because all the bytes are dedicated to describing the address. Platforms which need to store
203 /// additional information in the pointer may not support this operation, since the 'expose'
204 /// side-effect which is required for [`from_exposed_addr`][] to work is typically not
207 /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
208 /// [module documentation][crate::ptr] for details.
210 /// [`from_exposed_addr`]: from_exposed_addr
213 #[unstable(feature = "strict_provenance", issue = "95228")]
214 pub fn expose_addr(self) -> usize
218 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
222 /// Creates a new pointer with the given address.
224 /// This performs the same operation as an `addr as ptr` cast, but copies
225 /// the *address-space* and *provenance* of `self` to the new pointer.
226 /// This allows us to dynamically preserve and propagate this important
227 /// information in a way that is otherwise impossible with a unary cast.
229 /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
230 /// `self` to the given address, and therefore has all the same capabilities and restrictions.
232 /// This API and its claimed semantics are part of the Strict Provenance experiment,
233 /// see the [module documentation][crate::ptr] for details.
236 #[unstable(feature = "strict_provenance", issue = "95228")]
237 pub fn with_addr(self, addr: usize) -> Self
241 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
243 // In the mean-time, this operation is defined to be "as if" it was
244 // a wrapping_offset, so we can emulate it as such. This should properly
245 // restore pointer provenance even under today's compiler.
246 let self_addr = self.addr() as isize;
247 let dest_addr = addr as isize;
248 let offset = dest_addr.wrapping_sub(self_addr);
250 // This is the canonical desugarring of this operation
251 self.wrapping_byte_offset(offset)
254 /// Creates a new pointer by mapping `self`'s address to a new one.
256 /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
258 /// This API and its claimed semantics are part of the Strict Provenance experiment,
259 /// see the [module documentation][crate::ptr] for details.
262 #[unstable(feature = "strict_provenance", issue = "95228")]
263 pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self
267 self.with_addr(f(self.addr()))
270 /// Decompose a (possibly wide) pointer into its address and metadata components.
272 /// The pointer can be later reconstructed with [`from_raw_parts`].
273 #[unstable(feature = "ptr_metadata", issue = "81513")]
274 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
276 pub const fn to_raw_parts(self) -> (*const (), <T as super::Pointee>::Metadata) {
277 (self.cast(), metadata(self))
280 /// Returns `None` if the pointer is null, or else returns a shared reference to
281 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
282 /// must be used instead.
284 /// [`as_uninit_ref`]: #method.as_uninit_ref
288 /// When calling this method, you have to ensure that *either* the pointer is null *or*
289 /// all of the following is true:
291 /// * The pointer must be properly aligned.
293 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
295 /// * The pointer must point to an initialized instance of `T`.
297 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
298 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
299 /// In particular, while this reference exists, the memory the pointer points to must
300 /// not get mutated (except inside `UnsafeCell`).
302 /// This applies even if the result of this method is unused!
303 /// (The part about being initialized is not yet fully decided, but until
304 /// it is, the only safe approach is to ensure that they are indeed initialized.)
306 /// [the module documentation]: crate::ptr#safety
313 /// let ptr: *const u8 = &10u8 as *const u8;
316 /// if let Some(val_back) = ptr.as_ref() {
317 /// println!("We got back the value: {val_back}!");
322 /// # Null-unchecked version
324 /// If you are sure the pointer can never be null and are looking for some kind of
325 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
326 /// dereference the pointer directly.
329 /// let ptr: *const u8 = &10u8 as *const u8;
332 /// let val_back = &*ptr;
333 /// println!("We got back the value: {val_back}!");
336 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
337 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
339 pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
340 // SAFETY: the caller must guarantee that `self` is valid
341 // for a reference if it isn't null.
342 if self.is_null() { None } else { unsafe { Some(&*self) } }
345 /// Returns `None` if the pointer is null, or else returns a shared reference to
346 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
347 /// that the value has to be initialized.
349 /// [`as_ref`]: #method.as_ref
353 /// When calling this method, you have to ensure that *either* the pointer is null *or*
354 /// all of the following is true:
356 /// * The pointer must be properly aligned.
358 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
360 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
361 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
362 /// In particular, while this reference exists, the memory the pointer points to must
363 /// not get mutated (except inside `UnsafeCell`).
365 /// This applies even if the result of this method is unused!
367 /// [the module documentation]: crate::ptr#safety
374 /// #![feature(ptr_as_uninit)]
376 /// let ptr: *const u8 = &10u8 as *const u8;
379 /// if let Some(val_back) = ptr.as_uninit_ref() {
380 /// println!("We got back the value: {}!", val_back.assume_init());
385 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
386 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
387 pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
391 // SAFETY: the caller must guarantee that `self` meets all the
392 // requirements for a reference.
393 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
396 /// Calculates the offset from a pointer.
398 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
399 /// offset of `3 * size_of::<T>()` bytes.
403 /// If any of the following conditions are violated, the result is Undefined
406 /// * Both the starting and resulting pointer must be either in bounds or one
407 /// byte past the end of the same [allocated object].
409 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
411 /// * The offset being in bounds cannot rely on "wrapping around" the address
412 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
414 /// The compiler and standard library generally tries to ensure allocations
415 /// never reach a size where an offset is a concern. For instance, `Vec`
416 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
417 /// `vec.as_ptr().add(vec.len())` is always safe.
419 /// Most platforms fundamentally can't even construct such an allocation.
420 /// For instance, no known 64-bit platform can ever serve a request
421 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
422 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
423 /// more than `isize::MAX` bytes with things like Physical Address
424 /// Extension. As such, memory acquired directly from allocators or memory
425 /// mapped files *may* be too large to handle with this function.
427 /// Consider using [`wrapping_offset`] instead if these constraints are
428 /// difficult to satisfy. The only advantage of this method is that it
429 /// enables more aggressive compiler optimizations.
431 /// [`wrapping_offset`]: #method.wrapping_offset
432 /// [allocated object]: crate::ptr#allocated-object
439 /// let s: &str = "123";
440 /// let ptr: *const u8 = s.as_ptr();
443 /// println!("{}", *ptr.offset(1) as char);
444 /// println!("{}", *ptr.offset(2) as char);
447 #[stable(feature = "rust1", since = "1.0.0")]
448 #[must_use = "returns a new pointer rather than modifying its argument"]
449 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
451 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
452 pub const unsafe fn offset(self, count: isize) -> *const T
456 // SAFETY: the caller must uphold the safety contract for `offset`.
457 unsafe { intrinsics::offset(self, count) }
460 /// Calculates the offset from a pointer in bytes.
462 /// `count` is in units of **bytes**.
464 /// This is purely a convenience for casting to a `u8` pointer and
465 /// using [offset][pointer::offset] on it. See that method for documentation
466 /// and safety requirements.
468 /// For non-`Sized` pointees this operation changes only the data pointer,
469 /// leaving the metadata untouched.
472 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
473 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
474 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
475 pub const unsafe fn byte_offset(self, count: isize) -> Self {
476 // SAFETY: the caller must uphold the safety contract for `offset`.
477 unsafe { self.cast::<u8>().offset(count).with_metadata_of(self) }
480 /// Calculates the offset from a pointer using wrapping arithmetic.
482 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
483 /// offset of `3 * size_of::<T>()` bytes.
487 /// This operation itself is always safe, but using the resulting pointer is not.
489 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
490 /// be used to read or write other allocated objects.
492 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
493 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
494 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
495 /// `x` and `y` point into the same allocated object.
497 /// Compared to [`offset`], this method basically delays the requirement of staying within the
498 /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
499 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
500 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
501 /// can be optimized better and is thus preferable in performance-sensitive code.
503 /// The delayed check only considers the value of the pointer that was dereferenced, not the
504 /// intermediate values used during the computation of the final result. For example,
505 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
506 /// words, leaving the allocated object and then re-entering it later is permitted.
508 /// [`offset`]: #method.offset
509 /// [allocated object]: crate::ptr#allocated-object
516 /// // Iterate using a raw pointer in increments of two elements
517 /// let data = [1u8, 2, 3, 4, 5];
518 /// let mut ptr: *const u8 = data.as_ptr();
520 /// let end_rounded_up = ptr.wrapping_offset(6);
522 /// // This loop prints "1, 3, 5, "
523 /// while ptr != end_rounded_up {
525 /// print!("{}, ", *ptr);
527 /// ptr = ptr.wrapping_offset(step);
530 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
531 #[must_use = "returns a new pointer rather than modifying its argument"]
532 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
534 pub const fn wrapping_offset(self, count: isize) -> *const T
538 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
539 unsafe { intrinsics::arith_offset(self, count) }
542 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
544 /// `count` is in units of **bytes**.
546 /// This is purely a convenience for casting to a `u8` pointer and
547 /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
548 /// for documentation.
550 /// For non-`Sized` pointees this operation changes only the data pointer,
551 /// leaving the metadata untouched.
554 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
555 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
556 pub const fn wrapping_byte_offset(self, count: isize) -> Self {
557 self.cast::<u8>().wrapping_offset(count).with_metadata_of(self)
560 /// Masks out bits of the pointer according to a mask.
562 /// This is convenience for `ptr.map_addr(|a| a & mask)`.
564 /// For non-`Sized` pointees this operation changes only the data pointer,
565 /// leaving the metadata untouched.
570 /// #![feature(ptr_mask, strict_provenance)]
572 /// let ptr: *const u32 = &v;
574 /// // `u32` is 4 bytes aligned,
575 /// // which means that lower 2 bits are always 0.
576 /// let tag_mask = 0b11;
577 /// let ptr_mask = !tag_mask;
579 /// // We can store something in these lower bits
580 /// let tagged_ptr = ptr.map_addr(|a| a | 0b10);
582 /// // Get the "tag" back
583 /// let tag = tagged_ptr.addr() & tag_mask;
584 /// assert_eq!(tag, 0b10);
586 /// // Note that `tagged_ptr` is unaligned, it's UB to read from it.
587 /// // To get original pointer `mask` can be used:
588 /// let masked_ptr = tagged_ptr.mask(ptr_mask);
589 /// assert_eq!(unsafe { *masked_ptr }, 17);
591 #[unstable(feature = "ptr_mask", issue = "98290")]
592 #[must_use = "returns a new pointer rather than modifying its argument"]
594 pub fn mask(self, mask: usize) -> *const T {
595 intrinsics::ptr_mask(self.cast::<()>(), mask).with_metadata_of(self)
598 /// Calculates the distance between two pointers. The returned value is in
599 /// units of T: the distance in bytes divided by `mem::size_of::<T>()`.
601 /// This function is the inverse of [`offset`].
603 /// [`offset`]: #method.offset
607 /// If any of the following conditions are violated, the result is Undefined
610 /// * Both the starting and other pointer must be either in bounds or one
611 /// byte past the end of the same [allocated object].
613 /// * Both pointers must be *derived from* a pointer to the same object.
614 /// (See below for an example.)
616 /// * The distance between the pointers, in bytes, must be an exact multiple
617 /// of the size of `T`.
619 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
621 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
623 /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
624 /// address space, so two pointers within some value of any Rust type `T` will always satisfy
625 /// the last two conditions. The standard library also generally ensures that allocations
626 /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
627 /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
628 /// always satisfies the last two conditions.
630 /// Most platforms fundamentally can't even construct such a large allocation.
631 /// For instance, no known 64-bit platform can ever serve a request
632 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
633 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
634 /// more than `isize::MAX` bytes with things like Physical Address
635 /// Extension. As such, memory acquired directly from allocators or memory
636 /// mapped files *may* be too large to handle with this function.
637 /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
638 /// such large allocations either.)
640 /// [`add`]: #method.add
641 /// [allocated object]: crate::ptr#allocated-object
645 /// This function panics if `T` is a Zero-Sized Type ("ZST").
653 /// let ptr1: *const i32 = &a[1];
654 /// let ptr2: *const i32 = &a[3];
656 /// assert_eq!(ptr2.offset_from(ptr1), 2);
657 /// assert_eq!(ptr1.offset_from(ptr2), -2);
658 /// assert_eq!(ptr1.offset(2), ptr2);
659 /// assert_eq!(ptr2.offset(-2), ptr1);
663 /// *Incorrect* usage:
666 /// let ptr1 = Box::into_raw(Box::new(0u8)) as *const u8;
667 /// let ptr2 = Box::into_raw(Box::new(1u8)) as *const u8;
668 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
669 /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
670 /// let ptr2_other = (ptr1 as *const u8).wrapping_offset(diff);
671 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
672 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
673 /// // computing their offset is undefined behavior, even though
674 /// // they point to the same address!
676 /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
679 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
680 #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
682 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
683 pub const unsafe fn offset_from(self, origin: *const T) -> isize
687 let pointee_size = mem::size_of::<T>();
688 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
689 // SAFETY: the caller must uphold the safety contract for `ptr_offset_from`.
690 unsafe { intrinsics::ptr_offset_from(self, origin) }
693 /// Calculates the distance between two pointers. The returned value is in
694 /// units of **bytes**.
696 /// This is purely a convenience for casting to a `u8` pointer and
697 /// using [offset_from][pointer::offset_from] on it. See that method for
698 /// documentation and safety requirements.
700 /// For non-`Sized` pointees this operation considers only the data pointers,
701 /// ignoring the metadata.
703 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
704 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
705 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
706 pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: *const U) -> isize {
707 // SAFETY: the caller must uphold the safety contract for `offset_from`.
708 unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
711 /// Calculates the distance between two pointers, *where it's known that
712 /// `self` is equal to or greater than `origin`*. The returned value is in
713 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
715 /// This computes the same value that [`offset_from`](#method.offset_from)
716 /// would compute, but with the added precondition that the offset is
717 /// guaranteed to be non-negative. This method is equivalent to
718 /// `usize::from(self.offset_from(origin)).unwrap_unchecked()`,
719 /// but it provides slightly more information to the optimizer, which can
720 /// sometimes allow it to optimize slightly better with some backends.
722 /// This method can be though of as recovering the `count` that was passed
723 /// to [`add`](#method.add) (or, with the parameters in the other order,
724 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
725 /// that their safety preconditions are met:
727 /// # #![feature(ptr_sub_ptr)]
728 /// # unsafe fn blah(ptr: *const i32, origin: *const i32, count: usize) -> bool {
729 /// ptr.sub_ptr(origin) == count
731 /// origin.add(count) == ptr
733 /// ptr.sub(count) == origin
739 /// - The distance between the pointers must be non-negative (`self >= origin`)
741 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
742 /// apply to this method as well; see it for the full details.
744 /// Importantly, despite the return type of this method being able to represent
745 /// a larger offset, it's still *not permitted* to pass pointers which differ
746 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
747 /// always be less than or equal to `isize::MAX as usize`.
751 /// This function panics if `T` is a Zero-Sized Type ("ZST").
756 /// #![feature(ptr_sub_ptr)]
759 /// let ptr1: *const i32 = &a[1];
760 /// let ptr2: *const i32 = &a[3];
762 /// assert_eq!(ptr2.sub_ptr(ptr1), 2);
763 /// assert_eq!(ptr1.add(2), ptr2);
764 /// assert_eq!(ptr2.sub(2), ptr1);
765 /// assert_eq!(ptr2.sub_ptr(ptr2), 0);
768 /// // This would be incorrect, as the pointers are not correctly ordered:
769 /// // ptr1.sub_ptr(ptr2)
771 #[unstable(feature = "ptr_sub_ptr", issue = "95892")]
772 #[rustc_const_unstable(feature = "const_ptr_sub_ptr", issue = "95892")]
774 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
775 pub const unsafe fn sub_ptr(self, origin: *const T) -> usize
780 // SAFETY: The comparison has no side-effects, and the intrinsic
781 // does this check internally in the CTFE implementation.
783 assert_unsafe_precondition!(
784 "ptr::sub_ptr requires `this >= origin`",
785 [T](this: *const T, origin: *const T) => this >= origin
789 let pointee_size = mem::size_of::<T>();
790 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
791 // SAFETY: the caller must uphold the safety contract for `ptr_offset_from_unsigned`.
792 unsafe { intrinsics::ptr_offset_from_unsigned(self, origin) }
795 /// Returns whether two pointers are guaranteed to be equal.
797 /// At runtime this function behaves like `Some(self == other)`.
798 /// However, in some contexts (e.g., compile-time evaluation),
799 /// it is not always possible to determine equality of two pointers, so this function may
800 /// spuriously return `None` for pointers that later actually turn out to have its equality known.
801 /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
803 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
804 /// version and unsafe code must not
805 /// rely on the result of this function for soundness. It is suggested to only use this function
806 /// for performance optimizations where spurious `None` return values by this function do not
807 /// affect the outcome, but just the performance.
808 /// The consequences of using this method to make runtime and compile-time code behave
809 /// differently have not been explored. This method should not be used to introduce such
810 /// differences, and it should also not be stabilized before we have a better understanding
812 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
813 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
815 pub const fn guaranteed_eq(self, other: *const T) -> Option<bool>
819 match intrinsics::ptr_guaranteed_cmp(self as _, other as _) {
821 other => Some(other == 1),
825 /// Returns whether two pointers are guaranteed to be inequal.
827 /// At runtime this function behaves like `Some(self != other)`.
828 /// However, in some contexts (e.g., compile-time evaluation),
829 /// it is not always possible to determine inequality of two pointers, so this function may
830 /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
831 /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
833 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
834 /// version and unsafe code must not
835 /// rely on the result of this function for soundness. It is suggested to only use this function
836 /// for performance optimizations where spurious `None` return values by this function do not
837 /// affect the outcome, but just the performance.
838 /// The consequences of using this method to make runtime and compile-time code behave
839 /// differently have not been explored. This method should not be used to introduce such
840 /// differences, and it should also not be stabilized before we have a better understanding
842 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
843 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
845 pub const fn guaranteed_ne(self, other: *const T) -> Option<bool>
849 match self.guaranteed_eq(other) {
851 Some(eq) => Some(!eq),
855 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
857 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
858 /// offset of `3 * size_of::<T>()` bytes.
862 /// If any of the following conditions are violated, the result is Undefined
865 /// * Both the starting and resulting pointer must be either in bounds or one
866 /// byte past the end of the same [allocated object].
868 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
870 /// * The offset being in bounds cannot rely on "wrapping around" the address
871 /// space. That is, the infinite-precision sum must fit in a `usize`.
873 /// The compiler and standard library generally tries to ensure allocations
874 /// never reach a size where an offset is a concern. For instance, `Vec`
875 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
876 /// `vec.as_ptr().add(vec.len())` is always safe.
878 /// Most platforms fundamentally can't even construct such an allocation.
879 /// For instance, no known 64-bit platform can ever serve a request
880 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
881 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
882 /// more than `isize::MAX` bytes with things like Physical Address
883 /// Extension. As such, memory acquired directly from allocators or memory
884 /// mapped files *may* be too large to handle with this function.
886 /// Consider using [`wrapping_add`] instead if these constraints are
887 /// difficult to satisfy. The only advantage of this method is that it
888 /// enables more aggressive compiler optimizations.
890 /// [`wrapping_add`]: #method.wrapping_add
891 /// [allocated object]: crate::ptr#allocated-object
898 /// let s: &str = "123";
899 /// let ptr: *const u8 = s.as_ptr();
902 /// println!("{}", *ptr.add(1) as char);
903 /// println!("{}", *ptr.add(2) as char);
906 #[stable(feature = "pointer_methods", since = "1.26.0")]
907 #[must_use = "returns a new pointer rather than modifying its argument"]
908 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
910 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
911 pub const unsafe fn add(self, count: usize) -> Self
915 // SAFETY: the caller must uphold the safety contract for `offset`.
916 unsafe { self.offset(count as isize) }
919 /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
921 /// `count` is in units of bytes.
923 /// This is purely a convenience for casting to a `u8` pointer and
924 /// using [add][pointer::add] on it. See that method for documentation
925 /// and safety requirements.
927 /// For non-`Sized` pointees this operation changes only the data pointer,
928 /// leaving the metadata untouched.
931 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
932 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
933 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
934 pub const unsafe fn byte_add(self, count: usize) -> Self {
935 // SAFETY: the caller must uphold the safety contract for `add`.
936 unsafe { self.cast::<u8>().add(count).with_metadata_of(self) }
939 /// Calculates the offset from a pointer (convenience for
940 /// `.offset((count as isize).wrapping_neg())`).
942 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
943 /// offset of `3 * size_of::<T>()` bytes.
947 /// If any of the following conditions are violated, the result is Undefined
950 /// * Both the starting and resulting pointer must be either in bounds or one
951 /// byte past the end of the same [allocated object].
953 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
955 /// * The offset being in bounds cannot rely on "wrapping around" the address
956 /// space. That is, the infinite-precision sum must fit in a usize.
958 /// The compiler and standard library generally tries to ensure allocations
959 /// never reach a size where an offset is a concern. For instance, `Vec`
960 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
961 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
963 /// Most platforms fundamentally can't even construct such an allocation.
964 /// For instance, no known 64-bit platform can ever serve a request
965 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
966 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
967 /// more than `isize::MAX` bytes with things like Physical Address
968 /// Extension. As such, memory acquired directly from allocators or memory
969 /// mapped files *may* be too large to handle with this function.
971 /// Consider using [`wrapping_sub`] instead if these constraints are
972 /// difficult to satisfy. The only advantage of this method is that it
973 /// enables more aggressive compiler optimizations.
975 /// [`wrapping_sub`]: #method.wrapping_sub
976 /// [allocated object]: crate::ptr#allocated-object
983 /// let s: &str = "123";
986 /// let end: *const u8 = s.as_ptr().add(3);
987 /// println!("{}", *end.sub(1) as char);
988 /// println!("{}", *end.sub(2) as char);
991 #[stable(feature = "pointer_methods", since = "1.26.0")]
992 #[must_use = "returns a new pointer rather than modifying its argument"]
993 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
995 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
996 pub const unsafe fn sub(self, count: usize) -> Self
1000 // SAFETY: the caller must uphold the safety contract for `offset`.
1001 unsafe { self.offset((count as isize).wrapping_neg()) }
1004 /// Calculates the offset from a pointer in bytes (convenience for
1005 /// `.byte_offset((count as isize).wrapping_neg())`).
1007 /// `count` is in units of bytes.
1009 /// This is purely a convenience for casting to a `u8` pointer and
1010 /// using [sub][pointer::sub] on it. See that method for documentation
1011 /// and safety requirements.
1013 /// For non-`Sized` pointees this operation changes only the data pointer,
1014 /// leaving the metadata untouched.
1017 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1018 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1019 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1020 pub const unsafe fn byte_sub(self, count: usize) -> Self {
1021 // SAFETY: the caller must uphold the safety contract for `sub`.
1022 unsafe { self.cast::<u8>().sub(count).with_metadata_of(self) }
1025 /// Calculates the offset from a pointer using wrapping arithmetic.
1026 /// (convenience for `.wrapping_offset(count as isize)`)
1028 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1029 /// offset of `3 * size_of::<T>()` bytes.
1033 /// This operation itself is always safe, but using the resulting pointer is not.
1035 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1036 /// be used to read or write other allocated objects.
1038 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1039 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1040 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1041 /// `x` and `y` point into the same allocated object.
1043 /// Compared to [`add`], this method basically delays the requirement of staying within the
1044 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
1045 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1046 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1047 /// can be optimized better and is thus preferable in performance-sensitive code.
1049 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1050 /// intermediate values used during the computation of the final result. For example,
1051 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1052 /// allocated object and then re-entering it later is permitted.
1054 /// [`add`]: #method.add
1055 /// [allocated object]: crate::ptr#allocated-object
1062 /// // Iterate using a raw pointer in increments of two elements
1063 /// let data = [1u8, 2, 3, 4, 5];
1064 /// let mut ptr: *const u8 = data.as_ptr();
1066 /// let end_rounded_up = ptr.wrapping_add(6);
1068 /// // This loop prints "1, 3, 5, "
1069 /// while ptr != end_rounded_up {
1071 /// print!("{}, ", *ptr);
1073 /// ptr = ptr.wrapping_add(step);
1076 #[stable(feature = "pointer_methods", since = "1.26.0")]
1077 #[must_use = "returns a new pointer rather than modifying its argument"]
1078 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1080 pub const fn wrapping_add(self, count: usize) -> Self
1084 self.wrapping_offset(count as isize)
1087 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1088 /// (convenience for `.wrapping_byte_offset(count as isize)`)
1090 /// `count` is in units of bytes.
1092 /// This is purely a convenience for casting to a `u8` pointer and
1093 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1095 /// For non-`Sized` pointees this operation changes only the data pointer,
1096 /// leaving the metadata untouched.
1099 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1100 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1101 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1102 self.cast::<u8>().wrapping_add(count).with_metadata_of(self)
1105 /// Calculates the offset from a pointer using wrapping arithmetic.
1106 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1108 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1109 /// offset of `3 * size_of::<T>()` bytes.
1113 /// This operation itself is always safe, but using the resulting pointer is not.
1115 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1116 /// be used to read or write other allocated objects.
1118 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1119 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1120 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1121 /// `x` and `y` point into the same allocated object.
1123 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1124 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
1125 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1126 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1127 /// can be optimized better and is thus preferable in performance-sensitive code.
1129 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1130 /// intermediate values used during the computation of the final result. For example,
1131 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1132 /// allocated object and then re-entering it later is permitted.
1134 /// [`sub`]: #method.sub
1135 /// [allocated object]: crate::ptr#allocated-object
1142 /// // Iterate using a raw pointer in increments of two elements (backwards)
1143 /// let data = [1u8, 2, 3, 4, 5];
1144 /// let mut ptr: *const u8 = data.as_ptr();
1145 /// let start_rounded_down = ptr.wrapping_sub(2);
1146 /// ptr = ptr.wrapping_add(4);
1148 /// // This loop prints "5, 3, 1, "
1149 /// while ptr != start_rounded_down {
1151 /// print!("{}, ", *ptr);
1153 /// ptr = ptr.wrapping_sub(step);
1156 #[stable(feature = "pointer_methods", since = "1.26.0")]
1157 #[must_use = "returns a new pointer rather than modifying its argument"]
1158 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1160 pub const fn wrapping_sub(self, count: usize) -> Self
1164 self.wrapping_offset((count as isize).wrapping_neg())
1167 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1168 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1170 /// `count` is in units of bytes.
1172 /// This is purely a convenience for casting to a `u8` pointer and
1173 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1175 /// For non-`Sized` pointees this operation changes only the data pointer,
1176 /// leaving the metadata untouched.
1179 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1180 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1181 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1182 self.cast::<u8>().wrapping_sub(count).with_metadata_of(self)
1185 /// Reads the value from `self` without moving it. This leaves the
1186 /// memory in `self` unchanged.
1188 /// See [`ptr::read`] for safety concerns and examples.
1190 /// [`ptr::read`]: crate::ptr::read()
1191 #[stable(feature = "pointer_methods", since = "1.26.0")]
1192 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1194 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1195 pub const unsafe fn read(self) -> T
1199 // SAFETY: the caller must uphold the safety contract for `read`.
1200 unsafe { read(self) }
1203 /// Performs a volatile read of the value from `self` without moving it. This
1204 /// leaves the memory in `self` unchanged.
1206 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1207 /// to not be elided or reordered by the compiler across other volatile
1210 /// See [`ptr::read_volatile`] for safety concerns and examples.
1212 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1213 #[stable(feature = "pointer_methods", since = "1.26.0")]
1215 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1216 pub unsafe fn read_volatile(self) -> T
1220 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1221 unsafe { read_volatile(self) }
1224 /// Reads the value from `self` without moving it. This leaves the
1225 /// memory in `self` unchanged.
1227 /// Unlike `read`, the pointer may be unaligned.
1229 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1231 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1232 #[stable(feature = "pointer_methods", since = "1.26.0")]
1233 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1235 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1236 pub const unsafe fn read_unaligned(self) -> T
1240 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1241 unsafe { read_unaligned(self) }
1244 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1245 /// and destination may overlap.
1247 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1249 /// See [`ptr::copy`] for safety concerns and examples.
1251 /// [`ptr::copy`]: crate::ptr::copy()
1252 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1253 #[stable(feature = "pointer_methods", since = "1.26.0")]
1255 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1256 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1260 // SAFETY: the caller must uphold the safety contract for `copy`.
1261 unsafe { copy(self, dest, count) }
1264 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1265 /// and destination may *not* overlap.
1267 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1269 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1271 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1272 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1273 #[stable(feature = "pointer_methods", since = "1.26.0")]
1275 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1276 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1280 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1281 unsafe { copy_nonoverlapping(self, dest, count) }
1284 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1287 /// If it is not possible to align the pointer, the implementation returns
1288 /// `usize::MAX`. It is permissible for the implementation to *always*
1289 /// return `usize::MAX`. Only your algorithm's performance can depend
1290 /// on getting a usable offset here, not its correctness.
1292 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1293 /// used with the `wrapping_add` method.
1295 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1296 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1297 /// the returned offset is correct in all terms other than alignment.
1301 /// The function panics if `align` is not a power-of-two.
1305 /// Accessing adjacent `u8` as `u16`
1308 /// use std::mem::align_of;
1311 /// let x = [5_u8, 6, 7, 8, 9];
1312 /// let ptr = x.as_ptr();
1313 /// let offset = ptr.align_offset(align_of::<u16>());
1315 /// if offset < x.len() - 1 {
1316 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1317 /// assert!(*u16_ptr == u16::from_ne_bytes([5, 6]) || *u16_ptr == u16::from_ne_bytes([6, 7]));
1319 /// // while the pointer can be aligned via `offset`, it would point
1320 /// // outside the allocation
1326 #[stable(feature = "align_offset", since = "1.36.0")]
1327 #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1328 pub const fn align_offset(self, align: usize) -> usize
1332 if !align.is_power_of_two() {
1333 panic!("align_offset: align is not a power-of-two");
1338 fn rt_impl<T>(p: *const T, align: usize) -> usize {
1339 // SAFETY: `align` has been checked to be a power of 2 above
1340 unsafe { align_offset(p, align) }
1343 const fn ctfe_impl<T>(_: *const T, _: usize) -> usize {
1348 // It is permissible for `align_offset` to always return `usize::MAX`,
1349 // algorithm correctness can not depend on `align_offset` returning non-max values.
1351 // As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
1352 unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
1355 #[cfg(not(bootstrap))]
1357 // SAFETY: `align` has been checked to be a power of 2 above
1358 unsafe { align_offset(self, align) }
1362 /// Returns whether the pointer is properly aligned for `T`.
1368 /// #![feature(pointer_is_aligned)]
1369 /// #![feature(pointer_byte_offsets)]
1371 /// // On some platforms, the alignment of i32 is less than 4.
1372 /// #[repr(align(4))]
1373 /// struct AlignedI32(i32);
1375 /// let data = AlignedI32(42);
1376 /// let ptr = &data as *const AlignedI32;
1378 /// assert!(ptr.is_aligned());
1379 /// assert!(!ptr.wrapping_byte_add(1).is_aligned());
1382 /// # At compiletime
1383 /// **Note: Alignment at compiletime is experimental and subject to change. See the
1384 /// [tracking issue] for details.**
1386 /// At compiletime, the compiler may not know where a value will end up in memory.
1387 /// Calling this function on a pointer created from a reference at compiletime will only
1388 /// return `true` if the pointer is guaranteed to be aligned. This means that the pointer
1389 /// is never aligned if cast to a type with a stricter alignment than the reference's
1390 /// underlying allocation.
1392 #[cfg_attr(bootstrap, doc = "```ignore")]
1393 #[cfg_attr(not(bootstrap), doc = "```")]
1394 /// #![feature(pointer_is_aligned)]
1395 /// #![feature(const_pointer_is_aligned)]
1397 /// // On some platforms, the alignment of primitives is less than their size.
1398 /// #[repr(align(4))]
1399 /// struct AlignedI32(i32);
1400 /// #[repr(align(8))]
1401 /// struct AlignedI64(i64);
1404 /// let data = AlignedI32(42);
1405 /// let ptr = &data as *const AlignedI32;
1406 /// assert!(ptr.is_aligned());
1408 /// // At runtime either `ptr1` or `ptr2` would be aligned, but at compiletime neither is aligned.
1409 /// let ptr1 = ptr.cast::<AlignedI64>();
1410 /// let ptr2 = ptr.wrapping_add(1).cast::<AlignedI64>();
1411 /// assert!(!ptr1.is_aligned());
1412 /// assert!(!ptr2.is_aligned());
1416 /// Due to this behavior, it is possible that a runtime pointer derived from a compiletime
1417 /// pointer is aligned, even if the compiletime pointer wasn't aligned.
1419 #[cfg_attr(bootstrap, doc = "```ignore")]
1420 #[cfg_attr(not(bootstrap), doc = "```")]
1421 /// #![feature(pointer_is_aligned)]
1422 /// #![feature(const_pointer_is_aligned)]
1424 /// // On some platforms, the alignment of primitives is less than their size.
1425 /// #[repr(align(4))]
1426 /// struct AlignedI32(i32);
1427 /// #[repr(align(8))]
1428 /// struct AlignedI64(i64);
1430 /// // At compiletime, neither `COMPTIME_PTR` nor `COMPTIME_PTR + 1` is aligned.
1431 /// const COMPTIME_PTR: *const AlignedI32 = &AlignedI32(42);
1432 /// const _: () = assert!(!COMPTIME_PTR.cast::<AlignedI64>().is_aligned());
1433 /// const _: () = assert!(!COMPTIME_PTR.wrapping_add(1).cast::<AlignedI64>().is_aligned());
1435 /// // At runtime, either `runtime_ptr` or `runtime_ptr + 1` is aligned.
1436 /// let runtime_ptr = COMPTIME_PTR;
1438 /// runtime_ptr.cast::<AlignedI64>().is_aligned(),
1439 /// runtime_ptr.wrapping_add(1).cast::<AlignedI64>().is_aligned(),
1443 /// If a pointer is created from a fixed address, this function behaves the same during
1444 /// runtime and compiletime.
1446 #[cfg_attr(bootstrap, doc = "```ignore")]
1447 #[cfg_attr(not(bootstrap), doc = "```")]
1448 /// #![feature(pointer_is_aligned)]
1449 /// #![feature(const_pointer_is_aligned)]
1451 /// // On some platforms, the alignment of primitives is less than their size.
1452 /// #[repr(align(4))]
1453 /// struct AlignedI32(i32);
1454 /// #[repr(align(8))]
1455 /// struct AlignedI64(i64);
1458 /// let ptr = 40 as *const AlignedI32;
1459 /// assert!(ptr.is_aligned());
1461 /// // For pointers with a known address, runtime and compiletime behavior are identical.
1462 /// let ptr1 = ptr.cast::<AlignedI64>();
1463 /// let ptr2 = ptr.wrapping_add(1).cast::<AlignedI64>();
1464 /// assert!(ptr1.is_aligned());
1465 /// assert!(!ptr2.is_aligned());
1469 /// [tracking issue]: https://github.com/rust-lang/rust/issues/104203
1472 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1473 #[rustc_const_unstable(feature = "const_pointer_is_aligned", issue = "104203")]
1474 pub const fn is_aligned(self) -> bool
1478 self.is_aligned_to(mem::align_of::<T>())
1481 /// Returns whether the pointer is aligned to `align`.
1483 /// For non-`Sized` pointees this operation considers only the data pointer,
1484 /// ignoring the metadata.
1488 /// The function panics if `align` is not a power-of-two (this includes 0).
1494 /// #![feature(pointer_is_aligned)]
1495 /// #![feature(pointer_byte_offsets)]
1497 /// // On some platforms, the alignment of i32 is less than 4.
1498 /// #[repr(align(4))]
1499 /// struct AlignedI32(i32);
1501 /// let data = AlignedI32(42);
1502 /// let ptr = &data as *const AlignedI32;
1504 /// assert!(ptr.is_aligned_to(1));
1505 /// assert!(ptr.is_aligned_to(2));
1506 /// assert!(ptr.is_aligned_to(4));
1508 /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1509 /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1511 /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1514 /// # At compiletime
1515 /// **Note: Alignment at compiletime is experimental and subject to change. See the
1516 /// [tracking issue] for details.**
1518 /// At compiletime, the compiler may not know where a value will end up in memory.
1519 /// Calling this function on a pointer created from a reference at compiletime will only
1520 /// return `true` if the pointer is guaranteed to be aligned. This means that the pointer
1521 /// cannot be stricter aligned than the reference's underlying allocation.
1523 #[cfg_attr(bootstrap, doc = "```ignore")]
1524 #[cfg_attr(not(bootstrap), doc = "```")]
1525 /// #![feature(pointer_is_aligned)]
1526 /// #![feature(const_pointer_is_aligned)]
1528 /// // On some platforms, the alignment of i32 is less than 4.
1529 /// #[repr(align(4))]
1530 /// struct AlignedI32(i32);
1533 /// let data = AlignedI32(42);
1534 /// let ptr = &data as *const AlignedI32;
1536 /// assert!(ptr.is_aligned_to(1));
1537 /// assert!(ptr.is_aligned_to(2));
1538 /// assert!(ptr.is_aligned_to(4));
1540 /// // At compiletime, we know for sure that the pointer isn't aligned to 8.
1541 /// assert!(!ptr.is_aligned_to(8));
1542 /// assert!(!ptr.wrapping_add(1).is_aligned_to(8));
1546 /// Due to this behavior, it is possible that a runtime pointer derived from a compiletime
1547 /// pointer is aligned, even if the compiletime pointer wasn't aligned.
1549 #[cfg_attr(bootstrap, doc = "```ignore")]
1550 #[cfg_attr(not(bootstrap), doc = "```")]
1551 /// #![feature(pointer_is_aligned)]
1552 /// #![feature(const_pointer_is_aligned)]
1554 /// // On some platforms, the alignment of i32 is less than 4.
1555 /// #[repr(align(4))]
1556 /// struct AlignedI32(i32);
1558 /// // At compiletime, neither `COMPTIME_PTR` nor `COMPTIME_PTR + 1` is aligned.
1559 /// const COMPTIME_PTR: *const AlignedI32 = &AlignedI32(42);
1560 /// const _: () = assert!(!COMPTIME_PTR.is_aligned_to(8));
1561 /// const _: () = assert!(!COMPTIME_PTR.wrapping_add(1).is_aligned_to(8));
1563 /// // At runtime, either `runtime_ptr` or `runtime_ptr + 1` is aligned.
1564 /// let runtime_ptr = COMPTIME_PTR;
1566 /// runtime_ptr.is_aligned_to(8),
1567 /// runtime_ptr.wrapping_add(1).is_aligned_to(8),
1571 /// If a pointer is created from a fixed address, this function behaves the same during
1572 /// runtime and compiletime.
1574 #[cfg_attr(bootstrap, doc = "```ignore")]
1575 #[cfg_attr(not(bootstrap), doc = "```")]
1576 /// #![feature(pointer_is_aligned)]
1577 /// #![feature(const_pointer_is_aligned)]
1580 /// let ptr = 40 as *const u8;
1581 /// assert!(ptr.is_aligned_to(1));
1582 /// assert!(ptr.is_aligned_to(2));
1583 /// assert!(ptr.is_aligned_to(4));
1584 /// assert!(ptr.is_aligned_to(8));
1585 /// assert!(!ptr.is_aligned_to(16));
1589 /// [tracking issue]: https://github.com/rust-lang/rust/issues/104203
1592 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1593 #[rustc_const_unstable(feature = "const_pointer_is_aligned", issue = "104203")]
1594 pub const fn is_aligned_to(self, align: usize) -> bool {
1595 if !align.is_power_of_two() {
1596 panic!("is_aligned_to: align is not a power-of-two");
1599 // We can't use the address of `self` in a `const fn`, so we use `align_offset` instead.
1600 // The cast to `()` is used to
1601 // 1. deal with fat pointers; and
1602 // 2. ensure that `align_offset` doesn't actually try to compute an offset.
1603 self.cast::<()>().align_offset(align) == 0
1607 impl<T> *const [T] {
1608 /// Returns the length of a raw slice.
1610 /// The returned value is the number of **elements**, not the number of bytes.
1612 /// This function is safe, even when the raw slice cannot be cast to a slice
1613 /// reference because the pointer is null or unaligned.
1618 /// #![feature(slice_ptr_len)]
1622 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1623 /// assert_eq!(slice.len(), 3);
1626 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1627 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1628 pub const fn len(self) -> usize {
1632 /// Returns a raw pointer to the slice's buffer.
1634 /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1639 /// #![feature(slice_ptr_get)]
1642 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1643 /// assert_eq!(slice.as_ptr(), ptr::null());
1646 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1647 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
1648 pub const fn as_ptr(self) -> *const T {
1652 /// Returns a raw pointer to an element or subslice, without doing bounds
1655 /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
1656 /// is *[undefined behavior]* even if the resulting pointer is not used.
1658 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1663 /// #![feature(slice_ptr_get)]
1665 /// let x = &[1, 2, 4] as *const [i32];
1668 /// assert_eq!(x.get_unchecked(1), x.as_ptr().add(1));
1671 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1672 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
1674 pub const unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output
1676 I: ~const SliceIndex<[T]>,
1678 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1679 unsafe { index.get_unchecked(self) }
1682 /// Returns `None` if the pointer is null, or else returns a shared slice to
1683 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1684 /// that the value has to be initialized.
1686 /// [`as_ref`]: #method.as_ref
1690 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1691 /// all of the following is true:
1693 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1694 /// and it must be properly aligned. This means in particular:
1696 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1697 /// Slices can never span across multiple allocated objects.
1699 /// * The pointer must be aligned even for zero-length slices. One
1700 /// reason for this is that enum layout optimizations may rely on references
1701 /// (including slices of any length) being aligned and non-null to distinguish
1702 /// them from other data. You can obtain a pointer that is usable as `data`
1703 /// for zero-length slices using [`NonNull::dangling()`].
1705 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1706 /// See the safety documentation of [`pointer::offset`].
1708 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1709 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1710 /// In particular, while this reference exists, the memory the pointer points to must
1711 /// not get mutated (except inside `UnsafeCell`).
1713 /// This applies even if the result of this method is unused!
1715 /// See also [`slice::from_raw_parts`][].
1717 /// [valid]: crate::ptr#safety
1718 /// [allocated object]: crate::ptr#allocated-object
1720 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1721 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1722 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1726 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1727 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1732 // Equality for pointers
1733 #[stable(feature = "rust1", since = "1.0.0")]
1734 impl<T: ?Sized> PartialEq for *const T {
1736 fn eq(&self, other: &*const T) -> bool {
1741 #[stable(feature = "rust1", since = "1.0.0")]
1742 impl<T: ?Sized> Eq for *const T {}
1744 // Comparison for pointers
1745 #[stable(feature = "rust1", since = "1.0.0")]
1746 impl<T: ?Sized> Ord for *const T {
1748 fn cmp(&self, other: &*const T) -> Ordering {
1751 } else if self == other {
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 impl<T: ?Sized> PartialOrd for *const T {
1762 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
1763 Some(self.cmp(other))
1767 fn lt(&self, other: &*const T) -> bool {
1772 fn le(&self, other: &*const T) -> bool {
1777 fn gt(&self, other: &*const T) -> bool {
1782 fn ge(&self, other: &*const T) -> bool {