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