core/ptr/const_ptr.rs
1use super::*;
2use crate::cmp::Ordering::{Equal, Greater, Less};
3use crate::intrinsics::const_eval_select;
4use crate::mem::SizedTypeProperties;
5use crate::slice::{self, SliceIndex};
6
7impl<T: ?Sized> *const T {
8 /// Returns `true` if the pointer is null.
9 ///
10 /// Note that unsized types have many possible null pointers, as only the
11 /// raw data pointer is considered, not their length, vtable, etc.
12 /// Therefore, two pointers that are null may still not compare equal to
13 /// each other.
14 ///
15 /// # Panics during const evaluation
16 ///
17 /// If this method is used during const evaluation, and `self` is a pointer
18 /// that is offset beyond the bounds of the memory it initially pointed to,
19 /// then there might not be enough information to determine whether the
20 /// pointer is null. This is because the absolute address in memory is not
21 /// known at compile time. If the nullness of the pointer cannot be
22 /// determined, this method will panic.
23 ///
24 /// In-bounds pointers are never null, so the method will never panic for
25 /// such pointers.
26 ///
27 /// # Examples
28 ///
29 /// ```
30 /// let s: &str = "Follow the rabbit";
31 /// let ptr: *const u8 = s.as_ptr();
32 /// assert!(!ptr.is_null());
33 /// ```
34 #[stable(feature = "rust1", since = "1.0.0")]
35 #[rustc_const_stable(feature = "const_ptr_is_null", since = "1.84.0")]
36 #[rustc_diagnostic_item = "ptr_const_is_null"]
37 #[inline]
38 #[rustc_allow_const_fn_unstable(const_eval_select)]
39 pub const fn is_null(self) -> bool {
40 // Compare via a cast to a thin pointer, so fat pointers are only
41 // considering their "data" part for null-ness.
42 let ptr = self as *const u8;
43 const_eval_select!(
44 @capture { ptr: *const u8 } -> bool:
45 // This use of `const_raw_ptr_comparison` has been explicitly blessed by t-lang.
46 if const #[rustc_allow_const_fn_unstable(const_raw_ptr_comparison)] {
47 match (ptr).guaranteed_eq(null_mut()) {
48 Some(res) => res,
49 // To remain maximally convervative, we stop execution when we don't
50 // know whether the pointer is null or not.
51 // We can *not* return `false` here, that would be unsound in `NonNull::new`!
52 None => panic!("null-ness of this pointer cannot be determined in const context"),
53 }
54 } else {
55 ptr.addr() == 0
56 }
57 )
58 }
59
60 /// Casts to a pointer of another type.
61 #[stable(feature = "ptr_cast", since = "1.38.0")]
62 #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
63 #[rustc_diagnostic_item = "const_ptr_cast"]
64 #[inline(always)]
65 pub const fn cast<U>(self) -> *const U {
66 self as _
67 }
68
69 /// Uses the address value in a new pointer of another type.
70 ///
71 /// This operation will ignore the address part of its `meta` operand and discard existing
72 /// metadata of `self`. For pointers to a sized types (thin pointers), this has the same effect
73 /// as a simple cast. For pointers to an unsized type (fat pointers) this recombines the address
74 /// with new metadata such as slice lengths or `dyn`-vtable.
75 ///
76 /// The resulting pointer will have provenance of `self`. This operation is semantically the
77 /// same as creating a new pointer with the data pointer value of `self` but the metadata of
78 /// `meta`, being fat or thin depending on the `meta` operand.
79 ///
80 /// # Examples
81 ///
82 /// This function is primarily useful for enabling pointer arithmetic on potentially fat
83 /// pointers. The pointer is cast to a sized pointee to utilize offset operations and then
84 /// recombined with its own original metadata.
85 ///
86 /// ```
87 /// #![feature(set_ptr_value)]
88 /// # use core::fmt::Debug;
89 /// let arr: [i32; 3] = [1, 2, 3];
90 /// let mut ptr = arr.as_ptr() as *const dyn Debug;
91 /// let thin = ptr as *const u8;
92 /// unsafe {
93 /// ptr = thin.add(8).with_metadata_of(ptr);
94 /// # assert_eq!(*(ptr as *const i32), 3);
95 /// println!("{:?}", &*ptr); // will print "3"
96 /// }
97 /// ```
98 ///
99 /// # *Incorrect* usage
100 ///
101 /// The provenance from pointers is *not* combined. The result must only be used to refer to the
102 /// address allowed by `self`.
103 ///
104 /// ```rust,no_run
105 /// #![feature(set_ptr_value)]
106 /// let x = 0u32;
107 /// let y = 1u32;
108 ///
109 /// let x = (&x) as *const u32;
110 /// let y = (&y) as *const u32;
111 ///
112 /// let offset = (x as usize - y as usize) / 4;
113 /// let bad = x.wrapping_add(offset).with_metadata_of(y);
114 ///
115 /// // This dereference is UB. The pointer only has provenance for `x` but points to `y`.
116 /// println!("{:?}", unsafe { &*bad });
117 /// ```
118 #[unstable(feature = "set_ptr_value", issue = "75091")]
119 #[must_use = "returns a new pointer rather than modifying its argument"]
120 #[inline]
121 pub const fn with_metadata_of<U>(self, meta: *const U) -> *const U
122 where
123 U: ?Sized,
124 {
125 from_raw_parts::<U>(self as *const (), metadata(meta))
126 }
127
128 /// Changes constness without changing the type.
129 ///
130 /// This is a bit safer than `as` because it wouldn't silently change the type if the code is
131 /// refactored.
132 #[stable(feature = "ptr_const_cast", since = "1.65.0")]
133 #[rustc_const_stable(feature = "ptr_const_cast", since = "1.65.0")]
134 #[rustc_diagnostic_item = "ptr_cast_mut"]
135 #[inline(always)]
136 pub const fn cast_mut(self) -> *mut T {
137 self as _
138 }
139
140 /// Gets the "address" portion of the pointer.
141 ///
142 /// This is similar to `self as usize`, except that the [provenance][crate::ptr#provenance] of
143 /// the pointer is discarded and not [exposed][crate::ptr#exposed-provenance]. This means that
144 /// casting the returned address back to a pointer yields a [pointer without
145 /// provenance][without_provenance], which is undefined behavior to dereference. To properly
146 /// restore the lost information and obtain a dereferenceable pointer, use
147 /// [`with_addr`][pointer::with_addr] or [`map_addr`][pointer::map_addr].
148 ///
149 /// If using those APIs is not possible because there is no way to preserve a pointer with the
150 /// required provenance, then Strict Provenance might not be for you. Use pointer-integer casts
151 /// or [`expose_provenance`][pointer::expose_provenance] and [`with_exposed_provenance`][with_exposed_provenance]
152 /// instead. However, note that this makes your code less portable and less amenable to tools
153 /// that check for compliance with the Rust memory model.
154 ///
155 /// On most platforms this will produce a value with the same bytes as the original
156 /// pointer, because all the bytes are dedicated to describing the address.
157 /// Platforms which need to store additional information in the pointer may
158 /// perform a change of representation to produce a value containing only the address
159 /// portion of the pointer. What that means is up to the platform to define.
160 ///
161 /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
162 #[must_use]
163 #[inline(always)]
164 #[stable(feature = "strict_provenance", since = "1.84.0")]
165 pub fn addr(self) -> usize {
166 // A pointer-to-integer transmute currently has exactly the right semantics: it returns the
167 // address without exposing the provenance. Note that this is *not* a stable guarantee about
168 // transmute semantics, it relies on sysroot crates having special status.
169 // SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
170 // provenance).
171 unsafe { mem::transmute(self.cast::<()>()) }
172 }
173
174 /// Exposes the ["provenance"][crate::ptr#provenance] part of the pointer for future use in
175 /// [`with_exposed_provenance`] and returns the "address" portion.
176 ///
177 /// This is equivalent to `self as usize`, which semantically discards provenance information.
178 /// Furthermore, this (like the `as` cast) has the implicit side-effect of marking the
179 /// provenance as 'exposed', so on platforms that support it you can later call
180 /// [`with_exposed_provenance`] to reconstitute the original pointer including its provenance.
181 ///
182 /// Due to its inherent ambiguity, [`with_exposed_provenance`] may not be supported by tools
183 /// that help you to stay conformant with the Rust memory model. It is recommended to use
184 /// [Strict Provenance][crate::ptr#strict-provenance] APIs such as [`with_addr`][pointer::with_addr]
185 /// wherever possible, in which case [`addr`][pointer::addr] should be used instead of `expose_provenance`.
186 ///
187 /// On most platforms this will produce a value with the same bytes as the original pointer,
188 /// because all the bytes are dedicated to describing the address. Platforms which need to store
189 /// additional information in the pointer may not support this operation, since the 'expose'
190 /// side-effect which is required for [`with_exposed_provenance`] to work is typically not
191 /// available.
192 ///
193 /// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
194 ///
195 /// [`with_exposed_provenance`]: with_exposed_provenance
196 #[must_use]
197 #[inline(always)]
198 #[stable(feature = "exposed_provenance", since = "1.84.0")]
199 pub fn expose_provenance(self) -> usize {
200 self.cast::<()>() as usize
201 }
202
203 /// Creates a new pointer with the given address and the [provenance][crate::ptr#provenance] of
204 /// `self`.
205 ///
206 /// This is similar to a `addr as *const T` cast, but copies
207 /// the *provenance* of `self` to the new pointer.
208 /// This avoids the inherent ambiguity of the unary cast.
209 ///
210 /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset
211 /// `self` to the given address, and therefore has all the same capabilities and restrictions.
212 ///
213 /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
214 #[must_use]
215 #[inline]
216 #[stable(feature = "strict_provenance", since = "1.84.0")]
217 pub fn with_addr(self, addr: usize) -> Self {
218 // This should probably be an intrinsic to avoid doing any sort of arithmetic, but
219 // meanwhile, we can implement it with `wrapping_offset`, which preserves the pointer's
220 // provenance.
221 let self_addr = self.addr() as isize;
222 let dest_addr = addr as isize;
223 let offset = dest_addr.wrapping_sub(self_addr);
224 self.wrapping_byte_offset(offset)
225 }
226
227 /// Creates a new pointer by mapping `self`'s address to a new one, preserving the
228 /// [provenance][crate::ptr#provenance] of `self`.
229 ///
230 /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details.
231 ///
232 /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
233 #[must_use]
234 #[inline]
235 #[stable(feature = "strict_provenance", since = "1.84.0")]
236 pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self {
237 self.with_addr(f(self.addr()))
238 }
239
240 /// Decompose a (possibly wide) pointer into its data pointer and metadata components.
241 ///
242 /// The pointer can be later reconstructed with [`from_raw_parts`].
243 #[unstable(feature = "ptr_metadata", issue = "81513")]
244 #[inline]
245 pub const fn to_raw_parts(self) -> (*const (), <T as super::Pointee>::Metadata) {
246 (self.cast(), metadata(self))
247 }
248
249 /// Returns `None` if the pointer is null, or else returns a shared reference to
250 /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
251 /// must be used instead.
252 ///
253 /// [`as_uninit_ref`]: #method.as_uninit_ref
254 ///
255 /// # Safety
256 ///
257 /// When calling this method, you have to ensure that *either* the pointer is null *or*
258 /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
259 ///
260 /// # Panics during const evaluation
261 ///
262 /// This method will panic during const evaluation if the pointer cannot be
263 /// determined to be null or not. See [`is_null`] for more information.
264 ///
265 /// [`is_null`]: #method.is_null
266 ///
267 /// # Examples
268 ///
269 /// ```
270 /// let ptr: *const u8 = &10u8 as *const u8;
271 ///
272 /// unsafe {
273 /// if let Some(val_back) = ptr.as_ref() {
274 /// assert_eq!(val_back, &10);
275 /// }
276 /// }
277 /// ```
278 ///
279 /// # Null-unchecked version
280 ///
281 /// If you are sure the pointer can never be null and are looking for some kind of
282 /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
283 /// dereference the pointer directly.
284 ///
285 /// ```
286 /// let ptr: *const u8 = &10u8 as *const u8;
287 ///
288 /// unsafe {
289 /// let val_back = &*ptr;
290 /// assert_eq!(val_back, &10);
291 /// }
292 /// ```
293 #[stable(feature = "ptr_as_ref", since = "1.9.0")]
294 #[rustc_const_stable(feature = "const_ptr_is_null", since = "1.84.0")]
295 #[inline]
296 pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> {
297 // SAFETY: the caller must guarantee that `self` is valid
298 // for a reference if it isn't null.
299 if self.is_null() { None } else { unsafe { Some(&*self) } }
300 }
301
302 /// Returns a shared reference to the value behind the pointer.
303 /// If the pointer may be null or the value may be uninitialized, [`as_uninit_ref`] must be used instead.
304 /// If the pointer may be null, but the value is known to have been initialized, [`as_ref`] must be used instead.
305 ///
306 /// [`as_ref`]: #method.as_ref
307 /// [`as_uninit_ref`]: #method.as_uninit_ref
308 ///
309 /// # Safety
310 ///
311 /// When calling this method, you have to ensure that
312 /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
313 ///
314 /// # Examples
315 ///
316 /// ```
317 /// #![feature(ptr_as_ref_unchecked)]
318 /// let ptr: *const u8 = &10u8 as *const u8;
319 ///
320 /// unsafe {
321 /// assert_eq!(ptr.as_ref_unchecked(), &10);
322 /// }
323 /// ```
324 // FIXME: mention it in the docs for `as_ref` and `as_uninit_ref` once stabilized.
325 #[unstable(feature = "ptr_as_ref_unchecked", issue = "122034")]
326 #[inline]
327 #[must_use]
328 pub const unsafe fn as_ref_unchecked<'a>(self) -> &'a T {
329 // SAFETY: the caller must guarantee that `self` is valid for a reference
330 unsafe { &*self }
331 }
332
333 /// Returns `None` if the pointer is null, or else returns a shared reference to
334 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
335 /// that the value has to be initialized.
336 ///
337 /// [`as_ref`]: #method.as_ref
338 ///
339 /// # Safety
340 ///
341 /// When calling this method, you have to ensure that *either* the pointer is null *or*
342 /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
343 ///
344 /// # Panics during const evaluation
345 ///
346 /// This method will panic during const evaluation if the pointer cannot be
347 /// determined to be null or not. See [`is_null`] for more information.
348 ///
349 /// [`is_null`]: #method.is_null
350 ///
351 /// # Examples
352 ///
353 /// ```
354 /// #![feature(ptr_as_uninit)]
355 ///
356 /// let ptr: *const u8 = &10u8 as *const u8;
357 ///
358 /// unsafe {
359 /// if let Some(val_back) = ptr.as_uninit_ref() {
360 /// assert_eq!(val_back.assume_init(), 10);
361 /// }
362 /// }
363 /// ```
364 #[inline]
365 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
366 pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
367 where
368 T: Sized,
369 {
370 // SAFETY: the caller must guarantee that `self` meets all the
371 // requirements for a reference.
372 if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
373 }
374
375 /// Adds a signed offset to a pointer.
376 ///
377 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
378 /// offset of `3 * size_of::<T>()` bytes.
379 ///
380 /// # Safety
381 ///
382 /// If any of the following conditions are violated, the result is Undefined Behavior:
383 ///
384 /// * The offset in bytes, `count * size_of::<T>()`, computed on mathematical integers (without
385 /// "wrapping around"), must fit in an `isize`.
386 ///
387 /// * If the computed offset is non-zero, then `self` must be [derived from][crate::ptr#provenance] a pointer to some
388 /// [allocated object], and the entire memory range between `self` and the result must be in
389 /// bounds of that allocated object. In particular, this range must not "wrap around" the edge
390 /// of the address space.
391 ///
392 /// Allocated objects can never be larger than `isize::MAX` bytes, so if the computed offset
393 /// stays in bounds of the allocated object, it is guaranteed to satisfy the first requirement.
394 /// This implies, for instance, that `vec.as_ptr().add(vec.len())` (for `vec: Vec<T>`) is always
395 /// safe.
396 ///
397 /// Consider using [`wrapping_offset`] instead if these constraints are
398 /// difficult to satisfy. The only advantage of this method is that it
399 /// enables more aggressive compiler optimizations.
400 ///
401 /// [`wrapping_offset`]: #method.wrapping_offset
402 /// [allocated object]: crate::ptr#allocated-object
403 ///
404 /// # Examples
405 ///
406 /// ```
407 /// let s: &str = "123";
408 /// let ptr: *const u8 = s.as_ptr();
409 ///
410 /// unsafe {
411 /// assert_eq!(*ptr.offset(1) as char, '2');
412 /// assert_eq!(*ptr.offset(2) as char, '3');
413 /// }
414 /// ```
415 #[stable(feature = "rust1", since = "1.0.0")]
416 #[must_use = "returns a new pointer rather than modifying its argument"]
417 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
418 #[inline(always)]
419 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
420 pub const unsafe fn offset(self, count: isize) -> *const T
421 where
422 T: Sized,
423 {
424 #[inline]
425 #[rustc_allow_const_fn_unstable(const_eval_select)]
426 const fn runtime_offset_nowrap(this: *const (), count: isize, size: usize) -> bool {
427 // We can use const_eval_select here because this is only for UB checks.
428 const_eval_select!(
429 @capture { this: *const (), count: isize, size: usize } -> bool:
430 if const {
431 true
432 } else {
433 // `size` is the size of a Rust type, so we know that
434 // `size <= isize::MAX` and thus `as` cast here is not lossy.
435 let Some(byte_offset) = count.checked_mul(size as isize) else {
436 return false;
437 };
438 let (_, overflow) = this.addr().overflowing_add_signed(byte_offset);
439 !overflow
440 }
441 )
442 }
443
444 ub_checks::assert_unsafe_precondition!(
445 check_language_ub,
446 "ptr::offset requires the address calculation to not overflow",
447 (
448 this: *const () = self as *const (),
449 count: isize = count,
450 size: usize = size_of::<T>(),
451 ) => runtime_offset_nowrap(this, count, size)
452 );
453
454 // SAFETY: the caller must uphold the safety contract for `offset`.
455 unsafe { intrinsics::offset(self, count) }
456 }
457
458 /// Adds a signed offset in bytes to a pointer.
459 ///
460 /// `count` is in units of **bytes**.
461 ///
462 /// This is purely a convenience for casting to a `u8` pointer and
463 /// using [offset][pointer::offset] on it. See that method for documentation
464 /// and safety requirements.
465 ///
466 /// For non-`Sized` pointees this operation changes only the data pointer,
467 /// leaving the metadata untouched.
468 #[must_use]
469 #[inline(always)]
470 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
471 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
472 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
473 pub const unsafe fn byte_offset(self, count: isize) -> Self {
474 // SAFETY: the caller must uphold the safety contract for `offset`.
475 unsafe { self.cast::<u8>().offset(count).with_metadata_of(self) }
476 }
477
478 /// Adds a signed offset to a pointer using wrapping arithmetic.
479 ///
480 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
481 /// offset of `3 * size_of::<T>()` bytes.
482 ///
483 /// # Safety
484 ///
485 /// This operation itself is always safe, but using the resulting pointer is not.
486 ///
487 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
488 /// be used to read or write other allocated objects.
489 ///
490 /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
491 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
492 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
493 /// `x` and `y` point into the same allocated object.
494 ///
495 /// Compared to [`offset`], this method basically delays the requirement of staying within the
496 /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
497 /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
498 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
499 /// can be optimized better and is thus preferable in performance-sensitive code.
500 ///
501 /// The delayed check only considers the value of the pointer that was dereferenced, not the
502 /// intermediate values used during the computation of the final result. For example,
503 /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
504 /// words, leaving the allocated object and then re-entering it later is permitted.
505 ///
506 /// [`offset`]: #method.offset
507 /// [allocated object]: crate::ptr#allocated-object
508 ///
509 /// # Examples
510 ///
511 /// ```
512 /// # use std::fmt::Write;
513 /// // Iterate using a raw pointer in increments of two elements
514 /// let data = [1u8, 2, 3, 4, 5];
515 /// let mut ptr: *const u8 = data.as_ptr();
516 /// let step = 2;
517 /// let end_rounded_up = ptr.wrapping_offset(6);
518 ///
519 /// let mut out = String::new();
520 /// while ptr != end_rounded_up {
521 /// unsafe {
522 /// write!(&mut out, "{}, ", *ptr)?;
523 /// }
524 /// ptr = ptr.wrapping_offset(step);
525 /// }
526 /// assert_eq!(out.as_str(), "1, 3, 5, ");
527 /// # std::fmt::Result::Ok(())
528 /// ```
529 #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
530 #[must_use = "returns a new pointer rather than modifying its argument"]
531 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
532 #[inline(always)]
533 pub const fn wrapping_offset(self, count: isize) -> *const T
534 where
535 T: Sized,
536 {
537 // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
538 unsafe { intrinsics::arith_offset(self, count) }
539 }
540
541 /// Adds a signed offset in bytes to a pointer using wrapping arithmetic.
542 ///
543 /// `count` is in units of **bytes**.
544 ///
545 /// This is purely a convenience for casting to a `u8` pointer and
546 /// using [wrapping_offset][pointer::wrapping_offset] on it. See that method
547 /// for documentation.
548 ///
549 /// For non-`Sized` pointees this operation changes only the data pointer,
550 /// leaving the metadata untouched.
551 #[must_use]
552 #[inline(always)]
553 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
554 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
555 pub const fn wrapping_byte_offset(self, count: isize) -> Self {
556 self.cast::<u8>().wrapping_offset(count).with_metadata_of(self)
557 }
558
559 /// Masks out bits of the pointer according to a mask.
560 ///
561 /// This is convenience for `ptr.map_addr(|a| a & mask)`.
562 ///
563 /// For non-`Sized` pointees this operation changes only the data pointer,
564 /// leaving the metadata untouched.
565 ///
566 /// ## Examples
567 ///
568 /// ```
569 /// #![feature(ptr_mask)]
570 /// let v = 17_u32;
571 /// let ptr: *const u32 = &v;
572 ///
573 /// // `u32` is 4 bytes aligned,
574 /// // which means that lower 2 bits are always 0.
575 /// let tag_mask = 0b11;
576 /// let ptr_mask = !tag_mask;
577 ///
578 /// // We can store something in these lower bits
579 /// let tagged_ptr = ptr.map_addr(|a| a | 0b10);
580 ///
581 /// // Get the "tag" back
582 /// let tag = tagged_ptr.addr() & tag_mask;
583 /// assert_eq!(tag, 0b10);
584 ///
585 /// // Note that `tagged_ptr` is unaligned, it's UB to read from it.
586 /// // To get original pointer `mask` can be used:
587 /// let masked_ptr = tagged_ptr.mask(ptr_mask);
588 /// assert_eq!(unsafe { *masked_ptr }, 17);
589 /// ```
590 #[unstable(feature = "ptr_mask", issue = "98290")]
591 #[must_use = "returns a new pointer rather than modifying its argument"]
592 #[inline(always)]
593 pub fn mask(self, mask: usize) -> *const T {
594 intrinsics::ptr_mask(self.cast::<()>(), mask).with_metadata_of(self)
595 }
596
597 /// Calculates the distance between two pointers within the same allocation. The returned value is in
598 /// units of T: the distance in bytes divided by `mem::size_of::<T>()`.
599 ///
600 /// This is equivalent to `(self as isize - origin as isize) / (mem::size_of::<T>() as isize)`,
601 /// except that it has a lot more opportunities for UB, in exchange for the compiler
602 /// better understanding what you are doing.
603 ///
604 /// The primary motivation of this method is for computing the `len` of an array/slice
605 /// of `T` that you are currently representing as a "start" and "end" pointer
606 /// (and "end" is "one past the end" of the array).
607 /// In that case, `end.offset_from(start)` gets you the length of the array.
608 ///
609 /// All of the following safety requirements are trivially satisfied for this usecase.
610 ///
611 /// [`offset`]: #method.offset
612 ///
613 /// # Safety
614 ///
615 /// If any of the following conditions are violated, the result is Undefined Behavior:
616 ///
617 /// * `self` and `origin` must either
618 ///
619 /// * point to the same address, or
620 /// * both be [derived from][crate::ptr#provenance] a pointer to the same [allocated object], and the memory range between
621 /// the two pointers must be in bounds of that object. (See below for an example.)
622 ///
623 /// * The distance between the pointers, in bytes, must be an exact multiple
624 /// of the size of `T`.
625 ///
626 /// As a consequence, the absolute distance between the pointers, in bytes, computed on
627 /// mathematical integers (without "wrapping around"), cannot overflow an `isize`. This is
628 /// implied by the in-bounds requirement, and the fact that no allocated object can be larger
629 /// than `isize::MAX` bytes.
630 ///
631 /// The requirement for pointers to be derived from the same allocated object is primarily
632 /// needed for `const`-compatibility: the distance between pointers into *different* allocated
633 /// objects is not known at compile-time. However, the requirement also exists at
634 /// runtime and may be exploited by optimizations. If you wish to compute the difference between
635 /// pointers that are not guaranteed to be from the same allocation, use `(self as isize -
636 /// origin as isize) / mem::size_of::<T>()`.
637 // FIXME: recommend `addr()` instead of `as usize` once that is stable.
638 ///
639 /// [`add`]: #method.add
640 /// [allocated object]: crate::ptr#allocated-object
641 ///
642 /// # Panics
643 ///
644 /// This function panics if `T` is a Zero-Sized Type ("ZST").
645 ///
646 /// # Examples
647 ///
648 /// Basic usage:
649 ///
650 /// ```
651 /// let a = [0; 5];
652 /// let ptr1: *const i32 = &a[1];
653 /// let ptr2: *const i32 = &a[3];
654 /// unsafe {
655 /// assert_eq!(ptr2.offset_from(ptr1), 2);
656 /// assert_eq!(ptr1.offset_from(ptr2), -2);
657 /// assert_eq!(ptr1.offset(2), ptr2);
658 /// assert_eq!(ptr2.offset(-2), ptr1);
659 /// }
660 /// ```
661 ///
662 /// *Incorrect* usage:
663 ///
664 /// ```rust,no_run
665 /// let ptr1 = Box::into_raw(Box::new(0u8)) as *const u8;
666 /// let ptr2 = Box::into_raw(Box::new(1u8)) as *const u8;
667 /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
668 /// // Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.
669 /// let ptr2_other = (ptr1 as *const u8).wrapping_offset(diff).wrapping_offset(1);
670 /// assert_eq!(ptr2 as usize, ptr2_other as usize);
671 /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
672 /// // computing their offset is undefined behavior, even though
673 /// // they point to addresses that are in-bounds of the same object!
674 /// unsafe {
675 /// let one = ptr2_other.offset_from(ptr2); // Undefined Behavior! ⚠️
676 /// }
677 /// ```
678 #[stable(feature = "ptr_offset_from", since = "1.47.0")]
679 #[rustc_const_stable(feature = "const_ptr_offset_from", since = "1.65.0")]
680 #[inline]
681 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
682 pub const unsafe fn offset_from(self, origin: *const T) -> isize
683 where
684 T: Sized,
685 {
686 let pointee_size = mem::size_of::<T>();
687 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
688 // SAFETY: the caller must uphold the safety contract for `ptr_offset_from`.
689 unsafe { intrinsics::ptr_offset_from(self, origin) }
690 }
691
692 /// Calculates the distance between two pointers within the same allocation. The returned value is in
693 /// units of **bytes**.
694 ///
695 /// This is purely a convenience for casting to a `u8` pointer and
696 /// using [`offset_from`][pointer::offset_from] on it. See that method for
697 /// documentation and safety requirements.
698 ///
699 /// For non-`Sized` pointees this operation considers only the data pointers,
700 /// ignoring the metadata.
701 #[inline(always)]
702 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
703 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
704 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
705 pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: *const U) -> isize {
706 // SAFETY: the caller must uphold the safety contract for `offset_from`.
707 unsafe { self.cast::<u8>().offset_from(origin.cast::<u8>()) }
708 }
709
710 /// Calculates the distance between two pointers within the same allocation, *where it's known that
711 /// `self` is equal to or greater than `origin`*. The returned value is in
712 /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
713 ///
714 /// This computes the same value that [`offset_from`](#method.offset_from)
715 /// would compute, but with the added precondition that the offset is
716 /// guaranteed to be non-negative. This method is equivalent to
717 /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`,
718 /// but it provides slightly more information to the optimizer, which can
719 /// sometimes allow it to optimize slightly better with some backends.
720 ///
721 /// This method can be thought of as recovering the `count` that was passed
722 /// to [`add`](#method.add) (or, with the parameters in the other order,
723 /// to [`sub`](#method.sub)). The following are all equivalent, assuming
724 /// that their safety preconditions are met:
725 /// ```rust
726 /// # unsafe fn blah(ptr: *const i32, origin: *const i32, count: usize) -> bool { unsafe {
727 /// ptr.offset_from_unsigned(origin) == count
728 /// # &&
729 /// origin.add(count) == ptr
730 /// # &&
731 /// ptr.sub(count) == origin
732 /// # } }
733 /// ```
734 ///
735 /// # Safety
736 ///
737 /// - The distance between the pointers must be non-negative (`self >= origin`)
738 ///
739 /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
740 /// apply to this method as well; see it for the full details.
741 ///
742 /// Importantly, despite the return type of this method being able to represent
743 /// a larger offset, it's still *not permitted* to pass pointers which differ
744 /// by more than `isize::MAX` *bytes*. As such, the result of this method will
745 /// always be less than or equal to `isize::MAX as usize`.
746 ///
747 /// # Panics
748 ///
749 /// This function panics if `T` is a Zero-Sized Type ("ZST").
750 ///
751 /// # Examples
752 ///
753 /// ```
754 /// let a = [0; 5];
755 /// let ptr1: *const i32 = &a[1];
756 /// let ptr2: *const i32 = &a[3];
757 /// unsafe {
758 /// assert_eq!(ptr2.offset_from_unsigned(ptr1), 2);
759 /// assert_eq!(ptr1.add(2), ptr2);
760 /// assert_eq!(ptr2.sub(2), ptr1);
761 /// assert_eq!(ptr2.offset_from_unsigned(ptr2), 0);
762 /// }
763 ///
764 /// // This would be incorrect, as the pointers are not correctly ordered:
765 /// // ptr1.offset_from_unsigned(ptr2)
766 /// ```
767 #[stable(feature = "ptr_sub_ptr", since = "CURRENT_RUSTC_VERSION")]
768 #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "CURRENT_RUSTC_VERSION")]
769 #[inline]
770 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
771 pub const unsafe fn offset_from_unsigned(self, origin: *const T) -> usize
772 where
773 T: Sized,
774 {
775 #[rustc_allow_const_fn_unstable(const_eval_select)]
776 const fn runtime_ptr_ge(this: *const (), origin: *const ()) -> bool {
777 const_eval_select!(
778 @capture { this: *const (), origin: *const () } -> bool:
779 if const {
780 true
781 } else {
782 this >= origin
783 }
784 )
785 }
786
787 ub_checks::assert_unsafe_precondition!(
788 check_language_ub,
789 "ptr::offset_from_unsigned requires `self >= origin`",
790 (
791 this: *const () = self as *const (),
792 origin: *const () = origin as *const (),
793 ) => runtime_ptr_ge(this, origin)
794 );
795
796 let pointee_size = mem::size_of::<T>();
797 assert!(0 < pointee_size && pointee_size <= isize::MAX as usize);
798 // SAFETY: the caller must uphold the safety contract for `ptr_offset_from_unsigned`.
799 unsafe { intrinsics::ptr_offset_from_unsigned(self, origin) }
800 }
801
802 /// Calculates the distance between two pointers within the same allocation, *where it's known that
803 /// `self` is equal to or greater than `origin`*. The returned value is in
804 /// units of **bytes**.
805 ///
806 /// This is purely a convenience for casting to a `u8` pointer and
807 /// using [`sub_ptr`][pointer::offset_from_unsigned] on it. See that method for
808 /// documentation and safety requirements.
809 ///
810 /// For non-`Sized` pointees this operation considers only the data pointers,
811 /// ignoring the metadata.
812 #[stable(feature = "ptr_sub_ptr", since = "CURRENT_RUSTC_VERSION")]
813 #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "CURRENT_RUSTC_VERSION")]
814 #[inline]
815 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
816 pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: *const U) -> usize {
817 // SAFETY: the caller must uphold the safety contract for `sub_ptr`.
818 unsafe { self.cast::<u8>().offset_from_unsigned(origin.cast::<u8>()) }
819 }
820
821 /// Returns whether two pointers are guaranteed to be equal.
822 ///
823 /// At runtime this function behaves like `Some(self == other)`.
824 /// However, in some contexts (e.g., compile-time evaluation),
825 /// it is not always possible to determine equality of two pointers, so this function may
826 /// spuriously return `None` for pointers that later actually turn out to have its equality known.
827 /// But when it returns `Some`, the pointers' equality is guaranteed to be known.
828 ///
829 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
830 /// version and unsafe code must not
831 /// rely on the result of this function for soundness. It is suggested to only use this function
832 /// for performance optimizations where spurious `None` return values by this function do not
833 /// affect the outcome, but just the performance.
834 /// The consequences of using this method to make runtime and compile-time code behave
835 /// differently have not been explored. This method should not be used to introduce such
836 /// differences, and it should also not be stabilized before we have a better understanding
837 /// of this issue.
838 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
839 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
840 #[inline]
841 pub const fn guaranteed_eq(self, other: *const T) -> Option<bool>
842 where
843 T: Sized,
844 {
845 match intrinsics::ptr_guaranteed_cmp(self, other) {
846 2 => None,
847 other => Some(other == 1),
848 }
849 }
850
851 /// Returns whether two pointers are guaranteed to be inequal.
852 ///
853 /// At runtime this function behaves like `Some(self != other)`.
854 /// However, in some contexts (e.g., compile-time evaluation),
855 /// it is not always possible to determine inequality of two pointers, so this function may
856 /// spuriously return `None` for pointers that later actually turn out to have its inequality known.
857 /// But when it returns `Some`, the pointers' inequality is guaranteed to be known.
858 ///
859 /// The return value may change from `Some` to `None` and vice versa depending on the compiler
860 /// version and unsafe code must not
861 /// rely on the result of this function for soundness. It is suggested to only use this function
862 /// for performance optimizations where spurious `None` return values by this function do not
863 /// affect the outcome, but just the performance.
864 /// The consequences of using this method to make runtime and compile-time code behave
865 /// differently have not been explored. This method should not be used to introduce such
866 /// differences, and it should also not be stabilized before we have a better understanding
867 /// of this issue.
868 #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
869 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
870 #[inline]
871 pub const fn guaranteed_ne(self, other: *const T) -> Option<bool>
872 where
873 T: Sized,
874 {
875 match self.guaranteed_eq(other) {
876 None => None,
877 Some(eq) => Some(!eq),
878 }
879 }
880
881 /// Adds an unsigned offset to a pointer.
882 ///
883 /// This can only move the pointer forward (or not move it). If you need to move forward or
884 /// backward depending on the value, then you might want [`offset`](#method.offset) instead
885 /// which takes a signed offset.
886 ///
887 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
888 /// offset of `3 * size_of::<T>()` bytes.
889 ///
890 /// # Safety
891 ///
892 /// If any of the following conditions are violated, the result is Undefined Behavior:
893 ///
894 /// * The offset in bytes, `count * size_of::<T>()`, computed on mathematical integers (without
895 /// "wrapping around"), must fit in an `isize`.
896 ///
897 /// * If the computed offset is non-zero, then `self` must be [derived from][crate::ptr#provenance] a pointer to some
898 /// [allocated object], and the entire memory range between `self` and the result must be in
899 /// bounds of that allocated object. In particular, this range must not "wrap around" the edge
900 /// of the address space.
901 ///
902 /// Allocated objects can never be larger than `isize::MAX` bytes, so if the computed offset
903 /// stays in bounds of the allocated object, it is guaranteed to satisfy the first requirement.
904 /// This implies, for instance, that `vec.as_ptr().add(vec.len())` (for `vec: Vec<T>`) is always
905 /// safe.
906 ///
907 /// Consider using [`wrapping_add`] instead if these constraints are
908 /// difficult to satisfy. The only advantage of this method is that it
909 /// enables more aggressive compiler optimizations.
910 ///
911 /// [`wrapping_add`]: #method.wrapping_add
912 /// [allocated object]: crate::ptr#allocated-object
913 ///
914 /// # Examples
915 ///
916 /// ```
917 /// let s: &str = "123";
918 /// let ptr: *const u8 = s.as_ptr();
919 ///
920 /// unsafe {
921 /// assert_eq!(*ptr.add(1), b'2');
922 /// assert_eq!(*ptr.add(2), b'3');
923 /// }
924 /// ```
925 #[stable(feature = "pointer_methods", since = "1.26.0")]
926 #[must_use = "returns a new pointer rather than modifying its argument"]
927 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
928 #[inline(always)]
929 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
930 pub const unsafe fn add(self, count: usize) -> Self
931 where
932 T: Sized,
933 {
934 #[cfg(debug_assertions)]
935 #[inline]
936 #[rustc_allow_const_fn_unstable(const_eval_select)]
937 const fn runtime_add_nowrap(this: *const (), count: usize, size: usize) -> bool {
938 const_eval_select!(
939 @capture { this: *const (), count: usize, size: usize } -> bool:
940 if const {
941 true
942 } else {
943 let Some(byte_offset) = count.checked_mul(size) else {
944 return false;
945 };
946 let (_, overflow) = this.addr().overflowing_add(byte_offset);
947 byte_offset <= (isize::MAX as usize) && !overflow
948 }
949 )
950 }
951
952 #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
953 ub_checks::assert_unsafe_precondition!(
954 check_language_ub,
955 "ptr::add requires that the address calculation does not overflow",
956 (
957 this: *const () = self as *const (),
958 count: usize = count,
959 size: usize = size_of::<T>(),
960 ) => runtime_add_nowrap(this, count, size)
961 );
962
963 // SAFETY: the caller must uphold the safety contract for `offset`.
964 unsafe { intrinsics::offset(self, count) }
965 }
966
967 /// Adds an unsigned offset in bytes to a pointer.
968 ///
969 /// `count` is in units of bytes.
970 ///
971 /// This is purely a convenience for casting to a `u8` pointer and
972 /// using [add][pointer::add] on it. See that method for documentation
973 /// and safety requirements.
974 ///
975 /// For non-`Sized` pointees this operation changes only the data pointer,
976 /// leaving the metadata untouched.
977 #[must_use]
978 #[inline(always)]
979 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
980 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
981 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
982 pub const unsafe fn byte_add(self, count: usize) -> Self {
983 // SAFETY: the caller must uphold the safety contract for `add`.
984 unsafe { self.cast::<u8>().add(count).with_metadata_of(self) }
985 }
986
987 /// Subtracts an unsigned offset from a pointer.
988 ///
989 /// This can only move the pointer backward (or not move it). If you need to move forward or
990 /// backward depending on the value, then you might want [`offset`](#method.offset) instead
991 /// which takes a signed offset.
992 ///
993 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
994 /// offset of `3 * size_of::<T>()` bytes.
995 ///
996 /// # Safety
997 ///
998 /// If any of the following conditions are violated, the result is Undefined Behavior:
999 ///
1000 /// * The offset in bytes, `count * size_of::<T>()`, computed on mathematical integers (without
1001 /// "wrapping around"), must fit in an `isize`.
1002 ///
1003 /// * If the computed offset is non-zero, then `self` must be [derived from][crate::ptr#provenance] a pointer to some
1004 /// [allocated object], and the entire memory range between `self` and the result must be in
1005 /// bounds of that allocated object. In particular, this range must not "wrap around" the edge
1006 /// of the address space.
1007 ///
1008 /// Allocated objects can never be larger than `isize::MAX` bytes, so if the computed offset
1009 /// stays in bounds of the allocated object, it is guaranteed to satisfy the first requirement.
1010 /// This implies, for instance, that `vec.as_ptr().add(vec.len())` (for `vec: Vec<T>`) is always
1011 /// safe.
1012 ///
1013 /// Consider using [`wrapping_sub`] instead if these constraints are
1014 /// difficult to satisfy. The only advantage of this method is that it
1015 /// enables more aggressive compiler optimizations.
1016 ///
1017 /// [`wrapping_sub`]: #method.wrapping_sub
1018 /// [allocated object]: crate::ptr#allocated-object
1019 ///
1020 /// # Examples
1021 ///
1022 /// ```
1023 /// let s: &str = "123";
1024 ///
1025 /// unsafe {
1026 /// let end: *const u8 = s.as_ptr().add(3);
1027 /// assert_eq!(*end.sub(1), b'3');
1028 /// assert_eq!(*end.sub(2), b'2');
1029 /// }
1030 /// ```
1031 #[stable(feature = "pointer_methods", since = "1.26.0")]
1032 #[must_use = "returns a new pointer rather than modifying its argument"]
1033 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1034 #[inline(always)]
1035 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1036 pub const unsafe fn sub(self, count: usize) -> Self
1037 where
1038 T: Sized,
1039 {
1040 #[cfg(debug_assertions)]
1041 #[inline]
1042 #[rustc_allow_const_fn_unstable(const_eval_select)]
1043 const fn runtime_sub_nowrap(this: *const (), count: usize, size: usize) -> bool {
1044 const_eval_select!(
1045 @capture { this: *const (), count: usize, size: usize } -> bool:
1046 if const {
1047 true
1048 } else {
1049 let Some(byte_offset) = count.checked_mul(size) else {
1050 return false;
1051 };
1052 byte_offset <= (isize::MAX as usize) && this.addr() >= byte_offset
1053 }
1054 )
1055 }
1056
1057 #[cfg(debug_assertions)] // Expensive, and doesn't catch much in the wild.
1058 ub_checks::assert_unsafe_precondition!(
1059 check_language_ub,
1060 "ptr::sub requires that the address calculation does not overflow",
1061 (
1062 this: *const () = self as *const (),
1063 count: usize = count,
1064 size: usize = size_of::<T>(),
1065 ) => runtime_sub_nowrap(this, count, size)
1066 );
1067
1068 if T::IS_ZST {
1069 // Pointer arithmetic does nothing when the pointee is a ZST.
1070 self
1071 } else {
1072 // SAFETY: the caller must uphold the safety contract for `offset`.
1073 // Because the pointee is *not* a ZST, that means that `count` is
1074 // at most `isize::MAX`, and thus the negation cannot overflow.
1075 unsafe { intrinsics::offset(self, intrinsics::unchecked_sub(0, count as isize)) }
1076 }
1077 }
1078
1079 /// Subtracts an unsigned offset in bytes from a pointer.
1080 ///
1081 /// `count` is in units of bytes.
1082 ///
1083 /// This is purely a convenience for casting to a `u8` pointer and
1084 /// using [sub][pointer::sub] on it. See that method for documentation
1085 /// and safety requirements.
1086 ///
1087 /// For non-`Sized` pointees this operation changes only the data pointer,
1088 /// leaving the metadata untouched.
1089 #[must_use]
1090 #[inline(always)]
1091 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1092 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1093 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1094 pub const unsafe fn byte_sub(self, count: usize) -> Self {
1095 // SAFETY: the caller must uphold the safety contract for `sub`.
1096 unsafe { self.cast::<u8>().sub(count).with_metadata_of(self) }
1097 }
1098
1099 /// Adds an unsigned offset to a pointer using wrapping arithmetic.
1100 ///
1101 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1102 /// offset of `3 * size_of::<T>()` bytes.
1103 ///
1104 /// # Safety
1105 ///
1106 /// This operation itself is always safe, but using the resulting pointer is not.
1107 ///
1108 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1109 /// be used to read or write other allocated objects.
1110 ///
1111 /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
1112 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1113 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1114 /// `x` and `y` point into the same allocated object.
1115 ///
1116 /// Compared to [`add`], this method basically delays the requirement of staying within the
1117 /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
1118 /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
1119 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
1120 /// can be optimized better and is thus preferable in performance-sensitive code.
1121 ///
1122 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1123 /// intermediate values used during the computation of the final result. For example,
1124 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1125 /// allocated object and then re-entering it later is permitted.
1126 ///
1127 /// [`add`]: #method.add
1128 /// [allocated object]: crate::ptr#allocated-object
1129 ///
1130 /// # Examples
1131 ///
1132 /// ```
1133 /// # use std::fmt::Write;
1134 /// // Iterate using a raw pointer in increments of two elements
1135 /// let data = [1u8, 2, 3, 4, 5];
1136 /// let mut ptr: *const u8 = data.as_ptr();
1137 /// let step = 2;
1138 /// let end_rounded_up = ptr.wrapping_add(6);
1139 ///
1140 /// let mut out = String::new();
1141 /// while ptr != end_rounded_up {
1142 /// unsafe {
1143 /// write!(&mut out, "{}, ", *ptr)?;
1144 /// }
1145 /// ptr = ptr.wrapping_add(step);
1146 /// }
1147 /// assert_eq!(out, "1, 3, 5, ");
1148 /// # std::fmt::Result::Ok(())
1149 /// ```
1150 #[stable(feature = "pointer_methods", since = "1.26.0")]
1151 #[must_use = "returns a new pointer rather than modifying its argument"]
1152 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1153 #[inline(always)]
1154 pub const fn wrapping_add(self, count: usize) -> Self
1155 where
1156 T: Sized,
1157 {
1158 self.wrapping_offset(count as isize)
1159 }
1160
1161 /// Adds an unsigned offset in bytes to a pointer using wrapping arithmetic.
1162 ///
1163 /// `count` is in units of bytes.
1164 ///
1165 /// This is purely a convenience for casting to a `u8` pointer and
1166 /// using [wrapping_add][pointer::wrapping_add] on it. See that method for documentation.
1167 ///
1168 /// For non-`Sized` pointees this operation changes only the data pointer,
1169 /// leaving the metadata untouched.
1170 #[must_use]
1171 #[inline(always)]
1172 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1173 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1174 pub const fn wrapping_byte_add(self, count: usize) -> Self {
1175 self.cast::<u8>().wrapping_add(count).with_metadata_of(self)
1176 }
1177
1178 /// Subtracts an unsigned offset from a pointer using wrapping arithmetic.
1179 ///
1180 /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
1181 /// offset of `3 * size_of::<T>()` bytes.
1182 ///
1183 /// # Safety
1184 ///
1185 /// This operation itself is always safe, but using the resulting pointer is not.
1186 ///
1187 /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
1188 /// be used to read or write other allocated objects.
1189 ///
1190 /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
1191 /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
1192 /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
1193 /// `x` and `y` point into the same allocated object.
1194 ///
1195 /// Compared to [`sub`], this method basically delays the requirement of staying within the
1196 /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
1197 /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
1198 /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
1199 /// can be optimized better and is thus preferable in performance-sensitive code.
1200 ///
1201 /// The delayed check only considers the value of the pointer that was dereferenced, not the
1202 /// intermediate values used during the computation of the final result. For example,
1203 /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
1204 /// allocated object and then re-entering it later is permitted.
1205 ///
1206 /// [`sub`]: #method.sub
1207 /// [allocated object]: crate::ptr#allocated-object
1208 ///
1209 /// # Examples
1210 ///
1211 /// ```
1212 /// # use std::fmt::Write;
1213 /// // Iterate using a raw pointer in increments of two elements (backwards)
1214 /// let data = [1u8, 2, 3, 4, 5];
1215 /// let mut ptr: *const u8 = data.as_ptr();
1216 /// let start_rounded_down = ptr.wrapping_sub(2);
1217 /// ptr = ptr.wrapping_add(4);
1218 /// let step = 2;
1219 /// let mut out = String::new();
1220 /// while ptr != start_rounded_down {
1221 /// unsafe {
1222 /// write!(&mut out, "{}, ", *ptr)?;
1223 /// }
1224 /// ptr = ptr.wrapping_sub(step);
1225 /// }
1226 /// assert_eq!(out, "5, 3, 1, ");
1227 /// # std::fmt::Result::Ok(())
1228 /// ```
1229 #[stable(feature = "pointer_methods", since = "1.26.0")]
1230 #[must_use = "returns a new pointer rather than modifying its argument"]
1231 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
1232 #[inline(always)]
1233 pub const fn wrapping_sub(self, count: usize) -> Self
1234 where
1235 T: Sized,
1236 {
1237 self.wrapping_offset((count as isize).wrapping_neg())
1238 }
1239
1240 /// Subtracts an unsigned offset in bytes from a pointer using wrapping arithmetic.
1241 ///
1242 /// `count` is in units of bytes.
1243 ///
1244 /// This is purely a convenience for casting to a `u8` pointer and
1245 /// using [wrapping_sub][pointer::wrapping_sub] on it. See that method for documentation.
1246 ///
1247 /// For non-`Sized` pointees this operation changes only the data pointer,
1248 /// leaving the metadata untouched.
1249 #[must_use]
1250 #[inline(always)]
1251 #[stable(feature = "pointer_byte_offsets", since = "1.75.0")]
1252 #[rustc_const_stable(feature = "const_pointer_byte_offsets", since = "1.75.0")]
1253 pub const fn wrapping_byte_sub(self, count: usize) -> Self {
1254 self.cast::<u8>().wrapping_sub(count).with_metadata_of(self)
1255 }
1256
1257 /// Reads the value from `self` without moving it. This leaves the
1258 /// memory in `self` unchanged.
1259 ///
1260 /// See [`ptr::read`] for safety concerns and examples.
1261 ///
1262 /// [`ptr::read`]: crate::ptr::read()
1263 #[stable(feature = "pointer_methods", since = "1.26.0")]
1264 #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1265 #[inline]
1266 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1267 pub const unsafe fn read(self) -> T
1268 where
1269 T: Sized,
1270 {
1271 // SAFETY: the caller must uphold the safety contract for `read`.
1272 unsafe { read(self) }
1273 }
1274
1275 /// Performs a volatile read of the value from `self` without moving it. This
1276 /// leaves the memory in `self` unchanged.
1277 ///
1278 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1279 /// to not be elided or reordered by the compiler across other volatile
1280 /// operations.
1281 ///
1282 /// See [`ptr::read_volatile`] for safety concerns and examples.
1283 ///
1284 /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
1285 #[stable(feature = "pointer_methods", since = "1.26.0")]
1286 #[inline]
1287 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1288 pub unsafe fn read_volatile(self) -> T
1289 where
1290 T: Sized,
1291 {
1292 // SAFETY: the caller must uphold the safety contract for `read_volatile`.
1293 unsafe { read_volatile(self) }
1294 }
1295
1296 /// Reads the value from `self` without moving it. This leaves the
1297 /// memory in `self` unchanged.
1298 ///
1299 /// Unlike `read`, the pointer may be unaligned.
1300 ///
1301 /// See [`ptr::read_unaligned`] for safety concerns and examples.
1302 ///
1303 /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
1304 #[stable(feature = "pointer_methods", since = "1.26.0")]
1305 #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1306 #[inline]
1307 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1308 pub const unsafe fn read_unaligned(self) -> T
1309 where
1310 T: Sized,
1311 {
1312 // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
1313 unsafe { read_unaligned(self) }
1314 }
1315
1316 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1317 /// and destination may overlap.
1318 ///
1319 /// NOTE: this has the *same* argument order as [`ptr::copy`].
1320 ///
1321 /// See [`ptr::copy`] for safety concerns and examples.
1322 ///
1323 /// [`ptr::copy`]: crate::ptr::copy()
1324 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1325 #[stable(feature = "pointer_methods", since = "1.26.0")]
1326 #[inline]
1327 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1328 pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
1329 where
1330 T: Sized,
1331 {
1332 // SAFETY: the caller must uphold the safety contract for `copy`.
1333 unsafe { copy(self, dest, count) }
1334 }
1335
1336 /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
1337 /// and destination may *not* overlap.
1338 ///
1339 /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1340 ///
1341 /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1342 ///
1343 /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1344 #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1345 #[stable(feature = "pointer_methods", since = "1.26.0")]
1346 #[inline]
1347 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1348 pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
1349 where
1350 T: Sized,
1351 {
1352 // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1353 unsafe { copy_nonoverlapping(self, dest, count) }
1354 }
1355
1356 /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1357 /// `align`.
1358 ///
1359 /// If it is not possible to align the pointer, the implementation returns
1360 /// `usize::MAX`.
1361 ///
1362 /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
1363 /// used with the `wrapping_add` method.
1364 ///
1365 /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1366 /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1367 /// the returned offset is correct in all terms other than alignment.
1368 ///
1369 /// # Panics
1370 ///
1371 /// The function panics if `align` is not a power-of-two.
1372 ///
1373 /// # Examples
1374 ///
1375 /// Accessing adjacent `u8` as `u16`
1376 ///
1377 /// ```
1378 /// use std::mem::align_of;
1379 ///
1380 /// # unsafe {
1381 /// let x = [5_u8, 6, 7, 8, 9];
1382 /// let ptr = x.as_ptr();
1383 /// let offset = ptr.align_offset(align_of::<u16>());
1384 ///
1385 /// if offset < x.len() - 1 {
1386 /// let u16_ptr = ptr.add(offset).cast::<u16>();
1387 /// assert!(*u16_ptr == u16::from_ne_bytes([5, 6]) || *u16_ptr == u16::from_ne_bytes([6, 7]));
1388 /// } else {
1389 /// // while the pointer can be aligned via `offset`, it would point
1390 /// // outside the allocation
1391 /// }
1392 /// # }
1393 /// ```
1394 #[must_use]
1395 #[inline]
1396 #[stable(feature = "align_offset", since = "1.36.0")]
1397 pub fn align_offset(self, align: usize) -> usize
1398 where
1399 T: Sized,
1400 {
1401 if !align.is_power_of_two() {
1402 panic!("align_offset: align is not a power-of-two");
1403 }
1404
1405 // SAFETY: `align` has been checked to be a power of 2 above
1406 let ret = unsafe { align_offset(self, align) };
1407
1408 // Inform Miri that we want to consider the resulting pointer to be suitably aligned.
1409 #[cfg(miri)]
1410 if ret != usize::MAX {
1411 intrinsics::miri_promise_symbolic_alignment(self.wrapping_add(ret).cast(), align);
1412 }
1413
1414 ret
1415 }
1416
1417 /// Returns whether the pointer is properly aligned for `T`.
1418 ///
1419 /// # Examples
1420 ///
1421 /// ```
1422 /// // On some platforms, the alignment of i32 is less than 4.
1423 /// #[repr(align(4))]
1424 /// struct AlignedI32(i32);
1425 ///
1426 /// let data = AlignedI32(42);
1427 /// let ptr = &data as *const AlignedI32;
1428 ///
1429 /// assert!(ptr.is_aligned());
1430 /// assert!(!ptr.wrapping_byte_add(1).is_aligned());
1431 /// ```
1432 #[must_use]
1433 #[inline]
1434 #[stable(feature = "pointer_is_aligned", since = "1.79.0")]
1435 pub fn is_aligned(self) -> bool
1436 where
1437 T: Sized,
1438 {
1439 self.is_aligned_to(mem::align_of::<T>())
1440 }
1441
1442 /// Returns whether the pointer is aligned to `align`.
1443 ///
1444 /// For non-`Sized` pointees this operation considers only the data pointer,
1445 /// ignoring the metadata.
1446 ///
1447 /// # Panics
1448 ///
1449 /// The function panics if `align` is not a power-of-two (this includes 0).
1450 ///
1451 /// # Examples
1452 ///
1453 /// ```
1454 /// #![feature(pointer_is_aligned_to)]
1455 ///
1456 /// // On some platforms, the alignment of i32 is less than 4.
1457 /// #[repr(align(4))]
1458 /// struct AlignedI32(i32);
1459 ///
1460 /// let data = AlignedI32(42);
1461 /// let ptr = &data as *const AlignedI32;
1462 ///
1463 /// assert!(ptr.is_aligned_to(1));
1464 /// assert!(ptr.is_aligned_to(2));
1465 /// assert!(ptr.is_aligned_to(4));
1466 ///
1467 /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1468 /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1469 ///
1470 /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1471 /// ```
1472 #[must_use]
1473 #[inline]
1474 #[unstable(feature = "pointer_is_aligned_to", issue = "96284")]
1475 pub fn is_aligned_to(self, align: usize) -> bool {
1476 if !align.is_power_of_two() {
1477 panic!("is_aligned_to: align is not a power-of-two");
1478 }
1479
1480 self.addr() & (align - 1) == 0
1481 }
1482}
1483
1484impl<T> *const [T] {
1485 /// Returns the length of a raw slice.
1486 ///
1487 /// The returned value is the number of **elements**, not the number of bytes.
1488 ///
1489 /// This function is safe, even when the raw slice cannot be cast to a slice
1490 /// reference because the pointer is null or unaligned.
1491 ///
1492 /// # Examples
1493 ///
1494 /// ```rust
1495 /// use std::ptr;
1496 ///
1497 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1498 /// assert_eq!(slice.len(), 3);
1499 /// ```
1500 #[inline]
1501 #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1502 #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1503 pub const fn len(self) -> usize {
1504 metadata(self)
1505 }
1506
1507 /// Returns `true` if the raw slice has a length of 0.
1508 ///
1509 /// # Examples
1510 ///
1511 /// ```
1512 /// use std::ptr;
1513 ///
1514 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1515 /// assert!(!slice.is_empty());
1516 /// ```
1517 #[inline(always)]
1518 #[stable(feature = "slice_ptr_len", since = "1.79.0")]
1519 #[rustc_const_stable(feature = "const_slice_ptr_len", since = "1.79.0")]
1520 pub const fn is_empty(self) -> bool {
1521 self.len() == 0
1522 }
1523
1524 /// Returns a raw pointer to the slice's buffer.
1525 ///
1526 /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1527 ///
1528 /// # Examples
1529 ///
1530 /// ```rust
1531 /// #![feature(slice_ptr_get)]
1532 /// use std::ptr;
1533 ///
1534 /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
1535 /// assert_eq!(slice.as_ptr(), ptr::null());
1536 /// ```
1537 #[inline]
1538 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1539 pub const fn as_ptr(self) -> *const T {
1540 self as *const T
1541 }
1542
1543 /// Gets a raw pointer to the underlying array.
1544 ///
1545 /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
1546 #[unstable(feature = "slice_as_array", issue = "133508")]
1547 #[inline]
1548 #[must_use]
1549 pub const fn as_array<const N: usize>(self) -> Option<*const [T; N]> {
1550 if self.len() == N {
1551 let me = self.as_ptr() as *const [T; N];
1552 Some(me)
1553 } else {
1554 None
1555 }
1556 }
1557
1558 /// Returns a raw pointer to an element or subslice, without doing bounds
1559 /// checking.
1560 ///
1561 /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
1562 /// is *[undefined behavior]* even if the resulting pointer is not used.
1563 ///
1564 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1565 ///
1566 /// # Examples
1567 ///
1568 /// ```
1569 /// #![feature(slice_ptr_get)]
1570 ///
1571 /// let x = &[1, 2, 4] as *const [i32];
1572 ///
1573 /// unsafe {
1574 /// assert_eq!(x.get_unchecked(1), x.as_ptr().add(1));
1575 /// }
1576 /// ```
1577 #[unstable(feature = "slice_ptr_get", issue = "74265")]
1578 #[inline]
1579 pub unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output
1580 where
1581 I: SliceIndex<[T]>,
1582 {
1583 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1584 unsafe { index.get_unchecked(self) }
1585 }
1586
1587 /// Returns `None` if the pointer is null, or else returns a shared slice to
1588 /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
1589 /// that the value has to be initialized.
1590 ///
1591 /// [`as_ref`]: #method.as_ref
1592 ///
1593 /// # Safety
1594 ///
1595 /// When calling this method, you have to ensure that *either* the pointer is null *or*
1596 /// all of the following is true:
1597 ///
1598 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
1599 /// and it must be properly aligned. This means in particular:
1600 ///
1601 /// * The entire memory range of this slice must be contained within a single [allocated object]!
1602 /// Slices can never span across multiple allocated objects.
1603 ///
1604 /// * The pointer must be aligned even for zero-length slices. One
1605 /// reason for this is that enum layout optimizations may rely on references
1606 /// (including slices of any length) being aligned and non-null to distinguish
1607 /// them from other data. You can obtain a pointer that is usable as `data`
1608 /// for zero-length slices using [`NonNull::dangling()`].
1609 ///
1610 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1611 /// See the safety documentation of [`pointer::offset`].
1612 ///
1613 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1614 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1615 /// In particular, while this reference exists, the memory the pointer points to must
1616 /// not get mutated (except inside `UnsafeCell`).
1617 ///
1618 /// This applies even if the result of this method is unused!
1619 ///
1620 /// See also [`slice::from_raw_parts`][].
1621 ///
1622 /// [valid]: crate::ptr#safety
1623 /// [allocated object]: crate::ptr#allocated-object
1624 ///
1625 /// # Panics during const evaluation
1626 ///
1627 /// This method will panic during const evaluation if the pointer cannot be
1628 /// determined to be null or not. See [`is_null`] for more information.
1629 ///
1630 /// [`is_null`]: #method.is_null
1631 #[inline]
1632 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1633 pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
1634 if self.is_null() {
1635 None
1636 } else {
1637 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1638 Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
1639 }
1640 }
1641}
1642
1643impl<T, const N: usize> *const [T; N] {
1644 /// Returns a raw pointer to the array's buffer.
1645 ///
1646 /// This is equivalent to casting `self` to `*const T`, but more type-safe.
1647 ///
1648 /// # Examples
1649 ///
1650 /// ```rust
1651 /// #![feature(array_ptr_get)]
1652 /// use std::ptr;
1653 ///
1654 /// let arr: *const [i8; 3] = ptr::null();
1655 /// assert_eq!(arr.as_ptr(), ptr::null());
1656 /// ```
1657 #[inline]
1658 #[unstable(feature = "array_ptr_get", issue = "119834")]
1659 pub const fn as_ptr(self) -> *const T {
1660 self as *const T
1661 }
1662
1663 /// Returns a raw pointer to a slice containing the entire array.
1664 ///
1665 /// # Examples
1666 ///
1667 /// ```
1668 /// #![feature(array_ptr_get)]
1669 ///
1670 /// let arr: *const [i32; 3] = &[1, 2, 4] as *const [i32; 3];
1671 /// let slice: *const [i32] = arr.as_slice();
1672 /// assert_eq!(slice.len(), 3);
1673 /// ```
1674 #[inline]
1675 #[unstable(feature = "array_ptr_get", issue = "119834")]
1676 pub const fn as_slice(self) -> *const [T] {
1677 self
1678 }
1679}
1680
1681/// Pointer equality is by address, as produced by the [`<*const T>::addr`](pointer::addr) method.
1682#[stable(feature = "rust1", since = "1.0.0")]
1683impl<T: ?Sized> PartialEq for *const T {
1684 #[inline]
1685 #[allow(ambiguous_wide_pointer_comparisons)]
1686 fn eq(&self, other: &*const T) -> bool {
1687 *self == *other
1688 }
1689}
1690
1691/// Pointer equality is an equivalence relation.
1692#[stable(feature = "rust1", since = "1.0.0")]
1693impl<T: ?Sized> Eq for *const T {}
1694
1695/// Pointer comparison is by address, as produced by the `[`<*const T>::addr`](pointer::addr)` method.
1696#[stable(feature = "rust1", since = "1.0.0")]
1697impl<T: ?Sized> Ord for *const T {
1698 #[inline]
1699 #[allow(ambiguous_wide_pointer_comparisons)]
1700 fn cmp(&self, other: &*const T) -> Ordering {
1701 if self < other {
1702 Less
1703 } else if self == other {
1704 Equal
1705 } else {
1706 Greater
1707 }
1708 }
1709}
1710
1711/// Pointer comparison is by address, as produced by the `[`<*const T>::addr`](pointer::addr)` method.
1712#[stable(feature = "rust1", since = "1.0.0")]
1713impl<T: ?Sized> PartialOrd for *const T {
1714 #[inline]
1715 #[allow(ambiguous_wide_pointer_comparisons)]
1716 fn partial_cmp(&self, other: &*const T) -> Option<Ordering> {
1717 Some(self.cmp(other))
1718 }
1719
1720 #[inline]
1721 #[allow(ambiguous_wide_pointer_comparisons)]
1722 fn lt(&self, other: &*const T) -> bool {
1723 *self < *other
1724 }
1725
1726 #[inline]
1727 #[allow(ambiguous_wide_pointer_comparisons)]
1728 fn le(&self, other: &*const T) -> bool {
1729 *self <= *other
1730 }
1731
1732 #[inline]
1733 #[allow(ambiguous_wide_pointer_comparisons)]
1734 fn gt(&self, other: &*const T) -> bool {
1735 *self > *other
1736 }
1737
1738 #[inline]
1739 #[allow(ambiguous_wide_pointer_comparisons)]
1740 fn ge(&self, other: &*const T) -> bool {
1741 *self >= *other
1742 }
1743}