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 #[must_use = "returns a new pointer rather than modifying its argument"]
84 pub fn with_metadata_of<U>(self, mut val: *const U) -> *const U
88 let target = &mut val as *mut *const U as *mut *const u8;
89 // SAFETY: In case of a thin pointer, this operations is identical
90 // to a simple assignment. In case of a fat pointer, with the current
91 // fat pointer layout implementation, the first field of such a
92 // pointer is always the data pointer, which is likewise assigned.
93 unsafe { *target = self as *const u8 };
97 /// Changes constness without changing the type.
99 /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
101 #[stable(feature = "ptr_const_cast", since = "CURRENT_RUSTC_VERSION")]
102 #[rustc_const_stable(feature = "ptr_const_cast", since = "CURRENT_RUSTC_VERSION")]
103 pub const fn cast_mut(self) -> *mut T {
107 /// Casts a pointer to its raw bits.
109 /// This is equivalent to `as usize`, but is more specific to enhance readability.
110 /// The inverse method is [`from_bits`](#method.from_bits).
112 /// In particular, `*p as usize` and `p as usize` will both compile for
113 /// pointers to numeric types but do very different things, so using this
114 /// helps emphasize that reading the bits was intentional.
119 /// #![feature(ptr_to_from_bits)]
120 /// let array = [13, 42];
121 /// let p0: *const i32 = &array[0];
122 /// assert_eq!(<*const _>::from_bits(p0.to_bits()), p0);
123 /// let p1: *const i32 = &array[1];
124 /// assert_eq!(p1.to_bits() - p0.to_bits(), 4);
126 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
127 pub fn to_bits(self) -> usize
134 /// Creates a pointer from its raw bits.
136 /// This is equivalent to `as *const T`, but is more specific to enhance readability.
137 /// The inverse method is [`to_bits`](#method.to_bits).
142 /// #![feature(ptr_to_from_bits)]
143 /// use std::ptr::NonNull;
144 /// let dangling: *const u8 = NonNull::dangling().as_ptr();
145 /// assert_eq!(<*const u8>::from_bits(1), dangling);
147 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
148 pub fn from_bits(bits: usize) -> Self
155 /// Gets the "address" portion of the pointer.
157 /// This is similar to `self as usize`, which semantically discards *provenance* and
158 /// *address-space* information. However, unlike `self as usize`, casting the returned address
159 /// back to a pointer yields [`invalid`][], which is undefined behavior to dereference. To
160 /// properly restore the lost information and obtain a dereferenceable pointer, use
161 /// [`with_addr`][pointer::with_addr] or [`map_addr`][pointer::map_addr].
163 /// If using those APIs is not possible because there is no way to preserve a pointer with the
164 /// required provenance, use [`expose_addr`][pointer::expose_addr] and
165 /// [`from_exposed_addr`][from_exposed_addr] instead. However, note that this makes
166 /// your code less portable and less amenable to tools that check for compliance with the Rust
169 /// On most platforms this will produce a value with the same bytes as the original
170 /// pointer, because all the bytes are dedicated to describing the address.
171 /// Platforms which need to store additional information in the pointer may
172 /// perform a change of representation to produce a value containing only the address
173 /// portion of the pointer. What that means is up to the platform to define.
175 /// This API and its claimed semantics are part of the Strict Provenance experiment, and as such
176 /// might change in the future (including possibly weakening this so it becomes wholly
177 /// equivalent to `self as usize`). See the [module documentation][crate::ptr] for details.
180 #[unstable(feature = "strict_provenance", issue = "95228")]
181 pub fn addr(self) -> usize
185 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
186 // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
188 unsafe { mem::transmute(self) }
191 /// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future
192 /// use in [`from_exposed_addr`][].
194 /// This is equivalent to `self as usize`, which semantically discards *provenance* and
195 /// *address-space* information. Furthermore, this (like the `as` cast) has the implicit
196 /// side-effect of marking the provenance as 'exposed', so on platforms that support it you can
197 /// later call [`from_exposed_addr`][] to reconstitute the original pointer including its
198 /// provenance. (Reconstructing address space information, if required, is your responsibility.)
200 /// Using this method means that code is *not* following Strict Provenance rules. Supporting
201 /// [`from_exposed_addr`][] complicates specification and reasoning and may not be supported by
202 /// tools that help you to stay conformant with the Rust memory model, so it is recommended to
203 /// use [`addr`][pointer::addr] wherever possible.
205 /// On most platforms this will produce a value with the same bytes as the original pointer,
206 /// because all the bytes are dedicated to describing the address. Platforms which need to store
207 /// additional information in the pointer may not support this operation, since the 'expose'
208 /// side-effect which is required for [`from_exposed_addr`][] to work is typically not
211 /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
212 /// [module documentation][crate::ptr] for details.
214 /// [`from_exposed_addr`]: from_exposed_addr
217 #[unstable(feature = "strict_provenance", issue = "95228")]
218 pub fn expose_addr(self) -> usize
222 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
226 /// Creates a new pointer with the given address.
228 /// This performs the same operation as an `addr as ptr` cast, but copies
229 /// the *address-space* and *provenance* of `self` to the new pointer.
230 /// This allows us to dynamically preserve and propagate this important
231 /// information in a way that is otherwise impossible with a unary cast.
233 /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
234 /// `self` to the given address, and therefore has all the same capabilities and restrictions.
236 /// This API and its claimed semantics are part of the Strict Provenance experiment,
237 /// see the [module documentation][crate::ptr] for details.
240 #[unstable(feature = "strict_provenance", issue = "95228")]
241 pub fn with_addr(self, addr: usize) -> Self
245 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
247 // In the mean-time, this operation is defined to be "as if" it was
248 // a wrapping_offset, so we can emulate it as such. This should properly
249 // restore pointer provenance even under today's compiler.
250 let self_addr = self.addr() as isize;
251 let dest_addr = addr as isize;
252 let offset = dest_addr.wrapping_sub(self_addr);
254 // This is the canonical desugarring of this operation
255 self.wrapping_byte_offset(offset)
258 /// Creates a new pointer by mapping `self`'s address to a new one.
260 /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
262 /// This API and its claimed semantics are part of the Strict Provenance experiment,
263 /// see the [module documentation][crate::ptr] for details.
266 #[unstable(feature = "strict_provenance", issue = "95228")]
267 pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self
271 self.with_addr(f(self.addr()))
274 /// Decompose a (possibly wide) pointer into its address and metadata components.
276 /// The pointer can be later reconstructed with [`from_raw_parts`].
277 #[unstable(feature = "ptr_metadata", issue = "81513")]
278 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
280 pub const fn to_raw_parts(self) -> (*const (), <T as super::Pointee>::Metadata) {
281 (self.cast(), metadata(self))
284 /// Returns `None` if the pointer is null, or else returns a shared reference to
285 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
286 /// must be used instead.
288 /// [`as_uninit_ref`]: #method.as_uninit_ref
292 /// When calling this method, you have to ensure that *either* the pointer is null *or*
293 /// all of the following is true:
295 /// * The pointer must be properly aligned.
297 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
299 /// * The pointer must point to an initialized instance of `T`.
301 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
302 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
303 /// In particular, while this reference exists, the memory the pointer points to must
304 /// not get mutated (except inside `UnsafeCell`).
306 /// This applies even if the result of this method is unused!
307 /// (The part about being initialized is not yet fully decided, but until
308 /// it is, the only safe approach is to ensure that they are indeed initialized.)
310 /// [the module documentation]: crate::ptr#safety
317 /// let ptr: *const u8 = &10u8 as *const u8;
320 /// if let Some(val_back) = ptr.as_ref() {
321 /// println!("We got back the value: {val_back}!");
326 /// # Null-unchecked version
328 /// If you are sure the pointer can never be null and are looking for some kind of
329 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
330 /// dereference the pointer directly.
333 /// let ptr: *const u8 = &10u8 as *const u8;
336 /// let val_back = &*ptr;
337 /// println!("We got back the value: {val_back}!");
340 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
341 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
343 pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
344 // SAFETY: the caller must guarantee that `self` is valid
345 // for a reference if it isn't null.
346 if self.is_null() { None } else { unsafe { Some(&*self) } }
349 /// Returns `None` if the pointer is null, or else returns a shared reference to
350 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
351 /// that the value has to be initialized.
353 /// [`as_ref`]: #method.as_ref
357 /// When calling this method, you have to ensure that *either* the pointer is null *or*
358 /// all of the following is true:
360 /// * The pointer must be properly aligned.
362 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
364 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
365 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
366 /// In particular, while this reference exists, the memory the pointer points to must
367 /// not get mutated (except inside `UnsafeCell`).
369 /// This applies even if the result of this method is unused!
371 /// [the module documentation]: crate::ptr#safety
378 /// #![feature(ptr_as_uninit)]
380 /// let ptr: *const u8 = &10u8 as *const u8;
383 /// if let Some(val_back) = ptr.as_uninit_ref() {
384 /// println!("We got back the value: {}!", val_back.assume_init());
389 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
390 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
391 pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
395 // SAFETY: the caller must guarantee that `self` meets all the
396 // requirements for a reference.
397 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
400 /// Calculates the offset from a pointer.
402 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
403 /// offset of `3 * size_of::<T>()` bytes.
407 /// If any of the following conditions are violated, the result is Undefined
410 /// * Both the starting and resulting pointer must be either in bounds or one
411 /// byte past the end of the same [allocated object].
413 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
415 /// * The offset being in bounds cannot rely on "wrapping around" the address
416 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
418 /// The compiler and standard library generally tries to ensure allocations
419 /// never reach a size where an offset is a concern. For instance, `Vec`
420 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
421 /// `vec.as_ptr().add(vec.len())` is always safe.
423 /// Most platforms fundamentally can't even construct such an allocation.
424 /// For instance, no known 64-bit platform can ever serve a request
425 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
426 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
427 /// more than `isize::MAX` bytes with things like Physical Address
428 /// Extension. As such, memory acquired directly from allocators or memory
429 /// mapped files *may* be too large to handle with this function.
431 /// Consider using [`wrapping_offset`] instead if these constraints are
432 /// difficult to satisfy. The only advantage of this method is that it
433 /// enables more aggressive compiler optimizations.
435 /// [`wrapping_offset`]: #method.wrapping_offset
436 /// [allocated object]: crate::ptr#allocated-object
443 /// let s: &str = "123";
444 /// let ptr: *const u8 = s.as_ptr();
447 /// println!("{}", *ptr.offset(1) as char);
448 /// println!("{}", *ptr.offset(2) as char);
451 #[stable(feature = "rust1", since = "1.0.0")]
452 #[must_use = "returns a new pointer rather than modifying its argument"]
453 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
455 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
456 pub const unsafe fn offset(self, count: isize) -> *const T
460 // SAFETY: the caller must uphold the safety contract for `offset`.
461 unsafe { intrinsics::offset(self, count) }
464 /// Calculates the offset from a pointer in bytes.
466 /// `count` is in units of **bytes**.
468 /// This is purely a convenience for casting to a `u8` pointer and
469 /// using [offset][pointer::offset] on it. See that method for documentation
470 /// and safety requirements.
472 /// For non-`Sized` pointees this operation changes only the data pointer,
473 /// leaving the metadata untouched.
476 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
477 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
478 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
479 pub const unsafe fn byte_offset(self, count: isize) -> Self {
480 // SAFETY: the caller must uphold the safety contract for `offset`.
481 let this = unsafe { self.cast::<u8>().offset(count).cast::<()>() };
482 from_raw_parts::<T>(this, metadata(self))
485 /// Calculates the offset from a pointer using wrapping arithmetic.
487 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
488 /// offset of `3 * size_of::<T>()` bytes.
492 /// This operation itself is always safe, but using the resulting pointer is not.
494 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
495 /// be used to read or write other allocated objects.
497 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
498 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
499 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
500 /// `x` and `y` point into the same allocated object.
502 /// Compared to [`offset`], this method basically delays the requirement of staying within the
503 /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
504 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
505 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
506 /// can be optimized better and is thus preferable in performance-sensitive code.
508 /// The delayed check only considers the value of the pointer that was dereferenced, not the
509 /// intermediate values used during the computation of the final result. For example,
510 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
511 /// words, leaving the allocated object and then re-entering it later is permitted.
513 /// [`offset`]: #method.offset
514 /// [allocated object]: crate::ptr#allocated-object
521 /// // Iterate using a raw pointer in increments of two elements
522 /// let data = [1u8, 2, 3, 4, 5];
523 /// let mut ptr: *const u8 = data.as_ptr();
525 /// let end_rounded_up = ptr.wrapping_offset(6);
527 /// // This loop prints "1, 3, 5, "
528 /// while ptr != end_rounded_up {
530 /// print!("{}, ", *ptr);
532 /// ptr = ptr.wrapping_offset(step);
535 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
536 #[must_use = "returns a new pointer rather than modifying its argument"]
537 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
539 pub const fn wrapping_offset(self, count: isize) -> *const T
543 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
544 unsafe { intrinsics::arith_offset(self, count) }
547 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
549 /// `count` is in units of **bytes**.
551 /// This is purely a convenience for casting to a `u8` pointer and
552 /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
553 /// for documentation.
555 /// For non-`Sized` pointees this operation changes only the data pointer,
556 /// leaving the metadata untouched.
559 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
560 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
561 pub const fn wrapping_byte_offset(self, count: isize) -> Self {
562 from_raw_parts::<T>(self.cast::<u8>().wrapping_offset(count).cast::<()>(), metadata(self))
565 /// Masks out bits of the pointer according to a mask.
567 /// This is convenience for `ptr.map_addr(|a| a & mask)`.
569 /// For non-`Sized` pointees this operation changes only the data pointer,
570 /// leaving the metadata untouched.
571 #[cfg(not(bootstrap))]
572 #[unstable(feature = "ptr_mask", issue = "98290")]
573 #[must_use = "returns a new pointer rather than modifying its argument"]
575 pub fn mask(self, mask: usize) -> *const T {
576 let this = intrinsics::ptr_mask(self.cast::<()>(), mask);
577 from_raw_parts::<T>(this, metadata(self))
580 /// Calculates the distance between two pointers. The returned value is in
581 /// units of T: the distance in bytes divided by `mem::size_of::<T>()`.
583 /// This function is the inverse of [`offset`].
585 /// [`offset`]: #method.offset
589 /// If any of the following conditions are violated, the result is Undefined
592 /// * Both the starting and other pointer must be either in bounds or one
593 /// byte past the end of the same [allocated object].
595 /// * Both pointers must be *derived from* a pointer to the same object.
596 /// (See below for an example.)
598 /// * The distance between the pointers, in bytes, must be an exact multiple
599 /// of the size of `T`.
601 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
603 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
605 /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
606 /// address space, so two pointers within some value of any Rust type `T` will always satisfy
607 /// the last two conditions. The standard library also generally ensures that allocations
608 /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
609 /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
610 /// always satisfies the last two conditions.
612 /// Most platforms fundamentally can't even construct such a large allocation.
613 /// For instance, no known 64-bit platform can ever serve a request
614 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
615 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
616 /// more than `isize::MAX` bytes with things like Physical Address
617 /// Extension. As such, memory acquired directly from allocators or memory
618 /// mapped files *may* be too large to handle with this function.
619 /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
620 /// such large allocations either.)
622 /// [`add`]: #method.add
623 /// [allocated object]: crate::ptr#allocated-object
627 /// This function panics if `T` is a Zero-Sized Type ("ZST").
635 /// let ptr1: *const i32 = &a[1];
636 /// let ptr2: *const i32 = &a[3];
638 /// assert_eq!(ptr2.offset_from(ptr1), 2);
639 /// assert_eq!(ptr1.offset_from(ptr2), -2);
640 /// assert_eq!(ptr1.offset(2), ptr2);
641 /// assert_eq!(ptr2.offset(-2), ptr1);
645 /// *Incorrect* usage:
648 /// let ptr1 = Box::into_raw(Box::new(0u8)) as *const u8;
649 /// let ptr2 = Box::into_raw(Box::new(1u8)) as *const u8;
650 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
651 /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
652 /// let ptr2_other = (ptr1 as *const u8).wrapping_offset(diff);
653 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
654 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
655 /// // computing their offset is undefined behavior, even though
656 /// // they point to the same address!
658 /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
661 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
662 #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
664 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
665 pub const unsafe fn offset_from(self, origin: *const T) -> isize
669 let pointee_size = mem::size_of::<T>();
670 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
671 // SAFETY: the caller must uphold the safety contract for `ptr_offset_from`.
672 unsafe { intrinsics::ptr_offset_from(self, origin) }
675 /// Calculates the distance between two pointers. The returned value is in
676 /// units of **bytes**.
678 /// This is purely a convenience for casting to a `u8` pointer and
679 /// using [offset_from][pointer::offset_from] on it. See that method for
680 /// documentation and safety requirements.
682 /// For non-`Sized` pointees this operation considers only the data pointers,
683 /// ignoring the metadata.
685 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
686 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
687 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
688 pub const unsafe fn byte_offset_from(self, origin: *const T) -> isize {
689 // SAFETY: the caller must uphold the safety contract for `offset_from`.
690 unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
693 /// Calculates the distance between two pointers, *where it's known that
694 /// `self` is equal to or greater than `origin`*. The returned value is in
695 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
697 /// This computes the same value that [`offset_from`](#method.offset_from)
698 /// would compute, but with the added precondition that that the offset is
699 /// guaranteed to be non-negative. This method is equivalent to
700 /// `usize::from(self.offset_from(origin)).unwrap_unchecked()`,
701 /// but it provides slightly more information to the optimizer, which can
702 /// sometimes allow it to optimize slightly better with some backends.
704 /// This method can be though of as recovering the `count` that was passed
705 /// to [`add`](#method.add) (or, with the parameters in the other order,
706 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
707 /// that their safety preconditions are met:
709 /// # #![feature(ptr_sub_ptr)]
710 /// # unsafe fn blah(ptr: *const i32, origin: *const i32, count: usize) -> bool {
711 /// ptr.sub_ptr(origin) == count
713 /// origin.add(count) == ptr
715 /// ptr.sub(count) == origin
721 /// - The distance between the pointers must be non-negative (`self >= origin`)
723 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
724 /// apply to this method as well; see it for the full details.
726 /// Importantly, despite the return type of this method being able to represent
727 /// a larger offset, it's still *not permitted* to pass pointers which differ
728 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
729 /// always be less than or equal to `isize::MAX as usize`.
733 /// This function panics if `T` is a Zero-Sized Type ("ZST").
738 /// #![feature(ptr_sub_ptr)]
741 /// let ptr1: *const i32 = &a[1];
742 /// let ptr2: *const i32 = &a[3];
744 /// assert_eq!(ptr2.sub_ptr(ptr1), 2);
745 /// assert_eq!(ptr1.add(2), ptr2);
746 /// assert_eq!(ptr2.sub(2), ptr1);
747 /// assert_eq!(ptr2.sub_ptr(ptr2), 0);
750 /// // This would be incorrect, as the pointers are not correctly ordered:
751 /// // ptr1.sub_ptr(ptr2)
753 #[unstable(feature = "ptr_sub_ptr", issue = "95892")]
754 #[rustc_const_unstable(feature = "const_ptr_sub_ptr", issue = "95892")]
756 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
757 pub const unsafe fn sub_ptr(self, origin: *const T) -> usize
762 // SAFETY: The comparison has no side-effects, and the intrinsic
763 // does this check internally in the CTFE implementation.
765 assert_unsafe_precondition!([T](this: *const T, origin: *const T) => this >= origin)
768 let pointee_size = mem::size_of::<T>();
769 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
770 // SAFETY: the caller must uphold the safety contract for `ptr_offset_from_unsigned`.
771 unsafe { intrinsics::ptr_offset_from_unsigned(self, origin) }
774 /// Returns whether two pointers are guaranteed to be equal.
776 /// At runtime this function behaves like `Some(self == other)`.
777 /// However, in some contexts (e.g., compile-time evaluation),
778 /// it is not always possible to determine equality of two pointers, so this function may
779 /// spuriously return `None` for pointers that later actually turn out to have its equality known.
780 /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
782 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
783 /// version and unsafe code must not
784 /// rely on the result of this function for soundness. It is suggested to only use this function
785 /// for performance optimizations where spurious `None` return values by this function do not
786 /// affect the outcome, but just the performance.
787 /// The consequences of using this method to make runtime and compile-time code behave
788 /// differently have not been explored. This method should not be used to introduce such
789 /// differences, and it should also not be stabilized before we have a better understanding
791 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
792 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
794 pub const fn guaranteed_eq(self, other: *const T) -> Option<bool>
798 match intrinsics::ptr_guaranteed_cmp(self as _, other as _) {
800 other => Some(other == 1),
804 /// Returns whether two pointers are guaranteed to be inequal.
806 /// At runtime this function behaves like `Some(self == other)`.
807 /// However, in some contexts (e.g., compile-time evaluation),
808 /// it is not always possible to determine inequality of two pointers, so this function may
809 /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
810 /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
812 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
813 /// version and unsafe code must not
814 /// rely on the result of this function for soundness. It is suggested to only use this function
815 /// for performance optimizations where spurious `None` return values by this function do not
816 /// affect the outcome, but just the performance.
817 /// The consequences of using this method to make runtime and compile-time code behave
818 /// differently have not been explored. This method should not be used to introduce such
819 /// differences, and it should also not be stabilized before we have a better understanding
821 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
822 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
824 pub const fn guaranteed_ne(self, other: *const T) -> Option<bool>
828 match self.guaranteed_eq(other) {
830 Some(eq) => Some(!eq),
834 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
836 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
837 /// offset of `3 * size_of::<T>()` bytes.
841 /// If any of the following conditions are violated, the result is Undefined
844 /// * Both the starting and resulting pointer must be either in bounds or one
845 /// byte past the end of the same [allocated object].
847 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
849 /// * The offset being in bounds cannot rely on "wrapping around" the address
850 /// space. That is, the infinite-precision sum must fit in a `usize`.
852 /// The compiler and standard library generally tries to ensure allocations
853 /// never reach a size where an offset is a concern. For instance, `Vec`
854 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
855 /// `vec.as_ptr().add(vec.len())` is always safe.
857 /// Most platforms fundamentally can't even construct such an allocation.
858 /// For instance, no known 64-bit platform can ever serve a request
859 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
860 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
861 /// more than `isize::MAX` bytes with things like Physical Address
862 /// Extension. As such, memory acquired directly from allocators or memory
863 /// mapped files *may* be too large to handle with this function.
865 /// Consider using [`wrapping_add`] instead if these constraints are
866 /// difficult to satisfy. The only advantage of this method is that it
867 /// enables more aggressive compiler optimizations.
869 /// [`wrapping_add`]: #method.wrapping_add
870 /// [allocated object]: crate::ptr#allocated-object
877 /// let s: &str = "123";
878 /// let ptr: *const u8 = s.as_ptr();
881 /// println!("{}", *ptr.add(1) as char);
882 /// println!("{}", *ptr.add(2) as char);
885 #[stable(feature = "pointer_methods", since = "1.26.0")]
886 #[must_use = "returns a new pointer rather than modifying its argument"]
887 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
889 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
890 pub const unsafe fn add(self, count: usize) -> Self
894 // SAFETY: the caller must uphold the safety contract for `offset`.
895 unsafe { self.offset(count as isize) }
898 /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
900 /// `count` is in units of bytes.
902 /// This is purely a convenience for casting to a `u8` pointer and
903 /// using [add][pointer::add] on it. See that method for documentation
904 /// and safety requirements.
906 /// For non-`Sized` pointees this operation changes only the data pointer,
907 /// leaving the metadata untouched.
910 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
911 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
912 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
913 pub const unsafe fn byte_add(self, count: usize) -> Self {
914 // SAFETY: the caller must uphold the safety contract for `add`.
915 let this = unsafe { self.cast::<u8>().add(count).cast::<()>() };
916 from_raw_parts::<T>(this, metadata(self))
919 /// Calculates the offset from a pointer (convenience for
920 /// `.offset((count as isize).wrapping_neg())`).
922 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
923 /// offset of `3 * size_of::<T>()` bytes.
927 /// If any of the following conditions are violated, the result is Undefined
930 /// * Both the starting and resulting pointer must be either in bounds or one
931 /// byte past the end of the same [allocated object].
933 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
935 /// * The offset being in bounds cannot rely on "wrapping around" the address
936 /// space. That is, the infinite-precision sum must fit in a usize.
938 /// The compiler and standard library generally tries to ensure allocations
939 /// never reach a size where an offset is a concern. For instance, `Vec`
940 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
941 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
943 /// Most platforms fundamentally can't even construct such an allocation.
944 /// For instance, no known 64-bit platform can ever serve a request
945 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
946 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
947 /// more than `isize::MAX` bytes with things like Physical Address
948 /// Extension. As such, memory acquired directly from allocators or memory
949 /// mapped files *may* be too large to handle with this function.
951 /// Consider using [`wrapping_sub`] instead if these constraints are
952 /// difficult to satisfy. The only advantage of this method is that it
953 /// enables more aggressive compiler optimizations.
955 /// [`wrapping_sub`]: #method.wrapping_sub
956 /// [allocated object]: crate::ptr#allocated-object
963 /// let s: &str = "123";
966 /// let end: *const u8 = s.as_ptr().add(3);
967 /// println!("{}", *end.sub(1) as char);
968 /// println!("{}", *end.sub(2) as char);
971 #[stable(feature = "pointer_methods", since = "1.26.0")]
972 #[must_use = "returns a new pointer rather than modifying its argument"]
973 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
975 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
976 pub const unsafe fn sub(self, count: usize) -> Self
980 // SAFETY: the caller must uphold the safety contract for `offset`.
981 unsafe { self.offset((count as isize).wrapping_neg()) }
984 /// Calculates the offset from a pointer in bytes (convenience for
985 /// `.byte_offset((count as isize).wrapping_neg())`).
987 /// `count` is in units of bytes.
989 /// This is purely a convenience for casting to a `u8` pointer and
990 /// using [sub][pointer::sub] on it. See that method for documentation
991 /// and safety requirements.
993 /// For non-`Sized` pointees this operation changes only the data pointer,
994 /// leaving the metadata untouched.
997 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
998 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
999 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1000 pub const unsafe fn byte_sub(self, count: usize) -> Self {
1001 // SAFETY: the caller must uphold the safety contract for `sub`.
1002 let this = unsafe { self.cast::<u8>().sub(count).cast::<()>() };
1003 from_raw_parts::<T>(this, metadata(self))
1006 /// Calculates the offset from a pointer using wrapping arithmetic.
1007 /// (convenience for `.wrapping_offset(count as isize)`)
1009 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1010 /// offset of `3 * size_of::<T>()` bytes.
1014 /// This operation itself is always safe, but using the resulting pointer is not.
1016 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1017 /// be used to read or write other allocated objects.
1019 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1020 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1021 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1022 /// `x` and `y` point into the same allocated object.
1024 /// Compared to [`add`], this method basically delays the requirement of staying within the
1025 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
1026 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1027 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1028 /// can be optimized better and is thus preferable in performance-sensitive code.
1030 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1031 /// intermediate values used during the computation of the final result. For example,
1032 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1033 /// allocated object and then re-entering it later is permitted.
1035 /// [`add`]: #method.add
1036 /// [allocated object]: crate::ptr#allocated-object
1043 /// // Iterate using a raw pointer in increments of two elements
1044 /// let data = [1u8, 2, 3, 4, 5];
1045 /// let mut ptr: *const u8 = data.as_ptr();
1047 /// let end_rounded_up = ptr.wrapping_add(6);
1049 /// // This loop prints "1, 3, 5, "
1050 /// while ptr != end_rounded_up {
1052 /// print!("{}, ", *ptr);
1054 /// ptr = ptr.wrapping_add(step);
1057 #[stable(feature = "pointer_methods", since = "1.26.0")]
1058 #[must_use = "returns a new pointer rather than modifying its argument"]
1059 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1061 pub const fn wrapping_add(self, count: usize) -> Self
1065 self.wrapping_offset(count as isize)
1068 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1069 /// (convenience for `.wrapping_byte_offset(count as isize)`)
1071 /// `count` is in units of bytes.
1073 /// This is purely a convenience for casting to a `u8` pointer and
1074 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1076 /// For non-`Sized` pointees this operation changes only the data pointer,
1077 /// leaving the metadata untouched.
1080 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1081 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1082 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1083 from_raw_parts::<T>(self.cast::<u8>().wrapping_add(count).cast::<()>(), metadata(self))
1086 /// Calculates the offset from a pointer using wrapping arithmetic.
1087 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1089 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1090 /// offset of `3 * size_of::<T>()` bytes.
1094 /// This operation itself is always safe, but using the resulting pointer is not.
1096 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1097 /// be used to read or write other allocated objects.
1099 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1100 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1101 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1102 /// `x` and `y` point into the same allocated object.
1104 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1105 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
1106 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1107 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1108 /// can be optimized better and is thus preferable in performance-sensitive code.
1110 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1111 /// intermediate values used during the computation of the final result. For example,
1112 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1113 /// allocated object and then re-entering it later is permitted.
1115 /// [`sub`]: #method.sub
1116 /// [allocated object]: crate::ptr#allocated-object
1123 /// // Iterate using a raw pointer in increments of two elements (backwards)
1124 /// let data = [1u8, 2, 3, 4, 5];
1125 /// let mut ptr: *const u8 = data.as_ptr();
1126 /// let start_rounded_down = ptr.wrapping_sub(2);
1127 /// ptr = ptr.wrapping_add(4);
1129 /// // This loop prints "5, 3, 1, "
1130 /// while ptr != start_rounded_down {
1132 /// print!("{}, ", *ptr);
1134 /// ptr = ptr.wrapping_sub(step);
1137 #[stable(feature = "pointer_methods", since = "1.26.0")]
1138 #[must_use = "returns a new pointer rather than modifying its argument"]
1139 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1141 pub const fn wrapping_sub(self, count: usize) -> Self
1145 self.wrapping_offset((count as isize).wrapping_neg())
1148 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1149 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1151 /// `count` is in units of bytes.
1153 /// This is purely a convenience for casting to a `u8` pointer and
1154 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1156 /// For non-`Sized` pointees this operation changes only the data pointer,
1157 /// leaving the metadata untouched.
1160 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1161 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1162 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1163 from_raw_parts::<T>(self.cast::<u8>().wrapping_sub(count).cast::<()>(), metadata(self))
1166 /// Reads the value from `self` without moving it. This leaves the
1167 /// memory in `self` unchanged.
1169 /// See [`ptr::read`] for safety concerns and examples.
1171 /// [`ptr::read`]: crate::ptr::read()
1172 #[stable(feature = "pointer_methods", since = "1.26.0")]
1173 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1175 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1176 pub const unsafe fn read(self) -> T
1180 // SAFETY: the caller must uphold the safety contract for `read`.
1181 unsafe { read(self) }
1184 /// Performs a volatile read of the value from `self` without moving it. This
1185 /// leaves the memory in `self` unchanged.
1187 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1188 /// to not be elided or reordered by the compiler across other volatile
1191 /// See [`ptr::read_volatile`] for safety concerns and examples.
1193 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1194 #[stable(feature = "pointer_methods", since = "1.26.0")]
1196 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1197 pub unsafe fn read_volatile(self) -> T
1201 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1202 unsafe { read_volatile(self) }
1205 /// Reads the value from `self` without moving it. This leaves the
1206 /// memory in `self` unchanged.
1208 /// Unlike `read`, the pointer may be unaligned.
1210 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1212 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1213 #[stable(feature = "pointer_methods", since = "1.26.0")]
1214 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1216 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1217 pub const unsafe fn read_unaligned(self) -> T
1221 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1222 unsafe { read_unaligned(self) }
1225 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1226 /// and destination may overlap.
1228 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1230 /// See [`ptr::copy`] for safety concerns and examples.
1232 /// [`ptr::copy`]: crate::ptr::copy()
1233 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1234 #[stable(feature = "pointer_methods", since = "1.26.0")]
1236 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1237 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1241 // SAFETY: the caller must uphold the safety contract for `copy`.
1242 unsafe { copy(self, dest, count) }
1245 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1246 /// and destination may *not* overlap.
1248 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1250 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1252 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1253 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1254 #[stable(feature = "pointer_methods", since = "1.26.0")]
1256 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1257 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1261 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1262 unsafe { copy_nonoverlapping(self, dest, count) }
1265 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1268 /// If it is not possible to align the pointer, the implementation returns
1269 /// `usize::MAX`. It is permissible for the implementation to *always*
1270 /// return `usize::MAX`. Only your algorithm's performance can depend
1271 /// on getting a usable offset here, not its correctness.
1273 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1274 /// used with the `wrapping_add` method.
1276 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1277 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1278 /// the returned offset is correct in all terms other than alignment.
1282 /// The function panics if `align` is not a power-of-two.
1286 /// Accessing adjacent `u8` as `u16`
1289 /// use std::mem::align_of;
1292 /// let x = [5_u8, 6, 7, 8, 9];
1293 /// let ptr = x.as_ptr();
1294 /// let offset = ptr.align_offset(align_of::<u16>());
1296 /// if offset < x.len() - 1 {
1297 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1298 /// assert!(*u16_ptr == u16::from_ne_bytes([5, 6]) || *u16_ptr == u16::from_ne_bytes([6, 7]));
1300 /// // while the pointer can be aligned via `offset`, it would point
1301 /// // outside the allocation
1305 #[stable(feature = "align_offset", since = "1.36.0")]
1306 #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1307 pub const fn align_offset(self, align: usize) -> usize
1311 if !align.is_power_of_two() {
1312 panic!("align_offset: align is not a power-of-two");
1315 fn rt_impl<T>(p: *const T, align: usize) -> usize {
1316 // SAFETY: `align` has been checked to be a power of 2 above
1317 unsafe { align_offset(p, align) }
1320 const fn ctfe_impl<T>(_: *const T, _: usize) -> usize {
1325 // It is permissible for `align_offset` to always return `usize::MAX`,
1326 // algorithm correctness can not depend on `align_offset` returning non-max values.
1328 // As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
1329 unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
1332 /// Returns whether the pointer is properly aligned for `T`.
1335 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1336 pub fn is_aligned(self) -> bool
1340 self.is_aligned_to(core::mem::align_of::<T>())
1343 /// Returns whether the pointer is aligned to `align`.
1345 /// For non-`Sized` pointees this operation considers only the data pointer,
1346 /// ignoring the metadata.
1350 /// The function panics if `align` is not a power-of-two (this includes 0).
1353 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1354 pub fn is_aligned_to(self, align: usize) -> bool {
1355 if !align.is_power_of_two() {
1356 panic!("is_aligned_to: align is not a power-of-two");
1359 // Cast is needed for `T: !Sized`
1360 self.cast::<u8>().addr() & align - 1 == 0
1364 impl<T> *const [T] {
1365 /// Returns the length of a raw slice.
1367 /// The returned value is the number of **elements**, not the number of bytes.
1369 /// This function is safe, even when the raw slice cannot be cast to a slice
1370 /// reference because the pointer is null or unaligned.
1375 /// #![feature(slice_ptr_len)]
1379 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1380 /// assert_eq!(slice.len(), 3);
1383 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1384 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1385 pub const fn len(self) -> usize {
1389 /// Returns a raw pointer to the slice's buffer.
1391 /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1396 /// #![feature(slice_ptr_get)]
1399 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1400 /// assert_eq!(slice.as_ptr(), ptr::null());
1403 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1404 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
1405 pub const fn as_ptr(self) -> *const T {
1409 /// Returns a raw pointer to an element or subslice, without doing bounds
1412 /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
1413 /// is *[undefined behavior]* even if the resulting pointer is not used.
1415 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1420 /// #![feature(slice_ptr_get)]
1422 /// let x = &[1, 2, 4] as *const [i32];
1425 /// assert_eq!(x.get_unchecked(1), x.as_ptr().add(1));
1428 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1429 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
1431 pub const unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output
1433 I: ~const SliceIndex<[T]>,
1435 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1436 unsafe { index.get_unchecked(self) }
1439 /// Returns `None` if the pointer is null, or else returns a shared slice to
1440 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1441 /// that the value has to be initialized.
1443 /// [`as_ref`]: #method.as_ref
1447 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1448 /// all of the following is true:
1450 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1451 /// and it must be properly aligned. This means in particular:
1453 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1454 /// Slices can never span across multiple allocated objects.
1456 /// * The pointer must be aligned even for zero-length slices. One
1457 /// reason for this is that enum layout optimizations may rely on references
1458 /// (including slices of any length) being aligned and non-null to distinguish
1459 /// them from other data. You can obtain a pointer that is usable as `data`
1460 /// for zero-length slices using [`NonNull::dangling()`].
1462 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1463 /// See the safety documentation of [`pointer::offset`].
1465 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1466 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1467 /// In particular, while this reference exists, the memory the pointer points to must
1468 /// not get mutated (except inside `UnsafeCell`).
1470 /// This applies even if the result of this method is unused!
1472 /// See also [`slice::from_raw_parts`][].
1474 /// [valid]: crate::ptr#safety
1475 /// [allocated object]: crate::ptr#allocated-object
1477 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1478 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1479 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1483 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1484 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1489 // Equality for pointers
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 impl<T: ?Sized> PartialEq for *const T {
1493 fn eq(&self, other: &*const T) -> bool {
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl<T: ?Sized> Eq for *const T {}
1501 // Comparison for pointers
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 impl<T: ?Sized> Ord for *const T {
1505 fn cmp(&self, other: &*const T) -> Ordering {
1508 } else if self == other {
1516 #[stable(feature = "rust1", since = "1.0.0")]
1517 impl<T: ?Sized> PartialOrd for *const T {
1519 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
1520 Some(self.cmp(other))
1524 fn lt(&self, other: &*const T) -> bool {
1529 fn le(&self, other: &*const T) -> bool {
1534 fn gt(&self, other: &*const T) -> bool {
1539 fn ge(&self, other: &*const T) -> bool {