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 (self as *const u8).guaranteed_eq(null())
42 /// Casts to a pointer of another type.
43 #[stable(feature = "ptr_cast", since = "1.38.0")]
44 #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
46 pub const fn cast<U>(self) -> *const U {
50 /// Use the pointer value in a new pointer of another type.
52 /// In case `val` is a (fat) pointer to an unsized type, this operation
53 /// will ignore the pointer part, whereas for (thin) pointers to sized
54 /// types, this has the same effect as a simple cast.
56 /// The resulting pointer will have provenance of `self`, i.e., for a fat
57 /// pointer, this operation is semantically the same as creating a new
58 /// fat pointer with the data pointer value of `self` but the metadata of
63 /// This function is primarily useful for allowing byte-wise pointer
64 /// arithmetic on potentially fat pointers:
67 /// #![feature(set_ptr_value)]
68 /// # use core::fmt::Debug;
69 /// let arr: [i32; 3] = [1, 2, 3];
70 /// let mut ptr = arr.as_ptr() as *const dyn Debug;
71 /// let thin = ptr as *const u8;
73 /// ptr = thin.add(8).with_metadata_of(ptr);
74 /// # assert_eq!(*(ptr as *const i32), 3);
75 /// println!("{:?}", &*ptr); // will print "3"
78 #[unstable(feature = "set_ptr_value", issue = "75091")]
79 #[must_use = "returns a new pointer rather than modifying its argument"]
81 pub fn with_metadata_of<U>(self, mut val: *const U) -> *const U
85 let target = &mut val as *mut *const U as *mut *const u8;
86 // SAFETY: In case of a thin pointer, this operations is identical
87 // to a simple assignment. In case of a fat pointer, with the current
88 // fat pointer layout implementation, the first field of such a
89 // pointer is always the data pointer, which is likewise assigned.
90 unsafe { *target = self as *const u8 };
94 /// Changes constness without changing the type.
96 /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
98 #[unstable(feature = "ptr_const_cast", issue = "92675")]
99 #[rustc_const_unstable(feature = "ptr_const_cast", issue = "92675")]
100 pub const fn cast_mut(self) -> *mut T {
104 /// Casts a pointer to its raw bits.
106 /// This is equivalent to `as usize`, but is more specific to enhance readability.
107 /// The inverse method is [`from_bits`](#method.from_bits).
109 /// In particular, `*p as usize` and `p as usize` will both compile for
110 /// pointers to numeric types but do very different things, so using this
111 /// helps emphasize that reading the bits was intentional.
116 /// #![feature(ptr_to_from_bits)]
117 /// let array = [13, 42];
118 /// let p0: *const i32 = &array[0];
119 /// assert_eq!(<*const _>::from_bits(p0.to_bits()), p0);
120 /// let p1: *const i32 = &array[1];
121 /// assert_eq!(p1.to_bits() - p0.to_bits(), 4);
123 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
124 pub fn to_bits(self) -> usize
131 /// Creates a pointer from its raw bits.
133 /// This is equivalent to `as *const T`, but is more specific to enhance readability.
134 /// The inverse method is [`to_bits`](#method.to_bits).
139 /// #![feature(ptr_to_from_bits)]
140 /// use std::ptr::NonNull;
141 /// let dangling: *const u8 = NonNull::dangling().as_ptr();
142 /// assert_eq!(<*const u8>::from_bits(1), dangling);
144 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
145 pub fn from_bits(bits: usize) -> Self
152 /// Gets the "address" portion of the pointer.
154 /// This is similar to `self as usize`, which semantically discards *provenance* and
155 /// *address-space* information. However, unlike `self as usize`, casting the returned address
156 /// back to a pointer yields [`invalid`][], which is undefined behavior to dereference. To
157 /// properly restore the lost information and obtain a dereferencable pointer, use
158 /// [`with_addr`][pointer::with_addr] or [`map_addr`][pointer::map_addr].
160 /// If using those APIs is not possible because there is no way to preserve a pointer with the
161 /// required provenance, use [`expose_addr`][pointer::expose_addr] and
162 /// [`from_exposed_addr`][from_exposed_addr] instead. However, note that this makes
163 /// your code less portable and less amenable to tools that check for compliance with the Rust
166 /// On most platforms this will produce a value with the same bytes as the original
167 /// pointer, because all the bytes are dedicated to describing the address.
168 /// Platforms which need to store additional information in the pointer may
169 /// perform a change of representation to produce a value containing only the address
170 /// portion of the pointer. What that means is up to the platform to define.
172 /// This API and its claimed semantics are part of the Strict Provenance experiment, and as such
173 /// might change in the future (including possibly weakening this so it becomes wholly
174 /// equivalent to `self as usize`). See the [module documentation][crate::ptr] for details.
177 #[unstable(feature = "strict_provenance", issue = "95228")]
178 pub fn addr(self) -> usize
182 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
183 // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
185 unsafe { mem::transmute(self) }
188 /// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future
189 /// use in [`from_exposed_addr`][].
191 /// This is equivalent to `self as usize`, which semantically discards *provenance* and
192 /// *address-space* information. Furthermore, this (like the `as` cast) has the implicit
193 /// side-effect of marking the provenance as 'exposed', so on platforms that support it you can
194 /// later call [`from_exposed_addr`][] to reconstitute the original pointer including its
195 /// provenance. (Reconstructing address space information, if required, is your responsibility.)
197 /// Using this method means that code is *not* following Strict Provenance rules. Supporting
198 /// [`from_exposed_addr`][] complicates specification and reasoning and may not be supported by
199 /// tools that help you to stay conformant with the Rust memory model, so it is recommended to
200 /// use [`addr`][pointer::addr] wherever possible.
202 /// On most platforms this will produce a value with the same bytes as the original pointer,
203 /// because all the bytes are dedicated to describing the address. Platforms which need to store
204 /// additional information in the pointer may not support this operation, since the 'expose'
205 /// side-effect which is required for [`from_exposed_addr`][] to work is typically not
208 /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
209 /// [module documentation][crate::ptr] for details.
211 /// [`from_exposed_addr`]: from_exposed_addr
214 #[unstable(feature = "strict_provenance", issue = "95228")]
215 pub fn expose_addr(self) -> usize
219 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
223 /// Creates a new pointer with the given address.
225 /// This performs the same operation as an `addr as ptr` cast, but copies
226 /// the *address-space* and *provenance* of `self` to the new pointer.
227 /// This allows us to dynamically preserve and propagate this important
228 /// information in a way that is otherwise impossible with a unary cast.
230 /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
231 /// `self` to the given address, and therefore has all the same capabilities and restrictions.
233 /// This API and its claimed semantics are part of the Strict Provenance experiment,
234 /// see the [module documentation][crate::ptr] for details.
237 #[unstable(feature = "strict_provenance", issue = "95228")]
238 pub fn with_addr(self, addr: usize) -> Self
242 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
244 // In the mean-time, this operation is defined to be "as if" it was
245 // a wrapping_offset, so we can emulate it as such. This should properly
246 // restore pointer provenance even under today's compiler.
247 let self_addr = self.addr() as isize;
248 let dest_addr = addr as isize;
249 let offset = dest_addr.wrapping_sub(self_addr);
251 // This is the canonical desugarring of this operation
252 self.cast::<u8>().wrapping_offset(offset).cast::<T>()
255 /// Creates a new pointer by mapping `self`'s address to a new one.
257 /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
259 /// This API and its claimed semantics are part of the Strict Provenance experiment,
260 /// see the [module documentation][crate::ptr] for details.
263 #[unstable(feature = "strict_provenance", issue = "95228")]
264 pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self
268 self.with_addr(f(self.addr()))
271 /// Decompose a (possibly wide) pointer into its address and metadata components.
273 /// The pointer can be later reconstructed with [`from_raw_parts`].
274 #[unstable(feature = "ptr_metadata", issue = "81513")]
275 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
277 pub const fn to_raw_parts(self) -> (*const (), <T as super::Pointee>::Metadata) {
278 (self.cast(), metadata(self))
281 /// Returns `None` if the pointer is null, or else returns a shared reference to
282 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
283 /// must be used instead.
285 /// [`as_uninit_ref`]: #method.as_uninit_ref
289 /// When calling this method, you have to ensure that *either* the pointer is null *or*
290 /// all of the following is true:
292 /// * The pointer must be properly aligned.
294 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
296 /// * The pointer must point to an initialized instance of `T`.
298 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
299 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
300 /// In particular, while this reference exists, the memory the pointer points to must
301 /// not get mutated (except inside `UnsafeCell`).
303 /// This applies even if the result of this method is unused!
304 /// (The part about being initialized is not yet fully decided, but until
305 /// it is, the only safe approach is to ensure that they are indeed initialized.)
307 /// [the module documentation]: crate::ptr#safety
314 /// let ptr: *const u8 = &10u8 as *const u8;
317 /// if let Some(val_back) = ptr.as_ref() {
318 /// println!("We got back the value: {val_back}!");
323 /// # Null-unchecked version
325 /// If you are sure the pointer can never be null and are looking for some kind of
326 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
327 /// dereference the pointer directly.
330 /// let ptr: *const u8 = &10u8 as *const u8;
333 /// let val_back = &*ptr;
334 /// println!("We got back the value: {val_back}!");
337 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
338 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
340 pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
341 // SAFETY: the caller must guarantee that `self` is valid
342 // for a reference if it isn't null.
343 if self.is_null() { None } else { unsafe { Some(&*self) } }
346 /// Returns `None` if the pointer is null, or else returns a shared reference to
347 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
348 /// that the value has to be initialized.
350 /// [`as_ref`]: #method.as_ref
354 /// When calling this method, you have to ensure that *either* the pointer is null *or*
355 /// all of the following is true:
357 /// * The pointer must be properly aligned.
359 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
361 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
362 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
363 /// In particular, while this reference exists, the memory the pointer points to must
364 /// not get mutated (except inside `UnsafeCell`).
366 /// This applies even if the result of this method is unused!
368 /// [the module documentation]: crate::ptr#safety
375 /// #![feature(ptr_as_uninit)]
377 /// let ptr: *const u8 = &10u8 as *const u8;
380 /// if let Some(val_back) = ptr.as_uninit_ref() {
381 /// println!("We got back the value: {}!", val_back.assume_init());
386 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
387 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
388 pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
392 // SAFETY: the caller must guarantee that `self` meets all the
393 // requirements for a reference.
394 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
397 /// Calculates the offset from a pointer.
399 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
400 /// offset of `3 * size_of::<T>()` bytes.
404 /// If any of the following conditions are violated, the result is Undefined
407 /// * Both the starting and resulting pointer must be either in bounds or one
408 /// byte past the end of the same [allocated object].
410 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
412 /// * The offset being in bounds cannot rely on "wrapping around" the address
413 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
415 /// The compiler and standard library generally tries to ensure allocations
416 /// never reach a size where an offset is a concern. For instance, `Vec`
417 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
418 /// `vec.as_ptr().add(vec.len())` is always safe.
420 /// Most platforms fundamentally can't even construct such an allocation.
421 /// For instance, no known 64-bit platform can ever serve a request
422 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
423 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
424 /// more than `isize::MAX` bytes with things like Physical Address
425 /// Extension. As such, memory acquired directly from allocators or memory
426 /// mapped files *may* be too large to handle with this function.
428 /// Consider using [`wrapping_offset`] instead if these constraints are
429 /// difficult to satisfy. The only advantage of this method is that it
430 /// enables more aggressive compiler optimizations.
432 /// [`wrapping_offset`]: #method.wrapping_offset
433 /// [allocated object]: crate::ptr#allocated-object
440 /// let s: &str = "123";
441 /// let ptr: *const u8 = s.as_ptr();
444 /// println!("{}", *ptr.offset(1) as char);
445 /// println!("{}", *ptr.offset(2) as char);
448 #[stable(feature = "rust1", since = "1.0.0")]
449 #[must_use = "returns a new pointer rather than modifying its argument"]
450 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
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 pub const unsafe fn byte_offset(self, count: isize) -> Self {
475 // SAFETY: the caller must uphold the safety contract for `offset`.
476 let this = unsafe { self.cast::<u8>().offset(count).cast::<()>() };
477 from_raw_parts::<T>(this, metadata(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 from_raw_parts::<T>(self.cast::<u8>().wrapping_offset(count).cast::<()>(), metadata(self))
560 /// Calculates the distance between two pointers. The returned value is in
561 /// units of T: the distance in bytes divided by `mem::size_of::<T>()`.
563 /// This function is the inverse of [`offset`].
565 /// [`offset`]: #method.offset
569 /// If any of the following conditions are violated, the result is Undefined
572 /// * Both the starting and other pointer must be either in bounds or one
573 /// byte past the end of the same [allocated object].
575 /// * Both pointers must be *derived from* a pointer to the same object.
576 /// (See below for an example.)
578 /// * The distance between the pointers, in bytes, must be an exact multiple
579 /// of the size of `T`.
581 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
583 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
585 /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
586 /// address space, so two pointers within some value of any Rust type `T` will always satisfy
587 /// the last two conditions. The standard library also generally ensures that allocations
588 /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
589 /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
590 /// always satisfies the last two conditions.
592 /// Most platforms fundamentally can't even construct such a large allocation.
593 /// For instance, no known 64-bit platform can ever serve a request
594 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
595 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
596 /// more than `isize::MAX` bytes with things like Physical Address
597 /// Extension. As such, memory acquired directly from allocators or memory
598 /// mapped files *may* be too large to handle with this function.
599 /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
600 /// such large allocations either.)
602 /// [`add`]: #method.add
603 /// [allocated object]: crate::ptr#allocated-object
607 /// This function panics if `T` is a Zero-Sized Type ("ZST").
615 /// let ptr1: *const i32 = &a[1];
616 /// let ptr2: *const i32 = &a[3];
618 /// assert_eq!(ptr2.offset_from(ptr1), 2);
619 /// assert_eq!(ptr1.offset_from(ptr2), -2);
620 /// assert_eq!(ptr1.offset(2), ptr2);
621 /// assert_eq!(ptr2.offset(-2), ptr1);
625 /// *Incorrect* usage:
628 /// let ptr1 = Box::into_raw(Box::new(0u8)) as *const u8;
629 /// let ptr2 = Box::into_raw(Box::new(1u8)) as *const u8;
630 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
631 /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
632 /// let ptr2_other = (ptr1 as *const u8).wrapping_offset(diff);
633 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
634 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
635 /// // computing their offset is undefined behavior, even though
636 /// // they point to the same address!
638 /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
641 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
642 #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "92980")]
644 pub const unsafe fn offset_from(self, origin: *const T) -> isize
648 let pointee_size = mem::size_of::<T>();
649 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
650 // SAFETY: the caller must uphold the safety contract for `ptr_offset_from`.
651 unsafe { intrinsics::ptr_offset_from(self, origin) }
654 /// Calculates the distance between two pointers. The returned value is in
655 /// units of **bytes**.
657 /// This is purely a convenience for casting to a `u8` pointer and
658 /// using [offset_from][pointer::offset_from] on it. See that method for
659 /// documentation and safety requirements.
661 /// For non-`Sized` pointees this operation considers only the data pointers,
662 /// ignoring the metadata.
664 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
665 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
666 pub const unsafe fn byte_offset_from(self, origin: *const T) -> isize {
667 // SAFETY: the caller must uphold the safety contract for `offset_from`.
668 unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
671 /// Calculates the distance between two pointers, *where it's known that
672 /// `self` is equal to or greater than `origin`*. The returned value is in
673 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
675 /// This computes the same value that [`offset_from`](#method.offset_from)
676 /// would compute, but with the added precondition that that the offset is
677 /// guaranteed to be non-negative. This method is equivalent to
678 /// `usize::from(self.offset_from(origin)).unwrap_unchecked()`,
679 /// but it provides slightly more information to the optimizer, which can
680 /// sometimes allow it to optimize slightly better with some backends.
682 /// This method can be though of as recovering the `count` that was passed
683 /// to [`add`](#method.add) (or, with the parameters in the other order,
684 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
685 /// that their safety preconditions are met:
687 /// # #![feature(ptr_sub_ptr)]
688 /// # unsafe fn blah(ptr: *const i32, origin: *const i32, count: usize) -> bool {
689 /// ptr.sub_ptr(origin) == count
691 /// origin.add(count) == ptr
693 /// ptr.sub(count) == origin
699 /// - The distance between the pointers must be non-negative (`self >= origin`)
701 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
702 /// apply to this method as well; see it for the full details.
704 /// Importantly, despite the return type of this method being able to represent
705 /// a larger offset, it's still *not permitted* to pass pointers which differ
706 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
707 /// always be less than or equal to `isize::MAX as usize`.
711 /// This function panics if `T` is a Zero-Sized Type ("ZST").
716 /// #![feature(ptr_sub_ptr)]
719 /// let ptr1: *const i32 = &a[1];
720 /// let ptr2: *const i32 = &a[3];
722 /// assert_eq!(ptr2.sub_ptr(ptr1), 2);
723 /// assert_eq!(ptr1.add(2), ptr2);
724 /// assert_eq!(ptr2.sub(2), ptr1);
725 /// assert_eq!(ptr2.sub_ptr(ptr2), 0);
728 /// // This would be incorrect, as the pointers are not correctly ordered:
729 /// // ptr1.offset_from(ptr2)
731 #[unstable(feature = "ptr_sub_ptr", issue = "95892")]
732 #[rustc_const_unstable(feature = "const_ptr_sub_ptr", issue = "95892")]
734 pub const unsafe fn sub_ptr(self, origin: *const T) -> usize
738 // SAFETY: The comparison has no side-effects, and the intrinsic
739 // does this check internally in the CTFE implementation.
740 unsafe { assert_unsafe_precondition!(self >= origin) };
742 let pointee_size = mem::size_of::<T>();
743 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
744 // SAFETY: the caller must uphold the safety contract for `ptr_offset_from_unsigned`.
745 unsafe { intrinsics::ptr_offset_from_unsigned(self, origin) }
748 /// Returns whether two pointers are guaranteed to be equal.
750 /// At runtime this function behaves like `self == other`.
751 /// However, in some contexts (e.g., compile-time evaluation),
752 /// it is not always possible to determine equality of two pointers, so this function may
753 /// spuriously return `false` for pointers that later actually turn out to be equal.
754 /// But when it returns `true`, the pointers are guaranteed to be equal.
756 /// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
757 /// comparisons for which both functions return `false`.
759 /// [`guaranteed_ne`]: #method.guaranteed_ne
761 /// The return value may change depending on the compiler version and unsafe code must not
762 /// rely on the result of this function for soundness. It is suggested to only use this function
763 /// for performance optimizations where spurious `false` return values by this function do not
764 /// affect the outcome, but just the performance.
765 /// The consequences of using this method to make runtime and compile-time code behave
766 /// differently have not been explored. This method should not be used to introduce such
767 /// differences, and it should also not be stabilized before we have a better understanding
769 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
770 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
772 pub const fn guaranteed_eq(self, other: *const T) -> bool
776 intrinsics::ptr_guaranteed_eq(self, other)
779 /// Returns whether two pointers are guaranteed to be unequal.
781 /// At runtime this function behaves like `self != other`.
782 /// However, in some contexts (e.g., compile-time evaluation),
783 /// it is not always possible to determine the inequality of two pointers, so this function may
784 /// spuriously return `false` for pointers that later actually turn out to be unequal.
785 /// But when it returns `true`, the pointers are guaranteed to be unequal.
787 /// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
788 /// comparisons for which both functions return `false`.
790 /// [`guaranteed_eq`]: #method.guaranteed_eq
792 /// The return value may change depending on the compiler version and unsafe code must not
793 /// rely on the result of this function for soundness. It is suggested to only use this function
794 /// for performance optimizations where spurious `false` return values by this function do not
795 /// affect the outcome, but just the performance.
796 /// The consequences of using this method to make runtime and compile-time code behave
797 /// differently have not been explored. This method should not be used to introduce such
798 /// differences, and it should also not be stabilized before we have a better understanding
800 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
801 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
803 pub const fn guaranteed_ne(self, other: *const T) -> bool
807 intrinsics::ptr_guaranteed_ne(self, other)
810 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
812 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
813 /// offset of `3 * size_of::<T>()` bytes.
817 /// If any of the following conditions are violated, the result is Undefined
820 /// * Both the starting and resulting pointer must be either in bounds or one
821 /// byte past the end of the same [allocated object].
823 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
825 /// * The offset being in bounds cannot rely on "wrapping around" the address
826 /// space. That is, the infinite-precision sum must fit in a `usize`.
828 /// The compiler and standard library generally tries to ensure allocations
829 /// never reach a size where an offset is a concern. For instance, `Vec`
830 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
831 /// `vec.as_ptr().add(vec.len())` is always safe.
833 /// Most platforms fundamentally can't even construct such an allocation.
834 /// For instance, no known 64-bit platform can ever serve a request
835 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
836 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
837 /// more than `isize::MAX` bytes with things like Physical Address
838 /// Extension. As such, memory acquired directly from allocators or memory
839 /// mapped files *may* be too large to handle with this function.
841 /// Consider using [`wrapping_add`] instead if these constraints are
842 /// difficult to satisfy. The only advantage of this method is that it
843 /// enables more aggressive compiler optimizations.
845 /// [`wrapping_add`]: #method.wrapping_add
846 /// [allocated object]: crate::ptr#allocated-object
853 /// let s: &str = "123";
854 /// let ptr: *const u8 = s.as_ptr();
857 /// println!("{}", *ptr.add(1) as char);
858 /// println!("{}", *ptr.add(2) as char);
861 #[stable(feature = "pointer_methods", since = "1.26.0")]
862 #[must_use = "returns a new pointer rather than modifying its argument"]
863 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
865 pub const unsafe fn add(self, count: usize) -> Self
869 // SAFETY: the caller must uphold the safety contract for `offset`.
870 unsafe { self.offset(count as isize) }
873 /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
875 /// `count` is in units of bytes.
877 /// This is purely a convenience for casting to a `u8` pointer and
878 /// using [add][pointer::add] on it. See that method for documentation
879 /// and safety requirements.
881 /// For non-`Sized` pointees this operation changes only the data pointer,
882 /// leaving the metadata untouched.
885 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
886 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
887 pub const unsafe fn byte_add(self, count: usize) -> Self {
888 // SAFETY: the caller must uphold the safety contract for `add`.
889 let this = unsafe { self.cast::<u8>().add(count).cast::<()>() };
890 from_raw_parts::<T>(this, metadata(self))
893 /// Calculates the offset from a pointer (convenience for
894 /// `.offset((count as isize).wrapping_neg())`).
896 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
897 /// offset of `3 * size_of::<T>()` bytes.
901 /// If any of the following conditions are violated, the result is Undefined
904 /// * Both the starting and resulting pointer must be either in bounds or one
905 /// byte past the end of the same [allocated object].
907 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
909 /// * The offset being in bounds cannot rely on "wrapping around" the address
910 /// space. That is, the infinite-precision sum must fit in a usize.
912 /// The compiler and standard library generally tries to ensure allocations
913 /// never reach a size where an offset is a concern. For instance, `Vec`
914 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
915 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
917 /// Most platforms fundamentally can't even construct such an allocation.
918 /// For instance, no known 64-bit platform can ever serve a request
919 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
920 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
921 /// more than `isize::MAX` bytes with things like Physical Address
922 /// Extension. As such, memory acquired directly from allocators or memory
923 /// mapped files *may* be too large to handle with this function.
925 /// Consider using [`wrapping_sub`] instead if these constraints are
926 /// difficult to satisfy. The only advantage of this method is that it
927 /// enables more aggressive compiler optimizations.
929 /// [`wrapping_sub`]: #method.wrapping_sub
930 /// [allocated object]: crate::ptr#allocated-object
937 /// let s: &str = "123";
940 /// let end: *const u8 = s.as_ptr().add(3);
941 /// println!("{}", *end.sub(1) as char);
942 /// println!("{}", *end.sub(2) as char);
945 #[stable(feature = "pointer_methods", since = "1.26.0")]
946 #[must_use = "returns a new pointer rather than modifying its argument"]
947 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
949 pub const unsafe fn sub(self, count: usize) -> Self
953 // SAFETY: the caller must uphold the safety contract for `offset`.
954 unsafe { self.offset((count as isize).wrapping_neg()) }
957 /// Calculates the offset from a pointer in bytes (convenience for
958 /// `.byte_offset((count as isize).wrapping_neg())`).
960 /// `count` is in units of bytes.
962 /// This is purely a convenience for casting to a `u8` pointer and
963 /// using [sub][pointer::sub] on it. See that method for documentation
964 /// and safety requirements.
966 /// For non-`Sized` pointees this operation changes only the data pointer,
967 /// leaving the metadata untouched.
970 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
971 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
972 pub const unsafe fn byte_sub(self, count: usize) -> Self {
973 // SAFETY: the caller must uphold the safety contract for `sub`.
974 let this = unsafe { self.cast::<u8>().sub(count).cast::<()>() };
975 from_raw_parts::<T>(this, metadata(self))
978 /// Calculates the offset from a pointer using wrapping arithmetic.
979 /// (convenience for `.wrapping_offset(count as isize)`)
981 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
982 /// offset of `3 * size_of::<T>()` bytes.
986 /// This operation itself is always safe, but using the resulting pointer is not.
988 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
989 /// be used to read or write other allocated objects.
991 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
992 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
993 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
994 /// `x` and `y` point into the same allocated object.
996 /// Compared to [`add`], this method basically delays the requirement of staying within the
997 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
998 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
999 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1000 /// can be optimized better and is thus preferable in performance-sensitive code.
1002 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1003 /// intermediate values used during the computation of the final result. For example,
1004 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1005 /// allocated object and then re-entering it later is permitted.
1007 /// [`add`]: #method.add
1008 /// [allocated object]: crate::ptr#allocated-object
1015 /// // Iterate using a raw pointer in increments of two elements
1016 /// let data = [1u8, 2, 3, 4, 5];
1017 /// let mut ptr: *const u8 = data.as_ptr();
1019 /// let end_rounded_up = ptr.wrapping_add(6);
1021 /// // This loop prints "1, 3, 5, "
1022 /// while ptr != end_rounded_up {
1024 /// print!("{}, ", *ptr);
1026 /// ptr = ptr.wrapping_add(step);
1029 #[stable(feature = "pointer_methods", since = "1.26.0")]
1030 #[must_use = "returns a new pointer rather than modifying its argument"]
1031 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1033 pub const fn wrapping_add(self, count: usize) -> Self
1037 self.wrapping_offset(count as isize)
1040 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1041 /// (convenience for `.wrapping_byte_offset(count as isize)`)
1043 /// `count` is in units of bytes.
1045 /// This is purely a convenience for casting to a `u8` pointer and
1046 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1048 /// For non-`Sized` pointees this operation changes only the data pointer,
1049 /// leaving the metadata untouched.
1052 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1053 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1054 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1055 from_raw_parts::<T>(self.cast::<u8>().wrapping_add(count).cast::<()>(), metadata(self))
1058 /// Calculates the offset from a pointer using wrapping arithmetic.
1059 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1061 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1062 /// offset of `3 * size_of::<T>()` bytes.
1066 /// This operation itself is always safe, but using the resulting pointer is not.
1068 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1069 /// be used to read or write other allocated objects.
1071 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1072 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1073 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1074 /// `x` and `y` point into the same allocated object.
1076 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1077 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
1078 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1079 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1080 /// can be optimized better and is thus preferable in performance-sensitive code.
1082 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1083 /// intermediate values used during the computation of the final result. For example,
1084 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1085 /// allocated object and then re-entering it later is permitted.
1087 /// [`sub`]: #method.sub
1088 /// [allocated object]: crate::ptr#allocated-object
1095 /// // Iterate using a raw pointer in increments of two elements (backwards)
1096 /// let data = [1u8, 2, 3, 4, 5];
1097 /// let mut ptr: *const u8 = data.as_ptr();
1098 /// let start_rounded_down = ptr.wrapping_sub(2);
1099 /// ptr = ptr.wrapping_add(4);
1101 /// // This loop prints "5, 3, 1, "
1102 /// while ptr != start_rounded_down {
1104 /// print!("{}, ", *ptr);
1106 /// ptr = ptr.wrapping_sub(step);
1109 #[stable(feature = "pointer_methods", since = "1.26.0")]
1110 #[must_use = "returns a new pointer rather than modifying its argument"]
1111 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1113 pub const fn wrapping_sub(self, count: usize) -> Self
1117 self.wrapping_offset((count as isize).wrapping_neg())
1120 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1121 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1123 /// `count` is in units of bytes.
1125 /// This is purely a convenience for casting to a `u8` pointer and
1126 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1128 /// For non-`Sized` pointees this operation changes only the data pointer,
1129 /// leaving the metadata untouched.
1132 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1133 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1134 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1135 from_raw_parts::<T>(self.cast::<u8>().wrapping_sub(count).cast::<()>(), metadata(self))
1138 /// Reads the value from `self` without moving it. This leaves the
1139 /// memory in `self` unchanged.
1141 /// See [`ptr::read`] for safety concerns and examples.
1143 /// [`ptr::read`]: crate::ptr::read()
1144 #[stable(feature = "pointer_methods", since = "1.26.0")]
1145 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1147 pub const unsafe fn read(self) -> T
1151 // SAFETY: the caller must uphold the safety contract for `read`.
1152 unsafe { read(self) }
1155 /// Performs a volatile read of the value from `self` without moving it. This
1156 /// leaves the memory in `self` unchanged.
1158 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1159 /// to not be elided or reordered by the compiler across other volatile
1162 /// See [`ptr::read_volatile`] for safety concerns and examples.
1164 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1165 #[stable(feature = "pointer_methods", since = "1.26.0")]
1167 pub unsafe fn read_volatile(self) -> T
1171 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1172 unsafe { read_volatile(self) }
1175 /// Reads the value from `self` without moving it. This leaves the
1176 /// memory in `self` unchanged.
1178 /// Unlike `read`, the pointer may be unaligned.
1180 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1182 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1183 #[stable(feature = "pointer_methods", since = "1.26.0")]
1184 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1186 pub const unsafe fn read_unaligned(self) -> T
1190 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1191 unsafe { read_unaligned(self) }
1194 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1195 /// and destination may overlap.
1197 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1199 /// See [`ptr::copy`] for safety concerns and examples.
1201 /// [`ptr::copy`]: crate::ptr::copy()
1202 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1203 #[stable(feature = "pointer_methods", since = "1.26.0")]
1205 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1209 // SAFETY: the caller must uphold the safety contract for `copy`.
1210 unsafe { copy(self, dest, count) }
1213 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1214 /// and destination may *not* overlap.
1216 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1218 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1220 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1221 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1222 #[stable(feature = "pointer_methods", since = "1.26.0")]
1224 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1228 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1229 unsafe { copy_nonoverlapping(self, dest, count) }
1232 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1235 /// If it is not possible to align the pointer, the implementation returns
1236 /// `usize::MAX`. It is permissible for the implementation to *always*
1237 /// return `usize::MAX`. Only your algorithm's performance can depend
1238 /// on getting a usable offset here, not its correctness.
1240 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1241 /// used with the `wrapping_add` method.
1243 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1244 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1245 /// the returned offset is correct in all terms other than alignment.
1249 /// The function panics if `align` is not a power-of-two.
1253 /// Accessing adjacent `u8` as `u16`
1256 /// # fn foo(n: usize) {
1257 /// # use std::mem::align_of;
1259 /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
1260 /// let ptr = x.as_ptr().add(n) as *const u8;
1261 /// let offset = ptr.align_offset(align_of::<u16>());
1262 /// if offset < x.len() - n - 1 {
1263 /// let u16_ptr = ptr.add(offset) as *const u16;
1264 /// assert_ne!(*u16_ptr, 500);
1266 /// // while the pointer can be aligned via `offset`, it would point
1267 /// // outside the allocation
1271 #[stable(feature = "align_offset", since = "1.36.0")]
1272 #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1273 pub const fn align_offset(self, align: usize) -> usize
1277 if !align.is_power_of_two() {
1278 panic!("align_offset: align is not a power-of-two");
1281 fn rt_impl<T>(p: *const T, align: usize) -> usize {
1282 // SAFETY: `align` has been checked to be a power of 2 above
1283 unsafe { align_offset(p, align) }
1286 const fn ctfe_impl<T>(_: *const T, _: usize) -> usize {
1291 // It is permissible for `align_offset` to always return `usize::MAX`,
1292 // algorithm correctness can not depend on `align_offset` returning non-max values.
1294 // As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
1295 unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
1298 /// Returns whether the pointer is properly aligned for `T`.
1301 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1302 pub fn is_aligned(self) -> bool
1306 self.is_aligned_to(core::mem::align_of::<T>())
1309 /// Returns whether the pointer is aligned to `align`.
1311 /// For non-`Sized` pointees this operation considers only the data pointer,
1312 /// ignoring the metadata.
1316 /// The function panics if `align` is not a power-of-two (this includes 0).
1319 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1320 pub fn is_aligned_to(self, align: usize) -> bool {
1321 if !align.is_power_of_two() {
1322 panic!("is_aligned_to: align is not a power-of-two");
1325 // SAFETY: `is_power_of_two()` will return `false` for zero.
1326 unsafe { core::intrinsics::assume(align != 0) };
1328 // Cast is needed for `T: !Sized`
1329 self.cast::<u8>().addr() % align == 0
1333 impl<T> *const [T] {
1334 /// Returns the length of a raw slice.
1336 /// The returned value is the number of **elements**, not the number of bytes.
1338 /// This function is safe, even when the raw slice cannot be cast to a slice
1339 /// reference because the pointer is null or unaligned.
1344 /// #![feature(slice_ptr_len)]
1348 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1349 /// assert_eq!(slice.len(), 3);
1352 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1353 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1354 pub const fn len(self) -> usize {
1358 /// Returns a raw pointer to the slice's buffer.
1360 /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1365 /// #![feature(slice_ptr_get)]
1368 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1369 /// assert_eq!(slice.as_ptr(), ptr::null());
1372 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1373 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
1374 pub const fn as_ptr(self) -> *const T {
1378 /// Returns a raw pointer to an element or subslice, without doing bounds
1381 /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
1382 /// is *[undefined behavior]* even if the resulting pointer is not used.
1384 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1389 /// #![feature(slice_ptr_get)]
1391 /// let x = &[1, 2, 4] as *const [i32];
1394 /// assert_eq!(x.get_unchecked(1), x.as_ptr().add(1));
1397 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1398 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
1400 pub const unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output
1402 I: ~const SliceIndex<[T]>,
1404 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1405 unsafe { index.get_unchecked(self) }
1408 /// Returns `None` if the pointer is null, or else returns a shared slice to
1409 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1410 /// that the value has to be initialized.
1412 /// [`as_ref`]: #method.as_ref
1416 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1417 /// all of the following is true:
1419 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1420 /// and it must be properly aligned. This means in particular:
1422 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1423 /// Slices can never span across multiple allocated objects.
1425 /// * The pointer must be aligned even for zero-length slices. One
1426 /// reason for this is that enum layout optimizations may rely on references
1427 /// (including slices of any length) being aligned and non-null to distinguish
1428 /// them from other data. You can obtain a pointer that is usable as `data`
1429 /// for zero-length slices using [`NonNull::dangling()`].
1431 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1432 /// See the safety documentation of [`pointer::offset`].
1434 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1435 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1436 /// In particular, while this reference exists, the memory the pointer points to must
1437 /// not get mutated (except inside `UnsafeCell`).
1439 /// This applies even if the result of this method is unused!
1441 /// See also [`slice::from_raw_parts`][].
1443 /// [valid]: crate::ptr#safety
1444 /// [allocated object]: crate::ptr#allocated-object
1446 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1447 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1448 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1452 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1453 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1458 // Equality for pointers
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 impl<T: ?Sized> PartialEq for *const T {
1462 fn eq(&self, other: &*const T) -> bool {
1467 #[stable(feature = "rust1", since = "1.0.0")]
1468 impl<T: ?Sized> Eq for *const T {}
1470 // Comparison for pointers
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 impl<T: ?Sized> Ord for *const T {
1474 fn cmp(&self, other: &*const T) -> Ordering {
1477 } else if self == other {
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl<T: ?Sized> PartialOrd for *const T {
1488 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
1489 Some(self.cmp(other))
1493 fn lt(&self, other: &*const T) -> bool {
1498 fn le(&self, other: &*const T) -> bool {
1503 fn gt(&self, other: &*const T) -> bool {
1508 fn ge(&self, other: &*const T) -> bool {