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, mut val: *mut U) -> *mut U
87 let target = &mut val as *mut *mut U as *mut *mut u8;
88 // SAFETY: In case of a thin pointer, this operations is identical
89 // to a simple assignment. In case of a fat pointer, with the current
90 // fat pointer layout implementation, the first field of such a
91 // pointer is always the data pointer, which is likewise assigned.
92 unsafe { *target = self as *mut u8 };
96 /// Changes constness without changing the type.
98 /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
101 /// While not strictly required (`*mut T` coerces to `*const T`), this is provided for symmetry
102 /// with [`cast_mut`] on `*const T` and may have documentation value if used instead of implicit
105 /// [`cast_mut`]: #method.cast_mut
106 #[stable(feature = "ptr_const_cast", since = "1.65.0")]
107 #[rustc_const_stable(feature = "ptr_const_cast", since = "1.65.0")]
108 pub const fn cast_const(self) -> *const T {
112 /// Casts a pointer to its raw bits.
114 /// This is equivalent to `as usize`, but is more specific to enhance readability.
115 /// The inverse method is [`from_bits`](#method.from_bits-1).
117 /// In particular, `*p as usize` and `p as usize` will both compile for
118 /// pointers to numeric types but do very different things, so using this
119 /// helps emphasize that reading the bits was intentional.
124 /// #![feature(ptr_to_from_bits)]
125 /// let mut array = [13, 42];
126 /// let mut it = array.iter_mut();
127 /// let p0: *mut i32 = it.next().unwrap();
128 /// assert_eq!(<*mut _>::from_bits(p0.to_bits()), p0);
129 /// let p1: *mut i32 = it.next().unwrap();
130 /// assert_eq!(p1.to_bits() - p0.to_bits(), 4);
132 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
133 pub fn to_bits(self) -> usize
140 /// Creates a pointer from its raw bits.
142 /// This is equivalent to `as *mut T`, but is more specific to enhance readability.
143 /// The inverse method is [`to_bits`](#method.to_bits-1).
148 /// #![feature(ptr_to_from_bits)]
149 /// use std::ptr::NonNull;
150 /// let dangling: *mut u8 = NonNull::dangling().as_ptr();
151 /// assert_eq!(<*mut u8>::from_bits(1), dangling);
153 #[unstable(feature = "ptr_to_from_bits", issue = "91126")]
154 pub fn from_bits(bits: usize) -> Self
161 /// Gets the "address" portion of the pointer.
163 /// This is similar to `self as usize`, which semantically discards *provenance* and
164 /// *address-space* information. However, unlike `self as usize`, casting the returned address
165 /// back to a pointer yields [`invalid`][], which is undefined behavior to dereference. To
166 /// properly restore the lost information and obtain a dereferenceable pointer, use
167 /// [`with_addr`][pointer::with_addr] or [`map_addr`][pointer::map_addr].
169 /// If using those APIs is not possible because there is no way to preserve a pointer with the
170 /// required provenance, use [`expose_addr`][pointer::expose_addr] and
171 /// [`from_exposed_addr_mut`][from_exposed_addr_mut] instead. However, note that this makes
172 /// your code less portable and less amenable to tools that check for compliance with the Rust
175 /// On most platforms this will produce a value with the same bytes as the original
176 /// pointer, because all the bytes are dedicated to describing the address.
177 /// Platforms which need to store additional information in the pointer may
178 /// perform a change of representation to produce a value containing only the address
179 /// portion of the pointer. What that means is up to the platform to define.
181 /// This API and its claimed semantics are part of the Strict Provenance experiment, and as such
182 /// might change in the future (including possibly weakening this so it becomes wholly
183 /// equivalent to `self as usize`). See the [module documentation][crate::ptr] for details.
186 #[unstable(feature = "strict_provenance", issue = "95228")]
187 pub fn addr(self) -> usize
191 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
192 // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
194 unsafe { mem::transmute(self) }
197 /// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future
198 /// use in [`from_exposed_addr`][].
200 /// This is equivalent to `self as usize`, which semantically discards *provenance* and
201 /// *address-space* information. Furthermore, this (like the `as` cast) has the implicit
202 /// side-effect of marking the provenance as 'exposed', so on platforms that support it you can
203 /// later call [`from_exposed_addr_mut`][] to reconstitute the original pointer including its
204 /// provenance. (Reconstructing address space information, if required, is your responsibility.)
206 /// Using this method means that code is *not* following Strict Provenance rules. Supporting
207 /// [`from_exposed_addr_mut`][] complicates specification and reasoning and may not be supported
208 /// by tools that help you to stay conformant with the Rust memory model, so it is recommended
209 /// to use [`addr`][pointer::addr] wherever possible.
211 /// On most platforms this will produce a value with the same bytes as the original pointer,
212 /// because all the bytes are dedicated to describing the address. Platforms which need to store
213 /// additional information in the pointer may not support this operation, since the 'expose'
214 /// side-effect which is required for [`from_exposed_addr_mut`][] to work is typically not
217 /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
218 /// [module documentation][crate::ptr] for details.
220 /// [`from_exposed_addr_mut`]: from_exposed_addr_mut
223 #[unstable(feature = "strict_provenance", issue = "95228")]
224 pub fn expose_addr(self) -> usize
228 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
232 /// Creates a new pointer with the given address.
234 /// This performs the same operation as an `addr as ptr` cast, but copies
235 /// the *address-space* and *provenance* of `self` to the new pointer.
236 /// This allows us to dynamically preserve and propagate this important
237 /// information in a way that is otherwise impossible with a unary cast.
239 /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
240 /// `self` to the given address, and therefore has all the same capabilities and restrictions.
242 /// This API and its claimed semantics are part of the Strict Provenance experiment,
243 /// see the [module documentation][crate::ptr] for details.
246 #[unstable(feature = "strict_provenance", issue = "95228")]
247 pub fn with_addr(self, addr: usize) -> Self
251 // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
253 // In the mean-time, this operation is defined to be "as if" it was
254 // a wrapping_offset, so we can emulate it as such. This should properly
255 // restore pointer provenance even under today's compiler.
256 let self_addr = self.addr() as isize;
257 let dest_addr = addr as isize;
258 let offset = dest_addr.wrapping_sub(self_addr);
260 // This is the canonical desugarring of this operation
261 self.wrapping_byte_offset(offset)
264 /// Creates a new pointer by mapping `self`'s address to a new one.
266 /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
268 /// This API and its claimed semantics are part of the Strict Provenance experiment,
269 /// see the [module documentation][crate::ptr] for details.
272 #[unstable(feature = "strict_provenance", issue = "95228")]
273 pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self
277 self.with_addr(f(self.addr()))
280 /// Decompose a (possibly wide) pointer into its address and metadata components.
282 /// The pointer can be later reconstructed with [`from_raw_parts_mut`].
283 #[unstable(feature = "ptr_metadata", issue = "81513")]
284 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
286 pub const fn to_raw_parts(self) -> (*mut (), <T as super::Pointee>::Metadata) {
287 (self.cast(), super::metadata(self))
290 /// Returns `None` if the pointer is null, or else returns a shared reference to
291 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
292 /// must be used instead.
294 /// For the mutable counterpart see [`as_mut`].
296 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
297 /// [`as_mut`]: #method.as_mut
301 /// When calling this method, you have to ensure that *either* the pointer is null *or*
302 /// all of the following is true:
304 /// * The pointer must be properly aligned.
306 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
308 /// * The pointer must point to an initialized instance of `T`.
310 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
311 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
312 /// In particular, while this reference exists, the memory the pointer points to must
313 /// not get mutated (except inside `UnsafeCell`).
315 /// This applies even if the result of this method is unused!
316 /// (The part about being initialized is not yet fully decided, but until
317 /// it is, the only safe approach is to ensure that they are indeed initialized.)
319 /// [the module documentation]: crate::ptr#safety
326 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
329 /// if let Some(val_back) = ptr.as_ref() {
330 /// println!("We got back the value: {val_back}!");
335 /// # Null-unchecked version
337 /// If you are sure the pointer can never be null and are looking for some kind of
338 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
339 /// dereference the pointer directly.
342 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
345 /// let val_back = &*ptr;
346 /// println!("We got back the value: {val_back}!");
349 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
350 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
352 pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
353 // SAFETY: the caller must guarantee that `self` is valid for a
354 // reference if it isn't null.
355 if self.is_null() { None } else { unsafe { Some(&*self) } }
358 /// Returns `None` if the pointer is null, or else returns a shared reference to
359 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
360 /// that the value has to be initialized.
362 /// For the mutable counterpart see [`as_uninit_mut`].
364 /// [`as_ref`]: #method.as_ref-1
365 /// [`as_uninit_mut`]: #method.as_uninit_mut
369 /// When calling this method, you have to ensure that *either* the pointer is null *or*
370 /// all of the following is true:
372 /// * The pointer must be properly aligned.
374 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
376 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
377 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
378 /// In particular, while this reference exists, the memory the pointer points to must
379 /// not get mutated (except inside `UnsafeCell`).
381 /// This applies even if the result of this method is unused!
383 /// [the module documentation]: crate::ptr#safety
390 /// #![feature(ptr_as_uninit)]
392 /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
395 /// if let Some(val_back) = ptr.as_uninit_ref() {
396 /// println!("We got back the value: {}!", val_back.assume_init());
401 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
402 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
403 pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
407 // SAFETY: the caller must guarantee that `self` meets all the
408 // requirements for a reference.
409 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
412 /// Calculates the offset from a pointer.
414 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
415 /// offset of `3 * size_of::<T>()` bytes.
419 /// If any of the following conditions are violated, the result is Undefined
422 /// * Both the starting and resulting pointer must be either in bounds or one
423 /// byte past the end of the same [allocated object].
425 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
427 /// * The offset being in bounds cannot rely on "wrapping around" the address
428 /// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
430 /// The compiler and standard library generally tries to ensure allocations
431 /// never reach a size where an offset is a concern. For instance, `Vec`
432 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
433 /// `vec.as_ptr().add(vec.len())` is always safe.
435 /// Most platforms fundamentally can't even construct such an allocation.
436 /// For instance, no known 64-bit platform can ever serve a request
437 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
438 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
439 /// more than `isize::MAX` bytes with things like Physical Address
440 /// Extension. As such, memory acquired directly from allocators or memory
441 /// mapped files *may* be too large to handle with this function.
443 /// Consider using [`wrapping_offset`] instead if these constraints are
444 /// difficult to satisfy. The only advantage of this method is that it
445 /// enables more aggressive compiler optimizations.
447 /// [`wrapping_offset`]: #method.wrapping_offset
448 /// [allocated object]: crate::ptr#allocated-object
455 /// let mut s = [1, 2, 3];
456 /// let ptr: *mut u32 = s.as_mut_ptr();
459 /// println!("{}", *ptr.offset(1));
460 /// println!("{}", *ptr.offset(2));
463 #[stable(feature = "rust1", since = "1.0.0")]
464 #[must_use = "returns a new pointer rather than modifying its argument"]
465 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
467 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
468 pub const unsafe fn offset(self, count: isize) -> *mut T
472 // SAFETY: the caller must uphold the safety contract for `offset`.
473 // The obtained pointer is valid for writes since the caller must
474 // guarantee that it points to the same allocated object as `self`.
475 unsafe { intrinsics::offset(self, count) as *mut T }
478 /// Calculates the offset from a pointer in bytes.
480 /// `count` is in units of **bytes**.
482 /// This is purely a convenience for casting to a `u8` pointer and
483 /// using [offset][pointer::offset] on it. See that method for documentation
484 /// and safety requirements.
486 /// For non-`Sized` pointees this operation changes only the data pointer,
487 /// leaving the metadata untouched.
490 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
491 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
492 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
493 pub const unsafe fn byte_offset(self, count: isize) -> Self {
494 // SAFETY: the caller must uphold the safety contract for `offset`.
495 let this = unsafe { self.cast::<u8>().offset(count).cast::<()>() };
496 from_raw_parts_mut::<T>(this, metadata(self))
499 /// Calculates the offset from a pointer using wrapping arithmetic.
500 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
501 /// offset of `3 * size_of::<T>()` bytes.
505 /// This operation itself is always safe, but using the resulting pointer is not.
507 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
508 /// be used to read or write other allocated objects.
510 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
511 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
512 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
513 /// `x` and `y` point into the same allocated object.
515 /// Compared to [`offset`], this method basically delays the requirement of staying within the
516 /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
517 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
518 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
519 /// can be optimized better and is thus preferable in performance-sensitive code.
521 /// The delayed check only considers the value of the pointer that was dereferenced, not the
522 /// intermediate values used during the computation of the final result. For example,
523 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
524 /// words, leaving the allocated object and then re-entering it later is permitted.
526 /// [`offset`]: #method.offset
527 /// [allocated object]: crate::ptr#allocated-object
534 /// // Iterate using a raw pointer in increments of two elements
535 /// let mut data = [1u8, 2, 3, 4, 5];
536 /// let mut ptr: *mut u8 = data.as_mut_ptr();
538 /// let end_rounded_up = ptr.wrapping_offset(6);
540 /// while ptr != end_rounded_up {
544 /// ptr = ptr.wrapping_offset(step);
546 /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
548 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
549 #[must_use = "returns a new pointer rather than modifying its argument"]
550 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
552 pub const fn wrapping_offset(self, count: isize) -> *mut T
556 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
557 unsafe { intrinsics::arith_offset(self, count) as *mut T }
560 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
562 /// `count` is in units of **bytes**.
564 /// This is purely a convenience for casting to a `u8` pointer and
565 /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
566 /// for documentation.
568 /// For non-`Sized` pointees this operation changes only the data pointer,
569 /// leaving the metadata untouched.
572 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
573 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
574 pub const fn wrapping_byte_offset(self, count: isize) -> Self {
575 from_raw_parts_mut::<T>(
576 self.cast::<u8>().wrapping_offset(count).cast::<()>(),
581 /// Masks out bits of the pointer according to a mask.
583 /// This is convenience for `ptr.map_addr(|a| a & mask)`.
585 /// For non-`Sized` pointees this operation changes only the data pointer,
586 /// leaving the metadata untouched.
587 #[unstable(feature = "ptr_mask", issue = "98290")]
588 #[must_use = "returns a new pointer rather than modifying its argument"]
590 pub fn mask(self, mask: usize) -> *mut T {
591 let this = intrinsics::ptr_mask(self.cast::<()>(), mask) as *mut ();
592 from_raw_parts_mut::<T>(this, metadata(self))
595 /// Returns `None` if the pointer is null, or else returns a unique reference to
596 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
597 /// must be used instead.
599 /// For the shared counterpart see [`as_ref`].
601 /// [`as_uninit_mut`]: #method.as_uninit_mut
602 /// [`as_ref`]: #method.as_ref-1
606 /// When calling this method, you have to ensure that *either* the pointer is null *or*
607 /// all of the following is true:
609 /// * The pointer must be properly aligned.
611 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
613 /// * The pointer must point to an initialized instance of `T`.
615 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
616 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
617 /// In particular, while this reference exists, the memory the pointer points to must
618 /// not get accessed (read or written) through any other pointer.
620 /// This applies even if the result of this method is unused!
621 /// (The part about being initialized is not yet fully decided, but until
622 /// it is, the only safe approach is to ensure that they are indeed initialized.)
624 /// [the module documentation]: crate::ptr#safety
631 /// let mut s = [1, 2, 3];
632 /// let ptr: *mut u32 = s.as_mut_ptr();
633 /// let first_value = unsafe { ptr.as_mut().unwrap() };
634 /// *first_value = 4;
635 /// # assert_eq!(s, [4, 2, 3]);
636 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
639 /// # Null-unchecked version
641 /// If you are sure the pointer can never be null and are looking for some kind of
642 /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
643 /// you can dereference the pointer directly.
646 /// let mut s = [1, 2, 3];
647 /// let ptr: *mut u32 = s.as_mut_ptr();
648 /// let first_value = unsafe { &mut *ptr };
649 /// *first_value = 4;
650 /// # assert_eq!(s, [4, 2, 3]);
651 /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
653 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
654 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
656 pub const unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
657 // SAFETY: the caller must guarantee that `self` is be valid for
658 // a mutable reference if it isn't null.
659 if self.is_null() { None } else { unsafe { Some(&mut *self) } }
662 /// Returns `None` if the pointer is null, or else returns a unique reference to
663 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
664 /// that the value has to be initialized.
666 /// For the shared counterpart see [`as_uninit_ref`].
668 /// [`as_mut`]: #method.as_mut
669 /// [`as_uninit_ref`]: #method.as_uninit_ref-1
673 /// When calling this method, you have to ensure that *either* the pointer is null *or*
674 /// all of the following is true:
676 /// * The pointer must be properly aligned.
678 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
680 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
681 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
682 /// In particular, while this reference exists, the memory the pointer points to must
683 /// not get accessed (read or written) through any other pointer.
685 /// This applies even if the result of this method is unused!
687 /// [the module documentation]: crate::ptr#safety
689 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
690 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
691 pub const unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
695 // SAFETY: the caller must guarantee that `self` meets all the
696 // requirements for a reference.
697 if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
700 /// Returns whether two pointers are guaranteed to be equal.
702 /// At runtime this function behaves like `Some(self == other)`.
703 /// However, in some contexts (e.g., compile-time evaluation),
704 /// it is not always possible to determine equality of two pointers, so this function may
705 /// spuriously return `None` for pointers that later actually turn out to have its equality known.
706 /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
708 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
709 /// version and unsafe code must not
710 /// rely on the result of this function for soundness. It is suggested to only use this function
711 /// for performance optimizations where spurious `None` return values by this function do not
712 /// affect the outcome, but just the performance.
713 /// The consequences of using this method to make runtime and compile-time code behave
714 /// differently have not been explored. This method should not be used to introduce such
715 /// differences, and it should also not be stabilized before we have a better understanding
717 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
718 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
720 pub const fn guaranteed_eq(self, other: *mut T) -> Option<bool>
724 (self as *const T).guaranteed_eq(other as _)
727 /// Returns whether two pointers are guaranteed to be inequal.
729 /// At runtime this function behaves like `Some(self == other)`.
730 /// However, in some contexts (e.g., compile-time evaluation),
731 /// it is not always possible to determine inequality of two pointers, so this function may
732 /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
733 /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
735 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
736 /// version and unsafe code must not
737 /// rely on the result of this function for soundness. It is suggested to only use this function
738 /// for performance optimizations where spurious `None` return values by this function do not
739 /// affect the outcome, but just the performance.
740 /// The consequences of using this method to make runtime and compile-time code behave
741 /// differently have not been explored. This method should not be used to introduce such
742 /// differences, and it should also not be stabilized before we have a better understanding
744 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
745 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
747 pub const fn guaranteed_ne(self, other: *mut T) -> Option<bool>
751 (self as *const T).guaranteed_ne(other as _)
754 /// Calculates the distance between two pointers. The returned value is in
755 /// units of T: the distance in bytes divided by `mem::size_of::<T>()`.
757 /// This function is the inverse of [`offset`].
759 /// [`offset`]: #method.offset-1
763 /// If any of the following conditions are violated, the result is Undefined
766 /// * Both the starting and other pointer must be either in bounds or one
767 /// byte past the end of the same [allocated object].
769 /// * Both pointers must be *derived from* a pointer to the same object.
770 /// (See below for an example.)
772 /// * The distance between the pointers, in bytes, must be an exact multiple
773 /// of the size of `T`.
775 /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
777 /// * The distance being in bounds cannot rely on "wrapping around" the address space.
779 /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
780 /// address space, so two pointers within some value of any Rust type `T` will always satisfy
781 /// the last two conditions. The standard library also generally ensures that allocations
782 /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
783 /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
784 /// always satisfies the last two conditions.
786 /// Most platforms fundamentally can't even construct such a large allocation.
787 /// For instance, no known 64-bit platform can ever serve a request
788 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
789 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
790 /// more than `isize::MAX` bytes with things like Physical Address
791 /// Extension. As such, memory acquired directly from allocators or memory
792 /// mapped files *may* be too large to handle with this function.
793 /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
794 /// such large allocations either.)
796 /// [`add`]: #method.add
797 /// [allocated object]: crate::ptr#allocated-object
801 /// This function panics if `T` is a Zero-Sized Type ("ZST").
808 /// let mut a = [0; 5];
809 /// let ptr1: *mut i32 = &mut a[1];
810 /// let ptr2: *mut i32 = &mut a[3];
812 /// assert_eq!(ptr2.offset_from(ptr1), 2);
813 /// assert_eq!(ptr1.offset_from(ptr2), -2);
814 /// assert_eq!(ptr1.offset(2), ptr2);
815 /// assert_eq!(ptr2.offset(-2), ptr1);
819 /// *Incorrect* usage:
822 /// let ptr1 = Box::into_raw(Box::new(0u8));
823 /// let ptr2 = Box::into_raw(Box::new(1u8));
824 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
825 /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
826 /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff);
827 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
828 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
829 /// // computing their offset is undefined behavior, even though
830 /// // they point to the same address!
832 /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
835 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
836 #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
838 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
839 pub const unsafe fn offset_from(self, origin: *const T) -> isize
843 // SAFETY: the caller must uphold the safety contract for `offset_from`.
844 unsafe { (self as *const T).offset_from(origin) }
847 /// Calculates the distance between two pointers. The returned value is in
848 /// units of **bytes**.
850 /// This is purely a convenience for casting to a `u8` pointer and
851 /// using [offset_from][pointer::offset_from] on it. See that method for
852 /// documentation and safety requirements.
854 /// For non-`Sized` pointees this operation considers only the data pointers,
855 /// ignoring the metadata.
857 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
858 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
859 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
860 pub const unsafe fn byte_offset_from(self, origin: *const T) -> isize {
861 // SAFETY: the caller must uphold the safety contract for `offset_from`.
862 unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
865 /// Calculates the distance between two pointers, *where it's known that
866 /// `self` is equal to or greater than `origin`*. The returned value is in
867 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
869 /// This computes the same value that [`offset_from`](#method.offset_from)
870 /// would compute, but with the added precondition that the offset is
871 /// guaranteed to be non-negative. This method is equivalent to
872 /// `usize::from(self.offset_from(origin)).unwrap_unchecked()`,
873 /// but it provides slightly more information to the optimizer, which can
874 /// sometimes allow it to optimize slightly better with some backends.
876 /// This method can be though of as recovering the `count` that was passed
877 /// to [`add`](#method.add) (or, with the parameters in the other order,
878 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
879 /// that their safety preconditions are met:
881 /// # #![feature(ptr_sub_ptr)]
882 /// # unsafe fn blah(ptr: *mut i32, origin: *mut i32, count: usize) -> bool {
883 /// ptr.sub_ptr(origin) == count
885 /// origin.add(count) == ptr
887 /// ptr.sub(count) == origin
893 /// - The distance between the pointers must be non-negative (`self >= origin`)
895 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
896 /// apply to this method as well; see it for the full details.
898 /// Importantly, despite the return type of this method being able to represent
899 /// a larger offset, it's still *not permitted* to pass pointers which differ
900 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
901 /// always be less than or equal to `isize::MAX as usize`.
905 /// This function panics if `T` is a Zero-Sized Type ("ZST").
910 /// #![feature(ptr_sub_ptr)]
912 /// let mut a = [0; 5];
913 /// let p: *mut i32 = a.as_mut_ptr();
915 /// let ptr1: *mut i32 = p.add(1);
916 /// let ptr2: *mut i32 = p.add(3);
918 /// assert_eq!(ptr2.sub_ptr(ptr1), 2);
919 /// assert_eq!(ptr1.add(2), ptr2);
920 /// assert_eq!(ptr2.sub(2), ptr1);
921 /// assert_eq!(ptr2.sub_ptr(ptr2), 0);
924 /// // This would be incorrect, as the pointers are not correctly ordered:
925 /// // ptr1.offset_from(ptr2)
926 #[unstable(feature = "ptr_sub_ptr", issue = "95892")]
927 #[rustc_const_unstable(feature = "const_ptr_sub_ptr", issue = "95892")]
929 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
930 pub const unsafe fn sub_ptr(self, origin: *const T) -> usize
934 // SAFETY: the caller must uphold the safety contract for `sub_ptr`.
935 unsafe { (self as *const T).sub_ptr(origin) }
938 /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
940 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
941 /// offset of `3 * size_of::<T>()` bytes.
945 /// If any of the following conditions are violated, the result is Undefined
948 /// * Both the starting and resulting pointer must be either in bounds or one
949 /// byte past the end of the same [allocated object].
951 /// * The computed offset, **in bytes**, cannot overflow an `isize`.
953 /// * The offset being in bounds cannot rely on "wrapping around" the address
954 /// space. That is, the infinite-precision sum must fit in a `usize`.
956 /// The compiler and standard library generally tries to ensure allocations
957 /// never reach a size where an offset is a concern. For instance, `Vec`
958 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
959 /// `vec.as_ptr().add(vec.len())` is always safe.
961 /// Most platforms fundamentally can't even construct such an allocation.
962 /// For instance, no known 64-bit platform can ever serve a request
963 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
964 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
965 /// more than `isize::MAX` bytes with things like Physical Address
966 /// Extension. As such, memory acquired directly from allocators or memory
967 /// mapped files *may* be too large to handle with this function.
969 /// Consider using [`wrapping_add`] instead if these constraints are
970 /// difficult to satisfy. The only advantage of this method is that it
971 /// enables more aggressive compiler optimizations.
973 /// [`wrapping_add`]: #method.wrapping_add
974 /// [allocated object]: crate::ptr#allocated-object
981 /// let s: &str = "123";
982 /// let ptr: *const u8 = s.as_ptr();
985 /// println!("{}", *ptr.add(1) as char);
986 /// println!("{}", *ptr.add(2) as char);
989 #[stable(feature = "pointer_methods", since = "1.26.0")]
990 #[must_use = "returns a new pointer rather than modifying its argument"]
991 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
993 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
994 pub const unsafe fn add(self, count: usize) -> Self
998 // SAFETY: the caller must uphold the safety contract for `offset`.
999 unsafe { self.offset(count as isize) }
1002 /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
1004 /// `count` is in units of bytes.
1006 /// This is purely a convenience for casting to a `u8` pointer and
1007 /// using [add][pointer::add] on it. See that method for documentation
1008 /// and safety requirements.
1010 /// For non-`Sized` pointees this operation changes only the data pointer,
1011 /// leaving the metadata untouched.
1014 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1015 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1016 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1017 pub const unsafe fn byte_add(self, count: usize) -> Self {
1018 // SAFETY: the caller must uphold the safety contract for `add`.
1019 let this = unsafe { self.cast::<u8>().add(count).cast::<()>() };
1020 from_raw_parts_mut::<T>(this, metadata(self))
1023 /// Calculates the offset from a pointer (convenience for
1024 /// `.offset((count as isize).wrapping_neg())`).
1026 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1027 /// offset of `3 * size_of::<T>()` bytes.
1031 /// If any of the following conditions are violated, the result is Undefined
1034 /// * Both the starting and resulting pointer must be either in bounds or one
1035 /// byte past the end of the same [allocated object].
1037 /// * The computed offset cannot exceed `isize::MAX` **bytes**.
1039 /// * The offset being in bounds cannot rely on "wrapping around" the address
1040 /// space. That is, the infinite-precision sum must fit in a usize.
1042 /// The compiler and standard library generally tries to ensure allocations
1043 /// never reach a size where an offset is a concern. For instance, `Vec`
1044 /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
1045 /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
1047 /// Most platforms fundamentally can't even construct such an allocation.
1048 /// For instance, no known 64-bit platform can ever serve a request
1049 /// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
1050 /// However, some 32-bit and 16-bit platforms may successfully serve a request for
1051 /// more than `isize::MAX` bytes with things like Physical Address
1052 /// Extension. As such, memory acquired directly from allocators or memory
1053 /// mapped files *may* be too large to handle with this function.
1055 /// Consider using [`wrapping_sub`] instead if these constraints are
1056 /// difficult to satisfy. The only advantage of this method is that it
1057 /// enables more aggressive compiler optimizations.
1059 /// [`wrapping_sub`]: #method.wrapping_sub
1060 /// [allocated object]: crate::ptr#allocated-object
1067 /// let s: &str = "123";
1070 /// let end: *const u8 = s.as_ptr().add(3);
1071 /// println!("{}", *end.sub(1) as char);
1072 /// println!("{}", *end.sub(2) as char);
1075 #[stable(feature = "pointer_methods", since = "1.26.0")]
1076 #[must_use = "returns a new pointer rather than modifying its argument"]
1077 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1079 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1080 pub const unsafe fn sub(self, count: usize) -> Self
1084 // SAFETY: the caller must uphold the safety contract for `offset`.
1085 unsafe { self.offset((count as isize).wrapping_neg()) }
1088 /// Calculates the offset from a pointer in bytes (convenience for
1089 /// `.byte_offset((count as isize).wrapping_neg())`).
1091 /// `count` is in units of bytes.
1093 /// This is purely a convenience for casting to a `u8` pointer and
1094 /// using [sub][pointer::sub] on it. See that method for documentation
1095 /// and safety requirements.
1097 /// For non-`Sized` pointees this operation changes only the data pointer,
1098 /// leaving the metadata untouched.
1101 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1102 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1103 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1104 pub const unsafe fn byte_sub(self, count: usize) -> Self {
1105 // SAFETY: the caller must uphold the safety contract for `sub`.
1106 let this = unsafe { self.cast::<u8>().sub(count).cast::<()>() };
1107 from_raw_parts_mut::<T>(this, metadata(self))
1110 /// Calculates the offset from a pointer using wrapping arithmetic.
1111 /// (convenience for `.wrapping_offset(count as isize)`)
1113 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1114 /// offset of `3 * size_of::<T>()` bytes.
1118 /// This operation itself is always safe, but using the resulting pointer is not.
1120 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1121 /// be used to read or write other allocated objects.
1123 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1124 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1125 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1126 /// `x` and `y` point into the same allocated object.
1128 /// Compared to [`add`], this method basically delays the requirement of staying within the
1129 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
1130 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1131 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1132 /// can be optimized better and is thus preferable in performance-sensitive code.
1134 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1135 /// intermediate values used during the computation of the final result. For example,
1136 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1137 /// allocated object and then re-entering it later is permitted.
1139 /// [`add`]: #method.add
1140 /// [allocated object]: crate::ptr#allocated-object
1147 /// // Iterate using a raw pointer in increments of two elements
1148 /// let data = [1u8, 2, 3, 4, 5];
1149 /// let mut ptr: *const u8 = data.as_ptr();
1151 /// let end_rounded_up = ptr.wrapping_add(6);
1153 /// // This loop prints "1, 3, 5, "
1154 /// while ptr != end_rounded_up {
1156 /// print!("{}, ", *ptr);
1158 /// ptr = ptr.wrapping_add(step);
1161 #[stable(feature = "pointer_methods", since = "1.26.0")]
1162 #[must_use = "returns a new pointer rather than modifying its argument"]
1163 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1165 pub const fn wrapping_add(self, count: usize) -> Self
1169 self.wrapping_offset(count as isize)
1172 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1173 /// (convenience for `.wrapping_byte_offset(count as isize)`)
1175 /// `count` is in units of bytes.
1177 /// This is purely a convenience for casting to a `u8` pointer and
1178 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1180 /// For non-`Sized` pointees this operation changes only the data pointer,
1181 /// leaving the metadata untouched.
1184 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1185 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1186 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1187 from_raw_parts_mut::<T>(self.cast::<u8>().wrapping_add(count).cast::<()>(), metadata(self))
1190 /// Calculates the offset from a pointer using wrapping arithmetic.
1191 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1193 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1194 /// offset of `3 * size_of::<T>()` bytes.
1198 /// This operation itself is always safe, but using the resulting pointer is not.
1200 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1201 /// be used to read or write other allocated objects.
1203 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1204 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1205 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1206 /// `x` and `y` point into the same allocated object.
1208 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1209 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
1210 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1211 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1212 /// can be optimized better and is thus preferable in performance-sensitive code.
1214 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1215 /// intermediate values used during the computation of the final result. For example,
1216 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1217 /// allocated object and then re-entering it later is permitted.
1219 /// [`sub`]: #method.sub
1220 /// [allocated object]: crate::ptr#allocated-object
1227 /// // Iterate using a raw pointer in increments of two elements (backwards)
1228 /// let data = [1u8, 2, 3, 4, 5];
1229 /// let mut ptr: *const u8 = data.as_ptr();
1230 /// let start_rounded_down = ptr.wrapping_sub(2);
1231 /// ptr = ptr.wrapping_add(4);
1233 /// // This loop prints "5, 3, 1, "
1234 /// while ptr != start_rounded_down {
1236 /// print!("{}, ", *ptr);
1238 /// ptr = ptr.wrapping_sub(step);
1241 #[stable(feature = "pointer_methods", since = "1.26.0")]
1242 #[must_use = "returns a new pointer rather than modifying its argument"]
1243 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1245 pub const fn wrapping_sub(self, count: usize) -> Self
1249 self.wrapping_offset((count as isize).wrapping_neg())
1252 /// Calculates the offset from a pointer in bytes using wrapping arithmetic.
1253 /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
1255 /// `count` is in units of bytes.
1257 /// This is purely a convenience for casting to a `u8` pointer and
1258 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1260 /// For non-`Sized` pointees this operation changes only the data pointer,
1261 /// leaving the metadata untouched.
1264 #[unstable(feature = "pointer_byte_offsets", issue = "96283")]
1265 #[rustc_const_unstable(feature = "const_pointer_byte_offsets", issue = "96283")]
1266 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1267 from_raw_parts_mut::<T>(self.cast::<u8>().wrapping_sub(count).cast::<()>(), metadata(self))
1270 /// Reads the value from `self` without moving it. This leaves the
1271 /// memory in `self` unchanged.
1273 /// See [`ptr::read`] for safety concerns and examples.
1275 /// [`ptr::read`]: crate::ptr::read()
1276 #[stable(feature = "pointer_methods", since = "1.26.0")]
1277 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1279 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1280 pub const unsafe fn read(self) -> T
1284 // SAFETY: the caller must uphold the safety contract for ``.
1285 unsafe { read(self) }
1288 /// Performs a volatile read of the value from `self` without moving it. This
1289 /// leaves the memory in `self` unchanged.
1291 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1292 /// to not be elided or reordered by the compiler across other volatile
1295 /// See [`ptr::read_volatile`] for safety concerns and examples.
1297 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1298 #[stable(feature = "pointer_methods", since = "1.26.0")]
1300 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1301 pub unsafe fn read_volatile(self) -> T
1305 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1306 unsafe { read_volatile(self) }
1309 /// Reads the value from `self` without moving it. This leaves the
1310 /// memory in `self` unchanged.
1312 /// Unlike `read`, the pointer may be unaligned.
1314 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1316 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1317 #[stable(feature = "pointer_methods", since = "1.26.0")]
1318 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1320 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1321 pub const unsafe fn read_unaligned(self) -> T
1325 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1326 unsafe { read_unaligned(self) }
1329 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1330 /// and destination may overlap.
1332 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1334 /// See [`ptr::copy`] for safety concerns and examples.
1336 /// [`ptr::copy`]: crate::ptr::copy()
1337 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1338 #[stable(feature = "pointer_methods", since = "1.26.0")]
1340 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1341 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1345 // SAFETY: the caller must uphold the safety contract for `copy`.
1346 unsafe { copy(self, dest, count) }
1349 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1350 /// and destination may *not* overlap.
1352 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1354 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1356 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1357 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1358 #[stable(feature = "pointer_methods", since = "1.26.0")]
1360 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1361 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1365 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1366 unsafe { copy_nonoverlapping(self, dest, count) }
1369 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1370 /// and destination may overlap.
1372 /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1374 /// See [`ptr::copy`] for safety concerns and examples.
1376 /// [`ptr::copy`]: crate::ptr::copy()
1377 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1378 #[stable(feature = "pointer_methods", since = "1.26.0")]
1380 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1381 pub const unsafe fn copy_from(self, src: *const T, count: usize)
1385 // SAFETY: the caller must uphold the safety contract for `copy`.
1386 unsafe { copy(src, self, count) }
1389 /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
1390 /// and destination may *not* overlap.
1392 /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1394 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1396 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1397 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1398 #[stable(feature = "pointer_methods", since = "1.26.0")]
1400 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1401 pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
1405 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1406 unsafe { copy_nonoverlapping(src, self, count) }
1409 /// Executes the destructor (if any) of the pointed-to value.
1411 /// See [`ptr::drop_in_place`] for safety concerns and examples.
1413 /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1414 #[stable(feature = "pointer_methods", since = "1.26.0")]
1416 pub unsafe fn drop_in_place(self) {
1417 // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1418 unsafe { drop_in_place(self) }
1421 /// Overwrites a memory location with the given value without reading or
1422 /// dropping the old value.
1424 /// See [`ptr::write`] for safety concerns and examples.
1426 /// [`ptr::write`]: crate::ptr::write()
1427 #[stable(feature = "pointer_methods", since = "1.26.0")]
1428 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1430 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1431 pub const unsafe fn write(self, val: T)
1435 // SAFETY: the caller must uphold the safety contract for `write`.
1436 unsafe { write(self, val) }
1439 /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1440 /// bytes of memory starting at `self` to `val`.
1442 /// See [`ptr::write_bytes`] for safety concerns and examples.
1444 /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1445 #[doc(alias = "memset")]
1446 #[stable(feature = "pointer_methods", since = "1.26.0")]
1447 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1449 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1450 pub const unsafe fn write_bytes(self, val: u8, count: usize)
1454 // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1455 unsafe { write_bytes(self, val, count) }
1458 /// Performs a volatile write of a memory location with the given value without
1459 /// reading or dropping the old value.
1461 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1462 /// to not be elided or reordered by the compiler across other volatile
1465 /// See [`ptr::write_volatile`] for safety concerns and examples.
1467 /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1468 #[stable(feature = "pointer_methods", since = "1.26.0")]
1470 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1471 pub unsafe fn write_volatile(self, val: T)
1475 // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1476 unsafe { write_volatile(self, val) }
1479 /// Overwrites a memory location with the given value without reading or
1480 /// dropping the old value.
1482 /// Unlike `write`, the pointer may be unaligned.
1484 /// See [`ptr::write_unaligned`] for safety concerns and examples.
1486 /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1487 #[stable(feature = "pointer_methods", since = "1.26.0")]
1488 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1490 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1491 pub const unsafe fn write_unaligned(self, val: T)
1495 // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1496 unsafe { write_unaligned(self, val) }
1499 /// Replaces the value at `self` with `src`, returning the old
1500 /// value, without dropping either.
1502 /// See [`ptr::replace`] for safety concerns and examples.
1504 /// [`ptr::replace`]: crate::ptr::replace()
1505 #[stable(feature = "pointer_methods", since = "1.26.0")]
1507 pub unsafe fn replace(self, src: T) -> T
1511 // SAFETY: the caller must uphold the safety contract for `replace`.
1512 unsafe { replace(self, src) }
1515 /// Swaps the values at two mutable locations of the same type, without
1516 /// deinitializing either. They may overlap, unlike `mem::swap` which is
1517 /// otherwise equivalent.
1519 /// See [`ptr::swap`] for safety concerns and examples.
1521 /// [`ptr::swap`]: crate::ptr::swap()
1522 #[stable(feature = "pointer_methods", since = "1.26.0")]
1523 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
1525 pub const unsafe fn swap(self, with: *mut T)
1529 // SAFETY: the caller must uphold the safety contract for `swap`.
1530 unsafe { swap(self, with) }
1533 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1536 /// If it is not possible to align the pointer, the implementation returns
1537 /// `usize::MAX`. It is permissible for the implementation to *always*
1538 /// return `usize::MAX`. Only your algorithm's performance can depend
1539 /// on getting a usable offset here, not its correctness.
1541 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1542 /// used with the `wrapping_add` method.
1544 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1545 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1546 /// the returned offset is correct in all terms other than alignment.
1550 /// The function panics if `align` is not a power-of-two.
1554 /// Accessing adjacent `u8` as `u16`
1557 /// use std::mem::align_of;
1560 /// let mut x = [5_u8, 6, 7, 8, 9];
1561 /// let ptr = x.as_mut_ptr();
1562 /// let offset = ptr.align_offset(align_of::<u16>());
1564 /// if offset < x.len() - 1 {
1565 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1568 /// assert!(x == [0, 0, 7, 8, 9] || x == [5, 0, 0, 8, 9]);
1570 /// // while the pointer can be aligned via `offset`, it would point
1571 /// // outside the allocation
1575 #[stable(feature = "align_offset", since = "1.36.0")]
1576 #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
1577 pub const fn align_offset(self, align: usize) -> usize
1581 if !align.is_power_of_two() {
1582 panic!("align_offset: align is not a power-of-two");
1585 fn rt_impl<T>(p: *mut T, align: usize) -> usize {
1586 // SAFETY: `align` has been checked to be a power of 2 above
1587 unsafe { align_offset(p, align) }
1590 const fn ctfe_impl<T>(_: *mut T, _: usize) -> usize {
1595 // It is permissible for `align_offset` to always return `usize::MAX`,
1596 // algorithm correctness can not depend on `align_offset` returning non-max values.
1598 // As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
1599 unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
1602 /// Returns whether the pointer is properly aligned for `T`.
1605 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1606 pub fn is_aligned(self) -> bool
1610 self.is_aligned_to(core::mem::align_of::<T>())
1613 /// Returns whether the pointer is aligned to `align`.
1615 /// For non-`Sized` pointees this operation considers only the data pointer,
1616 /// ignoring the metadata.
1620 /// The function panics if `align` is not a power-of-two (this includes 0).
1623 #[unstable(feature = "pointer_is_aligned", issue = "96284")]
1624 pub fn is_aligned_to(self, align: usize) -> bool {
1625 if !align.is_power_of_two() {
1626 panic!("is_aligned_to: align is not a power-of-two");
1629 // Cast is needed for `T: !Sized`
1630 self.cast::<u8>().addr() & align - 1 == 0
1635 /// Returns the length of a raw slice.
1637 /// The returned value is the number of **elements**, not the number of bytes.
1639 /// This function is safe, even when the raw slice cannot be cast to a slice
1640 /// reference because the pointer is null or unaligned.
1645 /// #![feature(slice_ptr_len)]
1648 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1649 /// assert_eq!(slice.len(), 3);
1652 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1653 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1654 pub const fn len(self) -> usize {
1658 /// Returns `true` if the raw slice has a length of 0.
1663 /// #![feature(slice_ptr_len)]
1665 /// let mut a = [1, 2, 3];
1666 /// let ptr = &mut a as *mut [_];
1667 /// assert!(!ptr.is_empty());
1670 #[unstable(feature = "slice_ptr_len", issue = "71146")]
1671 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
1672 pub const fn is_empty(self) -> bool {
1676 /// Divides one mutable raw slice into two at an index.
1678 /// The first will contain all indices from `[0, mid)` (excluding
1679 /// the index `mid` itself) and the second will contain all
1680 /// indices from `[mid, len)` (excluding the index `len` itself).
1684 /// Panics if `mid > len`.
1688 /// `mid` must be [in-bounds] of the underlying [allocated object].
1689 /// Which means `self` must be dereferenceable and span a single allocation
1690 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1691 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1693 /// Since `len` being in-bounds it is not a safety invariant of `*mut [T]` the
1694 /// safety requirements of this method are the same as for [`split_at_mut_unchecked`].
1695 /// The explicit bounds check is only as useful as `len` is correct.
1697 /// [`split_at_mut_unchecked`]: #method.split_at_mut_unchecked
1698 /// [in-bounds]: #method.add
1699 /// [allocated object]: crate::ptr#allocated-object
1700 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1705 /// #![feature(raw_slice_split)]
1706 /// #![feature(slice_ptr_get)]
1708 /// let mut v = [1, 0, 3, 0, 5, 6];
1709 /// let ptr = &mut v as *mut [_];
1711 /// let (left, right) = ptr.split_at_mut(2);
1712 /// assert_eq!(&*left, [1, 0]);
1713 /// assert_eq!(&*right, [3, 0, 5, 6]);
1718 #[unstable(feature = "raw_slice_split", issue = "95595")]
1719 pub unsafe fn split_at_mut(self, mid: usize) -> (*mut [T], *mut [T]) {
1720 assert!(mid <= self.len());
1721 // SAFETY: The assert above is only a safety-net as long as `self.len()` is correct
1722 // The actual safety requirements of this function are the same as for `split_at_mut_unchecked`
1723 unsafe { self.split_at_mut_unchecked(mid) }
1726 /// Divides one mutable raw slice into two at an index, without doing bounds checking.
1728 /// The first will contain all indices from `[0, mid)` (excluding
1729 /// the index `mid` itself) and the second will contain all
1730 /// indices from `[mid, len)` (excluding the index `len` itself).
1734 /// `mid` must be [in-bounds] of the underlying [allocated object].
1735 /// Which means `self` must be dereferenceable and span a single allocation
1736 /// that is at least `mid * size_of::<T>()` bytes long. Not upholding these
1737 /// requirements is *[undefined behavior]* even if the resulting pointers are not used.
1739 /// [in-bounds]: #method.add
1740 /// [out-of-bounds index]: #method.add
1741 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1746 /// #![feature(raw_slice_split)]
1748 /// let mut v = [1, 0, 3, 0, 5, 6];
1749 /// // scoped to restrict the lifetime of the borrows
1751 /// let ptr = &mut v as *mut [_];
1752 /// let (left, right) = ptr.split_at_mut_unchecked(2);
1753 /// assert_eq!(&*left, [1, 0]);
1754 /// assert_eq!(&*right, [3, 0, 5, 6]);
1755 /// (&mut *left)[1] = 2;
1756 /// (&mut *right)[1] = 4;
1758 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1761 #[unstable(feature = "raw_slice_split", issue = "95595")]
1762 pub unsafe fn split_at_mut_unchecked(self, mid: usize) -> (*mut [T], *mut [T]) {
1763 let len = self.len();
1764 let ptr = self.as_mut_ptr();
1766 // SAFETY: Caller must pass a valid pointer and an index that is in-bounds.
1767 let tail = unsafe { ptr.add(mid) };
1769 crate::ptr::slice_from_raw_parts_mut(ptr, mid),
1770 crate::ptr::slice_from_raw_parts_mut(tail, len - mid),
1774 /// Returns a raw pointer to the slice's buffer.
1776 /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
1781 /// #![feature(slice_ptr_get)]
1784 /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
1785 /// assert_eq!(slice.as_mut_ptr(), ptr::null_mut());
1788 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1789 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
1790 pub const fn as_mut_ptr(self) -> *mut T {
1794 /// Returns a raw pointer to an element or subslice, without doing bounds
1797 /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
1798 /// is *[undefined behavior]* even if the resulting pointer is not used.
1800 /// [out-of-bounds index]: #method.add
1801 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1806 /// #![feature(slice_ptr_get)]
1808 /// let x = &mut [1, 2, 4] as *mut [i32];
1811 /// assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
1814 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1815 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
1817 pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
1819 I: ~const SliceIndex<[T]>,
1821 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1822 unsafe { index.get_unchecked_mut(self) }
1825 /// Returns `None` if the pointer is null, or else returns a shared slice to
1826 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1827 /// that the value has to be initialized.
1829 /// For the mutable counterpart see [`as_uninit_slice_mut`].
1831 /// [`as_ref`]: #method.as_ref-1
1832 /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
1836 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1837 /// all of the following is true:
1839 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1840 /// and it must be properly aligned. This means in particular:
1842 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1843 /// Slices can never span across multiple allocated objects.
1845 /// * The pointer must be aligned even for zero-length slices. One
1846 /// reason for this is that enum layout optimizations may rely on references
1847 /// (including slices of any length) being aligned and non-null to distinguish
1848 /// them from other data. You can obtain a pointer that is usable as `data`
1849 /// for zero-length slices using [`NonNull::dangling()`].
1851 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1852 /// See the safety documentation of [`pointer::offset`].
1854 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1855 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1856 /// In particular, while this reference exists, the memory the pointer points to must
1857 /// not get mutated (except inside `UnsafeCell`).
1859 /// This applies even if the result of this method is unused!
1861 /// See also [`slice::from_raw_parts`][].
1863 /// [valid]: crate::ptr#safety
1864 /// [allocated object]: crate::ptr#allocated-object
1866 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1867 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1868 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1872 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1873 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1877 /// Returns `None` if the pointer is null, or else returns a unique slice to
1878 /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
1879 /// that the value has to be initialized.
1881 /// For the shared counterpart see [`as_uninit_slice`].
1883 /// [`as_mut`]: #method.as_mut
1884 /// [`as_uninit_slice`]: #method.as_uninit_slice-1
1888 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1889 /// all of the following is true:
1891 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
1892 /// many bytes, and it must be properly aligned. This means in particular:
1894 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1895 /// Slices can never span across multiple allocated objects.
1897 /// * The pointer must be aligned even for zero-length slices. One
1898 /// reason for this is that enum layout optimizations may rely on references
1899 /// (including slices of any length) being aligned and non-null to distinguish
1900 /// them from other data. You can obtain a pointer that is usable as `data`
1901 /// for zero-length slices using [`NonNull::dangling()`].
1903 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1904 /// See the safety documentation of [`pointer::offset`].
1906 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1907 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1908 /// In particular, while this reference exists, the memory the pointer points to must
1909 /// not get accessed (read or written) through any other pointer.
1911 /// This applies even if the result of this method is unused!
1913 /// See also [`slice::from_raw_parts_mut`][].
1915 /// [valid]: crate::ptr#safety
1916 /// [allocated object]: crate::ptr#allocated-object
1918 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1919 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
1920 pub const unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
1924 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
1925 Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
1930 // Equality for pointers
1931 #[stable(feature = "rust1", since = "1.0.0")]
1932 impl<T: ?Sized> PartialEq for *mut T {
1934 fn eq(&self, other: &*mut T) -> bool {
1939 #[stable(feature = "rust1", since = "1.0.0")]
1940 impl<T: ?Sized> Eq for *mut T {}
1942 #[stable(feature = "rust1", since = "1.0.0")]
1943 impl<T: ?Sized> Ord for *mut T {
1945 fn cmp(&self, other: &*mut T) -> Ordering {
1948 } else if self == other {
1956 #[stable(feature = "rust1", since = "1.0.0")]
1957 impl<T: ?Sized> PartialOrd for *mut T {
1959 fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
1960 Some(self.cmp(other))
1964 fn lt(&self, other: &*mut T) -> bool {
1969 fn le(&self, other: &*mut T) -> bool {
1974 fn gt(&self, other: &*mut T) -> bool {
1979 fn ge(&self, other: &*mut T) -> bool {