2 use crate::cmp::Ordering::{self, Equal, Greater, Less};
4 use crate::slice::{self, SliceIndex};
6 impl<T: ?Sized> *mut T {
7 /// Returns `true` if the pointer is null.
9 /// Note that unsized types have many possible null pointers, as only the
10 /// raw data pointer is considered, not their length, vtable, etc.
11 /// Therefore, two pointers that are null may still not compare equal to
14 /// ## Behavior during const evaluation
16 /// When this function is used during const evaluation, it may return `false` for pointers
17 /// that turn out to be null at runtime. Specifically, when a pointer to some memory
18 /// is offset beyond its bounds in such a way that the resulting pointer is null,
19 /// the function will still return `false`. There is no way for CTFE to know
20 /// the absolute position of that memory, so we cannot tell if the pointer is
28 /// let mut s = [1, 2, 3];
29 /// let ptr: *mut u32 = s.as_mut_ptr();
30 /// assert!(!ptr.is_null());
32 #[stable(feature = "rust1", since = "1.0.0")]
33 #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")]
35 pub const fn is_null(self) -> bool {
36 // Compare via a cast to a thin pointer, so fat pointers are only
37 // considering their "data" part for null-ness.
38 match (self as *mut u8).guaranteed_eq(null_mut()) {
44 /// Casts to a pointer of another type.
45 #[stable(feature = "ptr_cast", since = "1.38.0")]
46 #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
48 pub const fn cast<U>(self) -> *mut U {
52 /// Use the pointer value in a new pointer of another type.
54 /// In case `val` is a (fat) pointer to an unsized type, this operation
55 /// will ignore the pointer part, whereas for (thin) pointers to sized
56 /// types, this has the same effect as a simple cast.
58 /// The resulting pointer will have provenance of `self`, i.e., for a fat
59 /// pointer, this operation is semantically the same as creating a new
60 /// fat pointer with the data pointer value of `self` but the metadata of
65 /// This function is primarily useful for allowing byte-wise pointer
66 /// arithmetic on potentially fat pointers:
69 /// #![feature(set_ptr_value)]
70 /// # use core::fmt::Debug;
71 /// let mut arr: [i32; 3] = [1, 2, 3];
72 /// let mut ptr = arr.as_mut_ptr() as *mut dyn Debug;
73 /// let thin = ptr as *mut u8;
75 /// ptr = thin.add(8).with_metadata_of(ptr);
76 /// # assert_eq!(*(ptr as *mut i32), 3);
77 /// println!("{:?}", &*ptr); // will print "3"
80 #[unstable(feature = "set_ptr_value", issue = "75091")]
81 #[must_use = "returns a new pointer rather than modifying its argument"]
83 pub fn with_metadata_of<U>(self, val: *const U) -> *mut U
87 // Prepare in the type system that we will replace the pointer value with a mutable
88 // pointer, taking the mutable provenance from the `self` pointer.
89 let mut val = val as *mut U;
90 // Pointer to the pointer value within the value.
91 let target = &mut val as *mut *mut U as *mut *mut u8;
92 // SAFETY: In case of a thin pointer, this operations is identical
93 // to a simple assignment. In case of a fat pointer, with the current
94 // fat pointer layout implementation, the first field of such a
95 // pointer is always the data pointer, which is likewise assigned.
96 unsafe { *target = self as *mut u8 };
100 /// Changes constness without changing the type.
102 /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
105 /// While not strictly required (`*mut T` coerces to `*const T`), this is provided for symmetry
106 /// with [`cast_mut`] on `*const T` and may have documentation value if used instead of implicit
109 /// [`cast_mut`]: #method.cast_mut
110 #[stable(feature = "ptr_const_cast", since = "1.65.0")]
111 #[rustc_const_stable(feature = "ptr_const_cast", since = "1.65.0")]
112 pub const fn cast_const(self) -> *const T {
116 /// Casts a pointer to its raw bits.
118 /// This is equivalent to `as usize`, but is more specific to enhance readability.
119 /// The inverse method is [`from_bits`](#method.from_bits-1).
121 /// In particular, `*p as usize` and `p as usize` will both compile for
122 /// pointers to numeric types but do very different things, so using this
123 /// helps emphasize that reading the bits was intentional.
128 /// #![feature(ptr_to_from_bits)]
129 /// let mut array = [13, 42];
130 /// let mut it = array.iter_mut();
131 /// let p0: *mut i32 = it.next().unwrap();
132 /// assert_eq!(<*mut _>::from_bits(p0.to_bits()), p0);
133 /// let p1: *mut i32 = it.next().unwrap();
134 /// assert_eq!(p1.to_bits() - p0.to_bits(), 4);
136 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
137 pub fn to_bits(self) -> usize
144 /// Creates a pointer from its raw bits.
146 /// This is equivalent to `as *mut T`, but is more specific to enhance readability.
147 /// The inverse method is [`to_bits`](#method.to_bits-1).
152 /// #![feature(ptr_to_from_bits)]
153 /// use std::ptr::NonNull;
154 /// let dangling: *mut u8 = NonNull::dangling().as_ptr();
155 /// assert_eq!(<*mut u8>::from_bits(1), dangling);
157 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
158 pub fn from_bits(bits: usize) -> Self
165 /// Gets the "address" portion of the pointer.
167 /// This is similar to `self as usize`, which semantically discards *provenance* and
168 /// *address-space* information. However, unlike `self as usize`, casting the returned address
169 /// back to a pointer yields [`invalid`][], which is undefined behavior to dereference. To
170 /// properly restore the lost information and obtain a dereferenceable pointer, use
171 /// [`with_addr`][pointer::with_addr] or [`map_addr`][pointer::map_addr].
173 /// If using those APIs is not possible because there is no way to preserve a pointer with the
174 /// required provenance, use [`expose_addr`][pointer::expose_addr] and
175 /// [`from_exposed_addr_mut`][from_exposed_addr_mut] instead. However, note that this makes
176 /// your code less portable and less amenable to tools that check for compliance with the Rust
179 /// On most platforms this will produce a value with the same bytes as the original
180 /// pointer, because all the bytes are dedicated to describing the address.
181 /// Platforms which need to store additional information in the pointer may
182 /// perform a change of representation to produce a value containing only the address
183 /// portion of the pointer. What that means is up to the platform to define.
185 /// This API and its claimed semantics are part of the Strict Provenance experiment, and as such
186 /// might change in the future (including possibly weakening this so it becomes wholly
187 /// equivalent to `self as usize`). See the [module documentation][crate::ptr] for details.
190 #[unstable(feature = "strict_provenance", issue = "95228")]
191 pub fn addr(self) -> usize
195 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
196 // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
198 unsafe { mem::transmute(self) }
201 /// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future
202 /// use in [`from_exposed_addr`][].
204 /// This is equivalent to `self as usize`, which semantically discards *provenance* and
205 /// *address-space* information. Furthermore, this (like the `as` cast) has the implicit
206 /// side-effect of marking the provenance as 'exposed', so on platforms that support it you can
207 /// later call [`from_exposed_addr_mut`][] to reconstitute the original pointer including its
208 /// provenance. (Reconstructing address space information, if required, is your responsibility.)
210 /// Using this method means that code is *not* following Strict Provenance rules. Supporting
211 /// [`from_exposed_addr_mut`][] complicates specification and reasoning and may not be supported
212 /// by tools that help you to stay conformant with the Rust memory model, so it is recommended
213 /// to use [`addr`][pointer::addr] wherever possible.
215 /// On most platforms this will produce a value with the same bytes as the original pointer,
216 /// because all the bytes are dedicated to describing the address. Platforms which need to store
217 /// additional information in the pointer may not support this operation, since the 'expose'
218 /// side-effect which is required for [`from_exposed_addr_mut`][] to work is typically not
221 /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
222 /// [module documentation][crate::ptr] for details.
224 /// [`from_exposed_addr_mut`]: from_exposed_addr_mut
227 #[unstable(feature = "strict_provenance", issue = "95228")]
228 pub fn expose_addr(self) -> usize
232 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
236 /// Creates a new pointer with the given address.
238 /// This performs the same operation as an `addr as ptr` cast, but copies
239 /// the *address-space* and *provenance* of `self` to the new pointer.
240 /// This allows us to dynamically preserve and propagate this important
241 /// information in a way that is otherwise impossible with a unary cast.
243 /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
244 /// `self` to the given address, and therefore has all the same capabilities and restrictions.
246 /// This API and its claimed semantics are part of the Strict Provenance experiment,
247 /// see the [module documentation][crate::ptr] for details.
250 #[unstable(feature = "strict_provenance", issue = "95228")]
251 pub fn with_addr(self, addr: usize) -> Self
255 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
257 // In the mean-time, this operation is defined to be "as if" it was
258 // a wrapping_offset, so we can emulate it as such. This should properly
259 // restore pointer provenance even under today's compiler.
260 let self_addr = self.addr() as isize;
261 let dest_addr = addr as isize;
262 let offset = dest_addr.wrapping_sub(self_addr);
264 // This is the canonical desugarring of this operation
265 self.wrapping_byte_offset(offset)
268 /// Creates a new pointer by mapping `self`'s address to a new one.
270 /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
272 /// This API and its claimed semantics are part of the Strict Provenance experiment,
273 /// see the [module documentation][crate::ptr] for details.
276 #[unstable(feature = "strict_provenance", issue = "95228")]
277 pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self
281 self.with_addr(f(self.addr()))
284 /// Decompose a (possibly wide) pointer into its address and metadata components.
286 /// The pointer can be later reconstructed with [`from_raw_parts_mut`].
287 #[unstable(feature = "ptr_metadata", issue = "81513")]
288 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
290 pub const fn to_raw_parts(self) -> (*mut (), <T as super::Pointee>::Metadata) {
291 (self.cast(), super::metadata(self))
294 /// Returns `None` if the pointer is null, or else returns a shared reference to
295 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
296 /// must be used instead.
298 /// For the mutable counterpart see [`as_mut`].
300 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
301 /// [`as_mut`]: #method.as_mut
305 /// When calling this method, you have to ensure that *either* the pointer is null *or*
306 /// all of the following is true:
308 /// * The pointer must be properly aligned.
310 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
312 /// * The pointer must point to an initialized instance of `T`.
314 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
315 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
316 /// In particular, while this reference exists, the memory the pointer points to must
317 /// not get mutated (except inside `UnsafeCell`).
319 /// This applies even if the result of this method is unused!
320 /// (The part about being initialized is not yet fully decided, but until
321 /// it is, the only safe approach is to ensure that they are indeed initialized.)
323 /// [the module documentation]: crate::ptr#safety
330 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
333 /// if let Some(val_back) = ptr.as_ref() {
334 /// println!("We got back the value: {val_back}!");
339 /// # Null-unchecked version
341 /// If you are sure the pointer can never be null and are looking for some kind of
342 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
343 /// dereference the pointer directly.
346 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
349 /// let val_back = &*ptr;
350 /// println!("We got back the value: {val_back}!");
353 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
354 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
356 pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
357 // SAFETY: the caller must guarantee that `self` is valid for a
358 // reference if it isn't null.
359 if self.is_null() { None } else { unsafe { Some(&*self) } }
362 /// Returns `None` if the pointer is null, or else returns a shared reference to
363 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
364 /// that the value has to be initialized.
366 /// For the mutable counterpart see [`as_uninit_mut`].
368 /// [`as_ref`]: #method.as_ref-1
369 /// [`as_uninit_mut`]: #method.as_uninit_mut
373 /// When calling this method, you have to ensure that *either* the pointer is null *or*
374 /// all of the following is true:
376 /// * The pointer must be properly aligned.
378 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
380 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
381 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
382 /// In particular, while this reference exists, the memory the pointer points to must
383 /// not get mutated (except inside `UnsafeCell`).
385 /// This applies even if the result of this method is unused!
387 /// [the module documentation]: crate::ptr#safety
394 /// #![feature(ptr_as_uninit)]
396 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
399 /// if let Some(val_back) = ptr.as_uninit_ref() {
400 /// println!("We got back the value: {}!", val_back.assume_init());
405 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
406 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
407 pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
411 // SAFETY: the caller must guarantee that `self` meets all the
412 // requirements for a reference.
413 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
416 /// Calculates the offset from a pointer.
418 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
419 /// offset of `3 * size_of::<T>()` bytes.
423 /// If any of the following conditions are violated, the result is Undefined
426 /// * Both the starting and resulting pointer must be either in bounds or one
427 /// byte past the end of the same [allocated object].
429 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
431 /// * The offset being in bounds cannot rely on "wrapping around" the address
432 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
434 /// The compiler and standard library generally tries to ensure allocations
435 /// never reach a size where an offset is a concern. For instance, `Vec`
436 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
437 /// `vec.as_ptr().add(vec.len())` is always safe.
439 /// Most platforms fundamentally can't even construct such an allocation.
440 /// For instance, no known 64-bit platform can ever serve a request
441 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
442 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
443 /// more than `isize::MAX` bytes with things like Physical Address
444 /// Extension. As such, memory acquired directly from allocators or memory
445 /// mapped files *may* be too large to handle with this function.
447 /// Consider using [`wrapping_offset`] instead if these constraints are
448 /// difficult to satisfy. The only advantage of this method is that it
449 /// enables more aggressive compiler optimizations.
451 /// [`wrapping_offset`]: #method.wrapping_offset
452 /// [allocated object]: crate::ptr#allocated-object
459 /// let mut s = [1, 2, 3];
460 /// let ptr: *mut u32 = s.as_mut_ptr();
463 /// println!("{}", *ptr.offset(1));
464 /// println!("{}", *ptr.offset(2));
467 #[stable(feature = "rust1", since = "1.0.0")]
468 #[must_use = "returns a new pointer rather than modifying its argument"]
469 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
471 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
472 pub const unsafe fn offset(self, count: isize) -> *mut T
476 // SAFETY: the caller must uphold the safety contract for `offset`.
477 // The obtained pointer is valid for writes since the caller must
478 // guarantee that it points to the same allocated object as `self`.
479 unsafe { intrinsics::offset(self, count) as *mut T }
482 /// Calculates the offset from a pointer in bytes.
484 /// `count` is in units of **bytes**.
486 /// This is purely a convenience for casting to a `u8` pointer and
487 /// using [offset][pointer::offset] on it. See that method for documentation
488 /// and safety requirements.
490 /// For non-`Sized` pointees this operation changes only the data pointer,
491 /// leaving the metadata untouched.
494 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
495 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
496 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
497 pub const unsafe fn byte_offset(self, count: isize) -> Self {
498 // SAFETY: the caller must uphold the safety contract for `offset`.
499 let this = unsafe { self.cast::<u8>().offset(count).cast::<()>() };
500 from_raw_parts_mut::<T>(this, metadata(self))
503 /// Calculates the offset from a pointer using wrapping arithmetic.
504 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
505 /// offset of `3 * size_of::<T>()` bytes.
509 /// This operation itself is always safe, but using the resulting pointer is not.
511 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
512 /// be used to read or write other allocated objects.
514 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
515 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
516 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
517 /// `x` and `y` point into the same allocated object.
519 /// Compared to [`offset`], this method basically delays the requirement of staying within the
520 /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
521 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
522 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
523 /// can be optimized better and is thus preferable in performance-sensitive code.
525 /// The delayed check only considers the value of the pointer that was dereferenced, not the
526 /// intermediate values used during the computation of the final result. For example,
527 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
528 /// words, leaving the allocated object and then re-entering it later is permitted.
530 /// [`offset`]: #method.offset
531 /// [allocated object]: crate::ptr#allocated-object
538 /// // Iterate using a raw pointer in increments of two elements
539 /// let mut data = [1u8, 2, 3, 4, 5];
540 /// let mut ptr: *mut u8 = data.as_mut_ptr();
542 /// let end_rounded_up = ptr.wrapping_offset(6);
544 /// while ptr != end_rounded_up {
548 /// ptr = ptr.wrapping_offset(step);
550 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
552 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
553 #[must_use = "returns a new pointer rather than modifying its argument"]
554 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
556 pub const fn wrapping_offset(self, count: isize) -> *mut T
560 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
561 unsafe { intrinsics::arith_offset(self, count) as *mut T }
564 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
566 /// `count` is in units of **bytes**.
568 /// This is purely a convenience for casting to a `u8` pointer and
569 /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
570 /// for documentation.
572 /// For non-`Sized` pointees this operation changes only the data pointer,
573 /// leaving the metadata untouched.
576 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
577 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
578 pub const fn wrapping_byte_offset(self, count: isize) -> Self {
579 from_raw_parts_mut::<T>(
580 self.cast::<u8>().wrapping_offset(count).cast::<()>(),
585 /// Masks out bits of the pointer according to a mask.
587 /// This is convenience for `ptr.map_addr(|a| a & mask)`.
589 /// For non-`Sized` pointees this operation changes only the data pointer,
590 /// leaving the metadata untouched.
591 #[unstable(feature = "ptr_mask", issue = "98290")]
592 #[must_use = "returns a new pointer rather than modifying its argument"]
594 pub fn mask(self, mask: usize) -> *mut T {
595 let this = intrinsics::ptr_mask(self.cast::<()>(), mask) as *mut ();
596 from_raw_parts_mut::<T>(this, metadata(self))
599 /// Returns `None` if the pointer is null, or else returns a unique reference to
600 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
601 /// must be used instead.
603 /// For the shared counterpart see [`as_ref`].
605 /// [`as_uninit_mut`]: #method.as_uninit_mut
606 /// [`as_ref`]: #method.as_ref-1
610 /// When calling this method, you have to ensure that *either* the pointer is null *or*
611 /// all of the following is true:
613 /// * The pointer must be properly aligned.
615 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
617 /// * The pointer must point to an initialized instance of `T`.
619 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
620 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
621 /// In particular, while this reference exists, the memory the pointer points to must
622 /// not get accessed (read or written) through any other pointer.
624 /// This applies even if the result of this method is unused!
625 /// (The part about being initialized is not yet fully decided, but until
626 /// it is, the only safe approach is to ensure that they are indeed initialized.)
628 /// [the module documentation]: crate::ptr#safety
635 /// let mut s = [1, 2, 3];
636 /// let ptr: *mut u32 = s.as_mut_ptr();
637 /// let first_value = unsafe { ptr.as_mut().unwrap() };
638 /// *first_value = 4;
639 /// # assert_eq!(s, [4, 2, 3]);
640 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
643 /// # Null-unchecked version
645 /// If you are sure the pointer can never be null and are looking for some kind of
646 /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
647 /// you can dereference the pointer directly.
650 /// let mut s = [1, 2, 3];
651 /// let ptr: *mut u32 = s.as_mut_ptr();
652 /// let first_value = unsafe { &mut *ptr };
653 /// *first_value = 4;
654 /// # assert_eq!(s, [4, 2, 3]);
655 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
657 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
658 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
660 pub const unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
661 // SAFETY: the caller must guarantee that `self` is be valid for
662 // a mutable reference if it isn't null.
663 if self.is_null() { None } else { unsafe { Some(&mut *self) } }
666 /// Returns `None` if the pointer is null, or else returns a unique reference to
667 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
668 /// that the value has to be initialized.
670 /// For the shared counterpart see [`as_uninit_ref`].
672 /// [`as_mut`]: #method.as_mut
673 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
677 /// When calling this method, you have to ensure that *either* the pointer is null *or*
678 /// all of the following is true:
680 /// * The pointer must be properly aligned.
682 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
684 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
685 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
686 /// In particular, while this reference exists, the memory the pointer points to must
687 /// not get accessed (read or written) through any other pointer.
689 /// This applies even if the result of this method is unused!
691 /// [the module documentation]: crate::ptr#safety
693 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
694 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
695 pub const unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
699 // SAFETY: the caller must guarantee that `self` meets all the
700 // requirements for a reference.
701 if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
704 /// Returns whether two pointers are guaranteed to be equal.
706 /// At runtime this function behaves like `Some(self == other)`.
707 /// However, in some contexts (e.g., compile-time evaluation),
708 /// it is not always possible to determine equality of two pointers, so this function may
709 /// spuriously return `None` for pointers that later actually turn out to have its equality known.
710 /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
712 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
713 /// version and unsafe code must not
714 /// rely on the result of this function for soundness. It is suggested to only use this function
715 /// for performance optimizations where spurious `None` return values by this function do not
716 /// affect the outcome, but just the performance.
717 /// The consequences of using this method to make runtime and compile-time code behave
718 /// differently have not been explored. This method should not be used to introduce such
719 /// differences, and it should also not be stabilized before we have a better understanding
721 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
722 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
724 pub const fn guaranteed_eq(self, other: *mut T) -> Option<bool>
728 (self as *const T).guaranteed_eq(other as _)
731 /// Returns whether two pointers are guaranteed to be inequal.
733 /// At runtime this function behaves like `Some(self != other)`.
734 /// However, in some contexts (e.g., compile-time evaluation),
735 /// it is not always possible to determine inequality of two pointers, so this function may
736 /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
737 /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
739 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
740 /// version and unsafe code must not
741 /// rely on the result of this function for soundness. It is suggested to only use this function
742 /// for performance optimizations where spurious `None` return values by this function do not
743 /// affect the outcome, but just the performance.
744 /// The consequences of using this method to make runtime and compile-time code behave
745 /// differently have not been explored. This method should not be used to introduce such
746 /// differences, and it should also not be stabilized before we have a better understanding
748 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
749 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
751 pub const fn guaranteed_ne(self, other: *mut T) -> Option<bool>
755 (self as *const T).guaranteed_ne(other as _)
758 /// Calculates the distance between two pointers. The returned value is in
759 /// units of T: the distance in bytes divided by `mem::size_of::<T>()`.
761 /// This function is the inverse of [`offset`].
763 /// [`offset`]: #method.offset-1
767 /// If any of the following conditions are violated, the result is Undefined
770 /// * Both the starting and other pointer must be either in bounds or one
771 /// byte past the end of the same [allocated object].
773 /// * Both pointers must be *derived from* a pointer to the same object.
774 /// (See below for an example.)
776 /// * The distance between the pointers, in bytes, must be an exact multiple
777 /// of the size of `T`.
779 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
781 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
783 /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
784 /// address space, so two pointers within some value of any Rust type `T` will always satisfy
785 /// the last two conditions. The standard library also generally ensures that allocations
786 /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
787 /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
788 /// always satisfies the last two conditions.
790 /// Most platforms fundamentally can't even construct such a large allocation.
791 /// For instance, no known 64-bit platform can ever serve a request
792 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
793 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
794 /// more than `isize::MAX` bytes with things like Physical Address
795 /// Extension. As such, memory acquired directly from allocators or memory
796 /// mapped files *may* be too large to handle with this function.
797 /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
798 /// such large allocations either.)
800 /// [`add`]: #method.add
801 /// [allocated object]: crate::ptr#allocated-object
805 /// This function panics if `T` is a Zero-Sized Type ("ZST").
812 /// let mut a = [0; 5];
813 /// let ptr1: *mut i32 = &mut a[1];
814 /// let ptr2: *mut i32 = &mut a[3];
816 /// assert_eq!(ptr2.offset_from(ptr1), 2);
817 /// assert_eq!(ptr1.offset_from(ptr2), -2);
818 /// assert_eq!(ptr1.offset(2), ptr2);
819 /// assert_eq!(ptr2.offset(-2), ptr1);
823 /// *Incorrect* usage:
826 /// let ptr1 = Box::into_raw(Box::new(0u8));
827 /// let ptr2 = Box::into_raw(Box::new(1u8));
828 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
829 /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
830 /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff);
831 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
832 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
833 /// // computing their offset is undefined behavior, even though
834 /// // they point to the same address!
836 /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
839 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
840 #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
842 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
843 pub const unsafe fn offset_from(self, origin: *const T) -> isize
847 // SAFETY: the caller must uphold the safety contract for `offset_from`.
848 unsafe { (self as *const T).offset_from(origin) }
851 /// Calculates the distance between two pointers. The returned value is in
852 /// units of **bytes**.
854 /// This is purely a convenience for casting to a `u8` pointer and
855 /// using [offset_from][pointer::offset_from] on it. See that method for
856 /// documentation and safety requirements.
858 /// For non-`Sized` pointees this operation considers only the data pointers,
859 /// ignoring the metadata.
861 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
862 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
863 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
864 pub const unsafe fn byte_offset_from(self, origin: *const T) -> isize {
865 // SAFETY: the caller must uphold the safety contract for `offset_from`.
866 unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
869 /// Calculates the distance between two pointers, *where it's known that
870 /// `self` is equal to or greater than `origin`*. The returned value is in
871 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
873 /// This computes the same value that [`offset_from`](#method.offset_from)
874 /// would compute, but with the added precondition that the offset is
875 /// guaranteed to be non-negative. This method is equivalent to
876 /// `usize::from(self.offset_from(origin)).unwrap_unchecked()`,
877 /// but it provides slightly more information to the optimizer, which can
878 /// sometimes allow it to optimize slightly better with some backends.
880 /// This method can be though of as recovering the `count` that was passed
881 /// to [`add`](#method.add) (or, with the parameters in the other order,
882 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
883 /// that their safety preconditions are met:
885 /// # #![feature(ptr_sub_ptr)]
886 /// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool {
887 /// ptr.sub_ptr(origin) == count
889 /// origin.add(count) == ptr
891 /// ptr.sub(count) == origin
897 /// - The distance between the pointers must be non-negative (`self >= origin`)
899 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
900 /// apply to this method as well; see it for the full details.
902 /// Importantly, despite the return type of this method being able to represent
903 /// a larger offset, it's still *not permitted* to pass pointers which differ
904 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
905 /// always be less than or equal to `isize::MAX as usize`.
909 /// This function panics if `T` is a Zero-Sized Type ("ZST").
914 /// #![feature(ptr_sub_ptr)]
916 /// let mut a = [0; 5];
917 /// let p: *mut i32 = a.as_mut_ptr();
919 /// let ptr1: *mut i32 = p.add(1);
920 /// let ptr2: *mut i32 = p.add(3);
922 /// assert_eq!(ptr2.sub_ptr(ptr1), 2);
923 /// assert_eq!(ptr1.add(2), ptr2);
924 /// assert_eq!(ptr2.sub(2), ptr1);
925 /// assert_eq!(ptr2.sub_ptr(ptr2), 0);
928 /// // This would be incorrect, as the pointers are not correctly ordered:
929 /// // ptr1.offset_from(ptr2)
930 #[unstable(feature = "ptr_sub_ptr", issue = "95892")]
931 #[rustc_const_unstable(feature = "const_ptr_sub_ptr", issue = "95892")]
933 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
934 pub const unsafe fn sub_ptr(self, origin: *const T) -> usize
938 // SAFETY: the caller must uphold the safety contract for `sub_ptr`.
939 unsafe { (self as *const T).sub_ptr(origin) }
942 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
944 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
945 /// offset of `3 * size_of::<T>()` bytes.
949 /// If any of the following conditions are violated, the result is Undefined
952 /// * Both the starting and resulting pointer must be either in bounds or one
953 /// byte past the end of the same [allocated object].
955 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
957 /// * The offset being in bounds cannot rely on "wrapping around" the address
958 /// space. That is, the infinite-precision sum must fit in a `usize`.
960 /// The compiler and standard library generally tries to ensure allocations
961 /// never reach a size where an offset is a concern. For instance, `Vec`
962 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
963 /// `vec.as_ptr().add(vec.len())` is always safe.
965 /// Most platforms fundamentally can't even construct such an allocation.
966 /// For instance, no known 64-bit platform can ever serve a request
967 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
968 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
969 /// more than `isize::MAX` bytes with things like Physical Address
970 /// Extension. As such, memory acquired directly from allocators or memory
971 /// mapped files *may* be too large to handle with this function.
973 /// Consider using [`wrapping_add`] instead if these constraints are
974 /// difficult to satisfy. The only advantage of this method is that it
975 /// enables more aggressive compiler optimizations.
977 /// [`wrapping_add`]: #method.wrapping_add
978 /// [allocated object]: crate::ptr#allocated-object
985 /// let s: &str = "123";
986 /// let ptr: *const u8 = s.as_ptr();
989 /// println!("{}", *ptr.add(1) as char);
990 /// println!("{}", *ptr.add(2) as char);
993 #[stable(feature = "pointer_methods", since = "1.26.0")]
994 #[must_use = "returns a new pointer rather than modifying its argument"]
995 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
997 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
998 pub const unsafe fn add(self, count: usize) -> Self
1002 // SAFETY: the caller must uphold the safety contract for `offset`.
1003 unsafe { self.offset(count as isize) }
1006 /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
1008 /// `count` is in units of bytes.
1010 /// This is purely a convenience for casting to a `u8` pointer and
1011 /// using [add][pointer::add] on it. See that method for documentation
1012 /// and safety requirements.
1014 /// For non-`Sized` pointees this operation changes only the data pointer,
1015 /// leaving the metadata untouched.
1018 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1019 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1020 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1021 pub const unsafe fn byte_add(self, count: usize) -> Self {
1022 // SAFETY: the caller must uphold the safety contract for `add`.
1023 let this = unsafe { self.cast::<u8>().add(count).cast::<()>() };
1024 from_raw_parts_mut::<T>(this, metadata(self))
1027 /// Calculates the offset from a pointer (convenience for
1028 /// `.offset((count as isize).wrapping_neg())`).
1030 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1031 /// offset of `3 * size_of::<T>()` bytes.
1035 /// If any of the following conditions are violated, the result is Undefined
1038 /// * Both the starting and resulting pointer must be either in bounds or one
1039 /// byte past the end of the same [allocated object].
1041 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1043 /// * The offset being in bounds cannot rely on "wrapping around" the address
1044 /// space. That is, the infinite-precision sum must fit in a usize.
1046 /// The compiler and standard library generally tries to ensure allocations
1047 /// never reach a size where an offset is a concern. For instance, `Vec`
1048 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1049 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1051 /// Most platforms fundamentally can't even construct such an allocation.
1052 /// For instance, no known 64-bit platform can ever serve a request
1053 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1054 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1055 /// more than `isize::MAX` bytes with things like Physical Address
1056 /// Extension. As such, memory acquired directly from allocators or memory
1057 /// mapped files *may* be too large to handle with this function.
1059 /// Consider using [`wrapping_sub`] instead if these constraints are
1060 /// difficult to satisfy. The only advantage of this method is that it
1061 /// enables more aggressive compiler optimizations.
1063 /// [`wrapping_sub`]: #method.wrapping_sub
1064 /// [allocated object]: crate::ptr#allocated-object
1071 /// let s: &str = "123";
1074 /// let end: *const u8 = s.as_ptr().add(3);
1075 /// println!("{}", *end.sub(1) as char);
1076 /// println!("{}", *end.sub(2) as char);
1079 #[stable(feature = "pointer_methods", since = "1.26.0")]
1080 #[must_use = "returns a new pointer rather than modifying its argument"]
1081 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1083 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1084 pub const unsafe fn sub(self, count: usize) -> Self
1088 // SAFETY: the caller must uphold the safety contract for `offset`.
1089 unsafe { self.offset((count as isize).wrapping_neg()) }
1092 /// Calculates the offset from a pointer in bytes (convenience for
1093 /// `.byte_offset((count as isize).wrapping_neg())`).
1095 /// `count` is in units of bytes.
1097 /// This is purely a convenience for casting to a `u8` pointer and
1098 /// using [sub][pointer::sub] on it. See that method for documentation
1099 /// and safety requirements.
1101 /// For non-`Sized` pointees this operation changes only the data pointer,
1102 /// leaving the metadata untouched.
1105 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1106 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1107 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1108 pub const unsafe fn byte_sub(self, count: usize) -> Self {
1109 // SAFETY: the caller must uphold the safety contract for `sub`.
1110 let this = unsafe { self.cast::<u8>().sub(count).cast::<()>() };
1111 from_raw_parts_mut::<T>(this, metadata(self))
1114 /// Calculates the offset from a pointer using wrapping arithmetic.
1115 /// (convenience for `.wrapping_offset(count as isize)`)
1117 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1118 /// offset of `3 * size_of::<T>()` bytes.
1122 /// This operation itself is always safe, but using the resulting pointer is not.
1124 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1125 /// be used to read or write other allocated objects.
1127 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1128 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1129 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1130 /// `x` and `y` point into the same allocated object.
1132 /// Compared to [`add`], this method basically delays the requirement of staying within the
1133 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
1134 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1135 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1136 /// can be optimized better and is thus preferable in performance-sensitive code.
1138 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1139 /// intermediate values used during the computation of the final result. For example,
1140 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1141 /// allocated object and then re-entering it later is permitted.
1143 /// [`add`]: #method.add
1144 /// [allocated object]: crate::ptr#allocated-object
1151 /// // Iterate using a raw pointer in increments of two elements
1152 /// let data = [1u8, 2, 3, 4, 5];
1153 /// let mut ptr: *const u8 = data.as_ptr();
1155 /// let end_rounded_up = ptr.wrapping_add(6);
1157 /// // This loop prints "1, 3, 5, "
1158 /// while ptr != end_rounded_up {
1160 /// print!("{}, ", *ptr);
1162 /// ptr = ptr.wrapping_add(step);
1165 #[stable(feature = "pointer_methods", since = "1.26.0")]
1166 #[must_use = "returns a new pointer rather than modifying its argument"]
1167 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1169 pub const fn wrapping_add(self, count: usize) -> Self
1173 self.wrapping_offset(count as isize)
1176 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1177 /// (convenience for `.wrapping_byte_offset(count as isize)`)
1179 /// `count` is in units of bytes.
1181 /// This is purely a convenience for casting to a `u8` pointer and
1182 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1184 /// For non-`Sized` pointees this operation changes only the data pointer,
1185 /// leaving the metadata untouched.
1188 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1189 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1190 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1191 from_raw_parts_mut::<T>(self.cast::<u8>().wrapping_add(count).cast::<()>(), metadata(self))
1194 /// Calculates the offset from a pointer using wrapping arithmetic.
1195 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1197 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1198 /// offset of `3 * size_of::<T>()` bytes.
1202 /// This operation itself is always safe, but using the resulting pointer is not.
1204 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1205 /// be used to read or write other allocated objects.
1207 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1208 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1209 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1210 /// `x` and `y` point into the same allocated object.
1212 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1213 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
1214 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1215 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1216 /// can be optimized better and is thus preferable in performance-sensitive code.
1218 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1219 /// intermediate values used during the computation of the final result. For example,
1220 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1221 /// allocated object and then re-entering it later is permitted.
1223 /// [`sub`]: #method.sub
1224 /// [allocated object]: crate::ptr#allocated-object
1231 /// // Iterate using a raw pointer in increments of two elements (backwards)
1232 /// let data = [1u8, 2, 3, 4, 5];
1233 /// let mut ptr: *const u8 = data.as_ptr();
1234 /// let start_rounded_down = ptr.wrapping_sub(2);
1235 /// ptr = ptr.wrapping_add(4);
1237 /// // This loop prints "5, 3, 1, "
1238 /// while ptr != start_rounded_down {
1240 /// print!("{}, ", *ptr);
1242 /// ptr = ptr.wrapping_sub(step);
1245 #[stable(feature = "pointer_methods", since = "1.26.0")]
1246 #[must_use = "returns a new pointer rather than modifying its argument"]
1247 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1249 pub const fn wrapping_sub(self, count: usize) -> Self
1253 self.wrapping_offset((count as isize).wrapping_neg())
1256 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1257 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1259 /// `count` is in units of bytes.
1261 /// This is purely a convenience for casting to a `u8` pointer and
1262 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1264 /// For non-`Sized` pointees this operation changes only the data pointer,
1265 /// leaving the metadata untouched.
1268 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1269 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1270 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1271 from_raw_parts_mut::<T>(self.cast::<u8>().wrapping_sub(count).cast::<()>(), metadata(self))
1274 /// Reads the value from `self` without moving it. This leaves the
1275 /// memory in `self` unchanged.
1277 /// See [`ptr::read`] for safety concerns and examples.
1279 /// [`ptr::read`]: crate::ptr::read()
1280 #[stable(feature = "pointer_methods", since = "1.26.0")]
1281 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1283 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1284 pub const unsafe fn read(self) -> T
1288 // SAFETY: the caller must uphold the safety contract for ``.
1289 unsafe { read(self) }
1292 /// Performs a volatile read of the value from `self` without moving it. This
1293 /// leaves the memory in `self` unchanged.
1295 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1296 /// to not be elided or reordered by the compiler across other volatile
1299 /// See [`ptr::read_volatile`] for safety concerns and examples.
1301 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1302 #[stable(feature = "pointer_methods", since = "1.26.0")]
1304 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1305 pub unsafe fn read_volatile(self) -> T
1309 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1310 unsafe { read_volatile(self) }
1313 /// Reads the value from `self` without moving it. This leaves the
1314 /// memory in `self` unchanged.
1316 /// Unlike `read`, the pointer may be unaligned.
1318 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1320 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1321 #[stable(feature = "pointer_methods", since = "1.26.0")]
1322 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1324 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1325 pub const unsafe fn read_unaligned(self) -> T
1329 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1330 unsafe { read_unaligned(self) }
1333 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1334 /// and destination may overlap.
1336 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1338 /// See [`ptr::copy`] for safety concerns and examples.
1340 /// [`ptr::copy`]: crate::ptr::copy()
1341 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1342 #[stable(feature = "pointer_methods", since = "1.26.0")]
1344 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1345 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1349 // SAFETY: the caller must uphold the safety contract for `copy`.
1350 unsafe { copy(self, dest, count) }
1353 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1354 /// and destination may *not* overlap.
1356 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1358 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1360 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1361 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1362 #[stable(feature = "pointer_methods", since = "1.26.0")]
1364 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1365 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1369 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1370 unsafe { copy_nonoverlapping(self, dest, count) }
1373 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1374 /// and destination may overlap.
1376 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1378 /// See [`ptr::copy`] for safety concerns and examples.
1380 /// [`ptr::copy`]: crate::ptr::copy()
1381 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1382 #[stable(feature = "pointer_methods", since = "1.26.0")]
1384 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1385 pub const unsafe fn copy_from(self, src: *const T, count: usize)
1389 // SAFETY: the caller must uphold the safety contract for `copy`.
1390 unsafe { copy(src, self, count) }
1393 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1394 /// and destination may *not* overlap.
1396 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1398 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1400 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1401 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1402 #[stable(feature = "pointer_methods", since = "1.26.0")]
1404 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1405 pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1409 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1410 unsafe { copy_nonoverlapping(src, self, count) }
1413 /// Executes the destructor (if any) of the pointed-to value.
1415 /// See [`ptr::drop_in_place`] for safety concerns and examples.
1417 /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1418 #[stable(feature = "pointer_methods", since = "1.26.0")]
1420 pub unsafe fn drop_in_place(self) {
1421 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1422 unsafe { drop_in_place(self) }
1425 /// Overwrites a memory location with the given value without reading or
1426 /// dropping the old value.
1428 /// See [`ptr::write`] for safety concerns and examples.
1430 /// [`ptr::write`]: crate::ptr::write()
1431 #[stable(feature = "pointer_methods", since = "1.26.0")]
1432 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1434 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1435 pub const unsafe fn write(self, val: T)
1439 // SAFETY: the caller must uphold the safety contract for `write`.
1440 unsafe { write(self, val) }
1443 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1444 /// bytes of memory starting at `self` to `val`.
1446 /// See [`ptr::write_bytes`] for safety concerns and examples.
1448 /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1449 #[doc(alias = "memset")]
1450 #[stable(feature = "pointer_methods", since = "1.26.0")]
1451 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1453 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1454 pub const unsafe fn write_bytes(self, val: u8, count: usize)
1458 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1459 unsafe { write_bytes(self, val, count) }
1462 /// Performs a volatile write of a memory location with the given value without
1463 /// reading or dropping the old value.
1465 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1466 /// to not be elided or reordered by the compiler across other volatile
1469 /// See [`ptr::write_volatile`] for safety concerns and examples.
1471 /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1472 #[stable(feature = "pointer_methods", since = "1.26.0")]
1474 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1475 pub unsafe fn write_volatile(self, val: T)
1479 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1480 unsafe { write_volatile(self, val) }
1483 /// Overwrites a memory location with the given value without reading or
1484 /// dropping the old value.
1486 /// Unlike `write`, the pointer may be unaligned.
1488 /// See [`ptr::write_unaligned`] for safety concerns and examples.
1490 /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1491 #[stable(feature = "pointer_methods", since = "1.26.0")]
1492 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1494 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1495 pub const unsafe fn write_unaligned(self, val: T)
1499 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1500 unsafe { write_unaligned(self, val) }
1503 /// Replaces the value at `self` with `src`, returning the old
1504 /// value, without dropping either.
1506 /// See [`ptr::replace`] for safety concerns and examples.
1508 /// [`ptr::replace`]: crate::ptr::replace()
1509 #[stable(feature = "pointer_methods", since = "1.26.0")]
1511 pub unsafe fn replace(self, src: T) -> T
1515 // SAFETY: the caller must uphold the safety contract for `replace`.
1516 unsafe { replace(self, src) }
1519 /// Swaps the values at two mutable locations of the same type, without
1520 /// deinitializing either. They may overlap, unlike `mem::swap` which is
1521 /// otherwise equivalent.
1523 /// See [`ptr::swap`] for safety concerns and examples.
1525 /// [`ptr::swap`]: crate::ptr::swap()
1526 #[stable(feature = "pointer_methods", since = "1.26.0")]
1527 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
1529 pub const unsafe fn swap(self, with: *mut T)
1533 // SAFETY: the caller must uphold the safety contract for `swap`.
1534 unsafe { swap(self, with) }
1537 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1540 /// If it is not possible to align the pointer, the implementation returns
1541 /// `usize::MAX`. It is permissible for the implementation to *always*
1542 /// return `usize::MAX`. Only your algorithm's performance can depend
1543 /// on getting a usable offset here, not its correctness.
1545 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1546 /// used with the `wrapping_add` method.
1548 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1549 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1550 /// the returned offset is correct in all terms other than alignment.
1554 /// The function panics if `align` is not a power-of-two.
1558 /// Accessing adjacent `u8` as `u16`
1561 /// use std::mem::align_of;
1564 /// let mut x = [5_u8, 6, 7, 8, 9];
1565 /// let ptr = x.as_mut_ptr();
1566 /// let offset = ptr.align_offset(align_of::<u16>());
1568 /// if offset < x.len() - 1 {
1569 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1572 /// assert!(x == [0, 0, 7, 8, 9] || x == [5, 0, 0, 8, 9]);
1574 /// // while the pointer can be aligned via `offset`, it would point
1575 /// // outside the allocation
1579 #[stable(feature = "align_offset", since = "1.36.0")]
1580 #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1581 pub const fn align_offset(self, align: usize) -> usize
1585 if !align.is_power_of_two() {
1586 panic!("align_offset: align is not a power-of-two");
1589 fn rt_impl<T>(p: *mut T, align: usize) -> usize {
1590 // SAFETY: `align` has been checked to be a power of 2 above
1591 unsafe { align_offset(p, align) }
1594 const fn ctfe_impl<T>(_: *mut T, _: usize) -> usize {
1599 // It is permissible for `align_offset` to always return `usize::MAX`,
1600 // algorithm correctness can not depend on `align_offset` returning non-max values.
1602 // As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
1603 unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
1606 /// Returns whether the pointer is properly aligned for `T`.
1609 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1610 pub fn is_aligned(self) -> bool
1614 self.is_aligned_to(core::mem::align_of::<T>())
1617 /// Returns whether the pointer is aligned to `align`.
1619 /// For non-`Sized` pointees this operation considers only the data pointer,
1620 /// ignoring the metadata.
1624 /// The function panics if `align` is not a power-of-two (this includes 0).
1627 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1628 pub fn is_aligned_to(self, align: usize) -> bool {
1629 if !align.is_power_of_two() {
1630 panic!("is_aligned_to: align is not a power-of-two");
1633 // Cast is needed for `T: !Sized`
1634 self.cast::<u8>().addr() & align - 1 == 0
1639 /// Returns the length of a raw slice.
1641 /// The returned value is the number of **elements**, not the number of bytes.
1643 /// This function is safe, even when the raw slice cannot be cast to a slice
1644 /// reference because the pointer is null or unaligned.
1649 /// #![feature(slice_ptr_len)]
1652 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1653 /// assert_eq!(slice.len(), 3);
1656 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1657 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1658 pub const fn len(self) -> usize {
1662 /// Returns `true` if the raw slice has a length of 0.
1667 /// #![feature(slice_ptr_len)]
1669 /// let mut a = [1, 2, 3];
1670 /// let ptr = &mut a as *mut [_];
1671 /// assert!(!ptr.is_empty());
1674 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1675 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1676 pub const fn is_empty(self) -> bool {
1680 /// Divides one mutable raw slice into two at an index.
1682 /// The first will contain all indices from `[0, mid)` (excluding
1683 /// the index `mid` itself) and the second will contain all
1684 /// indices from `[mid, len)` (excluding the index `len` itself).
1688 /// Panics if `mid > len`.
1692 /// `mid` must be [in-bounds] of the underlying [allocated object].
1693 /// Which means `self` must be dereferenceable and span a single allocation
1694 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1695 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1697 /// Since `len` being in-bounds it is not a safety invariant of `*mut [T]` the
1698 /// safety requirements of this method are the same as for [`split_at_mut_unchecked`].
1699 /// The explicit bounds check is only as useful as `len` is correct.
1701 /// [`split_at_mut_unchecked`]: #method.split_at_mut_unchecked
1702 /// [in-bounds]: #method.add
1703 /// [allocated object]: crate::ptr#allocated-object
1704 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1709 /// #![feature(raw_slice_split)]
1710 /// #![feature(slice_ptr_get)]
1712 /// let mut v = [1, 0, 3, 0, 5, 6];
1713 /// let ptr = &mut v as *mut [_];
1715 /// let (left, right) = ptr.split_at_mut(2);
1716 /// assert_eq!(&*left, [1, 0]);
1717 /// assert_eq!(&*right, [3, 0, 5, 6]);
1722 #[unstable(feature = "raw_slice_split", issue = "95595")]
1723 pub unsafe fn split_at_mut(self, mid: usize) -> (*mut [T], *mut [T]) {
1724 assert!(mid <= self.len());
1725 // SAFETY: The assert above is only a safety-net as long as `self.len()` is correct
1726 // The actual safety requirements of this function are the same as for `split_at_mut_unchecked`
1727 unsafe { self.split_at_mut_unchecked(mid) }
1730 /// Divides one mutable raw slice into two at an index, without doing bounds checking.
1732 /// The first will contain all indices from `[0, mid)` (excluding
1733 /// the index `mid` itself) and the second will contain all
1734 /// indices from `[mid, len)` (excluding the index `len` itself).
1738 /// `mid` must be [in-bounds] of the underlying [allocated object].
1739 /// Which means `self` must be dereferenceable and span a single allocation
1740 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1741 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1743 /// [in-bounds]: #method.add
1744 /// [out-of-bounds index]: #method.add
1745 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1750 /// #![feature(raw_slice_split)]
1752 /// let mut v = [1, 0, 3, 0, 5, 6];
1753 /// // scoped to restrict the lifetime of the borrows
1755 /// let ptr = &mut v as *mut [_];
1756 /// let (left, right) = ptr.split_at_mut_unchecked(2);
1757 /// assert_eq!(&*left, [1, 0]);
1758 /// assert_eq!(&*right, [3, 0, 5, 6]);
1759 /// (&mut *left)[1] = 2;
1760 /// (&mut *right)[1] = 4;
1762 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1765 #[unstable(feature = "raw_slice_split", issue = "95595")]
1766 pub unsafe fn split_at_mut_unchecked(self, mid: usize) -> (*mut [T], *mut [T]) {
1767 let len = self.len();
1768 let ptr = self.as_mut_ptr();
1770 // SAFETY: Caller must pass a valid pointer and an index that is in-bounds.
1771 let tail = unsafe { ptr.add(mid) };
1773 crate::ptr::slice_from_raw_parts_mut(ptr, mid),
1774 crate::ptr::slice_from_raw_parts_mut(tail, len - mid),
1778 /// Returns a raw pointer to the slice's buffer.
1780 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
1785 /// #![feature(slice_ptr_get)]
1788 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1789 /// assert_eq!(slice.as_mut_ptr(), ptr::null_mut());
1792 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1793 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
1794 pub const fn as_mut_ptr(self) -> *mut T {
1798 /// Returns a raw pointer to an element or subslice, without doing bounds
1801 /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
1802 /// is *[undefined behavior]* even if the resulting pointer is not used.
1804 /// [out-of-bounds index]: #method.add
1805 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1810 /// #![feature(slice_ptr_get)]
1812 /// let x = &mut [1, 2, 4] as *mut [i32];
1815 /// assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
1818 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1819 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
1821 pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
1823 I: ~const SliceIndex<[T]>,
1825 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1826 unsafe { index.get_unchecked_mut(self) }
1829 /// Returns `None` if the pointer is null, or else returns a shared slice to
1830 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1831 /// that the value has to be initialized.
1833 /// For the mutable counterpart see [`as_uninit_slice_mut`].
1835 /// [`as_ref`]: #method.as_ref-1
1836 /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
1840 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1841 /// all of the following is true:
1843 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1844 /// and it must be properly aligned. This means in particular:
1846 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1847 /// Slices can never span across multiple allocated objects.
1849 /// * The pointer must be aligned even for zero-length slices. One
1850 /// reason for this is that enum layout optimizations may rely on references
1851 /// (including slices of any length) being aligned and non-null to distinguish
1852 /// them from other data. You can obtain a pointer that is usable as `data`
1853 /// for zero-length slices using [`NonNull::dangling()`].
1855 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1856 /// See the safety documentation of [`pointer::offset`].
1858 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1859 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1860 /// In particular, while this reference exists, the memory the pointer points to must
1861 /// not get mutated (except inside `UnsafeCell`).
1863 /// This applies even if the result of this method is unused!
1865 /// See also [`slice::from_raw_parts`][].
1867 /// [valid]: crate::ptr#safety
1868 /// [allocated object]: crate::ptr#allocated-object
1870 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1871 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1872 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1876 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1877 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1881 /// Returns `None` if the pointer is null, or else returns a unique slice to
1882 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
1883 /// that the value has to be initialized.
1885 /// For the shared counterpart see [`as_uninit_slice`].
1887 /// [`as_mut`]: #method.as_mut
1888 /// [`as_uninit_slice`]: #method.as_uninit_slice-1
1892 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1893 /// all of the following is true:
1895 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
1896 /// many bytes, and it must be properly aligned. This means in particular:
1898 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1899 /// Slices can never span across multiple allocated objects.
1901 /// * The pointer must be aligned even for zero-length slices. One
1902 /// reason for this is that enum layout optimizations may rely on references
1903 /// (including slices of any length) being aligned and non-null to distinguish
1904 /// them from other data. You can obtain a pointer that is usable as `data`
1905 /// for zero-length slices using [`NonNull::dangling()`].
1907 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1908 /// See the safety documentation of [`pointer::offset`].
1910 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1911 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1912 /// In particular, while this reference exists, the memory the pointer points to must
1913 /// not get accessed (read or written) through any other pointer.
1915 /// This applies even if the result of this method is unused!
1917 /// See also [`slice::from_raw_parts_mut`][].
1919 /// [valid]: crate::ptr#safety
1920 /// [allocated object]: crate::ptr#allocated-object
1922 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1923 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1924 pub const unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
1928 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
1929 Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
1934 // Equality for pointers
1935 #[stable(feature = "rust1", since = "1.0.0")]
1936 impl<T: ?Sized> PartialEq for *mut T {
1938 fn eq(&self, other: &*mut T) -> bool {
1943 #[stable(feature = "rust1", since = "1.0.0")]
1944 impl<T: ?Sized> Eq for *mut T {}
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 impl<T: ?Sized> Ord for *mut T {
1949 fn cmp(&self, other: &*mut T) -> Ordering {
1952 } else if self == other {
1960 #[stable(feature = "rust1", since = "1.0.0")]
1961 impl<T: ?Sized> PartialOrd for *mut T {
1963 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
1964 Some(self.cmp(other))
1968 fn lt(&self, other: &*mut T) -> bool {
1973 fn le(&self, other: &*mut T) -> bool {
1978 fn gt(&self, other: &*mut T) -> bool {
1983 fn ge(&self, other: &*mut T) -> bool {