1 | use super::*; |
2 | use crate::cmp::Ordering::{Equal, Greater, Less}; |
3 | use crate::intrinsics::const_eval_select; |
4 | use crate::mem::{self, SizedTypeProperties}; |
5 | use crate::slice::{self, SliceIndex}; |
6 | |
7 | impl<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 | #[inline (always)] |
197 | #[stable (feature = "exposed_provenance" , since = "1.84.0" )] |
198 | pub fn expose_provenance(self) -> usize { |
199 | self.cast::<()>() as usize |
200 | } |
201 | |
202 | /// Creates a new pointer with the given address and the [provenance][crate::ptr#provenance] of |
203 | /// `self`. |
204 | /// |
205 | /// This is similar to a `addr as *const T` cast, but copies |
206 | /// the *provenance* of `self` to the new pointer. |
207 | /// This avoids the inherent ambiguity of the unary cast. |
208 | /// |
209 | /// This is equivalent to using [`wrapping_offset`][pointer::wrapping_offset] to offset |
210 | /// `self` to the given address, and therefore has all the same capabilities and restrictions. |
211 | /// |
212 | /// This is a [Strict Provenance][crate::ptr#strict-provenance] API. |
213 | #[must_use ] |
214 | #[inline ] |
215 | #[stable (feature = "strict_provenance" , since = "1.84.0" )] |
216 | pub fn with_addr(self, addr: usize) -> Self { |
217 | // This should probably be an intrinsic to avoid doing any sort of arithmetic, but |
218 | // meanwhile, we can implement it with `wrapping_offset`, which preserves the pointer's |
219 | // provenance. |
220 | let self_addr = self.addr() as isize; |
221 | let dest_addr = addr as isize; |
222 | let offset = dest_addr.wrapping_sub(self_addr); |
223 | self.wrapping_byte_offset(offset) |
224 | } |
225 | |
226 | /// Creates a new pointer by mapping `self`'s address to a new one, preserving the |
227 | /// [provenance][crate::ptr#provenance] of `self`. |
228 | /// |
229 | /// This is a convenience for [`with_addr`][pointer::with_addr], see that method for details. |
230 | /// |
231 | /// This is a [Strict Provenance][crate::ptr#strict-provenance] API. |
232 | #[must_use ] |
233 | #[inline ] |
234 | #[stable (feature = "strict_provenance" , since = "1.84.0" )] |
235 | pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self { |
236 | self.with_addr(f(self.addr())) |
237 | } |
238 | |
239 | /// Decompose a (possibly wide) pointer into its data pointer and metadata components. |
240 | /// |
241 | /// The pointer can be later reconstructed with [`from_raw_parts`]. |
242 | #[unstable (feature = "ptr_metadata" , issue = "81513" )] |
243 | #[inline ] |
244 | pub const fn to_raw_parts(self) -> (*const (), <T as super::Pointee>::Metadata) { |
245 | (self.cast(), metadata(self)) |
246 | } |
247 | |
248 | /// Returns `None` if the pointer is null, or else returns a shared reference to |
249 | /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`] |
250 | /// must be used instead. |
251 | /// |
252 | /// [`as_uninit_ref`]: #method.as_uninit_ref |
253 | /// |
254 | /// # Safety |
255 | /// |
256 | /// When calling this method, you have to ensure that *either* the pointer is null *or* |
257 | /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). |
258 | /// |
259 | /// # Panics during const evaluation |
260 | /// |
261 | /// This method will panic during const evaluation if the pointer cannot be |
262 | /// determined to be null or not. See [`is_null`] for more information. |
263 | /// |
264 | /// [`is_null`]: #method.is_null |
265 | /// |
266 | /// # Examples |
267 | /// |
268 | /// ``` |
269 | /// let ptr: *const u8 = &10u8 as *const u8; |
270 | /// |
271 | /// unsafe { |
272 | /// if let Some(val_back) = ptr.as_ref() { |
273 | /// assert_eq!(val_back, &10); |
274 | /// } |
275 | /// } |
276 | /// ``` |
277 | /// |
278 | /// # Null-unchecked version |
279 | /// |
280 | /// If you are sure the pointer can never be null and are looking for some kind of |
281 | /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can |
282 | /// dereference the pointer directly. |
283 | /// |
284 | /// ``` |
285 | /// let ptr: *const u8 = &10u8 as *const u8; |
286 | /// |
287 | /// unsafe { |
288 | /// let val_back = &*ptr; |
289 | /// assert_eq!(val_back, &10); |
290 | /// } |
291 | /// ``` |
292 | #[stable (feature = "ptr_as_ref" , since = "1.9.0" )] |
293 | #[rustc_const_stable (feature = "const_ptr_is_null" , since = "1.84.0" )] |
294 | #[inline ] |
295 | pub const unsafe fn as_ref<'a>(self) -> Option<&'a T> { |
296 | // SAFETY: the caller must guarantee that `self` is valid |
297 | // for a reference if it isn't null. |
298 | if self.is_null() { None } else { unsafe { Some(&*self) } } |
299 | } |
300 | |
301 | /// Returns a shared reference to the value behind the pointer. |
302 | /// If the pointer may be null or the value may be uninitialized, [`as_uninit_ref`] must be used instead. |
303 | /// If the pointer may be null, but the value is known to have been initialized, [`as_ref`] must be used instead. |
304 | /// |
305 | /// [`as_ref`]: #method.as_ref |
306 | /// [`as_uninit_ref`]: #method.as_uninit_ref |
307 | /// |
308 | /// # Safety |
309 | /// |
310 | /// When calling this method, you have to ensure that |
311 | /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). |
312 | /// |
313 | /// # Examples |
314 | /// |
315 | /// ``` |
316 | /// #![feature(ptr_as_ref_unchecked)] |
317 | /// let ptr: *const u8 = &10u8 as *const u8; |
318 | /// |
319 | /// unsafe { |
320 | /// assert_eq!(ptr.as_ref_unchecked(), &10); |
321 | /// } |
322 | /// ``` |
323 | // FIXME: mention it in the docs for `as_ref` and `as_uninit_ref` once stabilized. |
324 | #[unstable (feature = "ptr_as_ref_unchecked" , issue = "122034" )] |
325 | #[inline ] |
326 | #[must_use ] |
327 | pub const unsafe fn as_ref_unchecked<'a>(self) -> &'a T { |
328 | // SAFETY: the caller must guarantee that `self` is valid for a reference |
329 | unsafe { &*self } |
330 | } |
331 | |
332 | /// Returns `None` if the pointer is null, or else returns a shared reference to |
333 | /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require |
334 | /// that the value has to be initialized. |
335 | /// |
336 | /// [`as_ref`]: #method.as_ref |
337 | /// |
338 | /// # Safety |
339 | /// |
340 | /// When calling this method, you have to ensure that *either* the pointer is null *or* |
341 | /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion). |
342 | /// |
343 | /// # Panics during const evaluation |
344 | /// |
345 | /// This method will panic during const evaluation if the pointer cannot be |
346 | /// determined to be null or not. See [`is_null`] for more information. |
347 | /// |
348 | /// [`is_null`]: #method.is_null |
349 | /// |
350 | /// # Examples |
351 | /// |
352 | /// ``` |
353 | /// #![feature(ptr_as_uninit)] |
354 | /// |
355 | /// let ptr: *const u8 = &10u8 as *const u8; |
356 | /// |
357 | /// unsafe { |
358 | /// if let Some(val_back) = ptr.as_uninit_ref() { |
359 | /// assert_eq!(val_back.assume_init(), 10); |
360 | /// } |
361 | /// } |
362 | /// ``` |
363 | #[inline ] |
364 | #[unstable (feature = "ptr_as_uninit" , issue = "75402" )] |
365 | pub const unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>> |
366 | where |
367 | T: Sized, |
368 | { |
369 | // SAFETY: the caller must guarantee that `self` meets all the |
370 | // requirements for a reference. |
371 | if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) } |
372 | } |
373 | |
374 | /// Adds a signed offset to a pointer. |
375 | /// |
376 | /// `count` is in units of T; e.g., a `count` of 3 represents a pointer |
377 | /// offset of `3 * size_of::<T>()` bytes. |
378 | /// |
379 | /// # Safety |
380 | /// |
381 | /// If any of the following conditions are violated, the result is Undefined Behavior: |
382 | /// |
383 | /// * The offset in bytes, `count * size_of::<T>()`, computed on mathematical integers (without |
384 | /// "wrapping around"), must fit in an `isize`. |
385 | /// |
386 | /// * If the computed offset is non-zero, then `self` must be [derived from][crate::ptr#provenance] a pointer to some |
387 | /// [allocated object], and the entire memory range between `self` and the result must be in |
388 | /// bounds of that allocated object. In particular, this range must not "wrap around" the edge |
389 | /// of the address space. Note that "range" here refers to a half-open range as usual in Rust, |
390 | /// i.e., `self..result` for non-negative offsets and `result..self` for negative offsets. |
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 `size_of::<T>()`. |
599 | /// |
600 | /// This is equivalent to `(self as isize - origin as isize) / (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) / 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 = 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 `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 = "1.87.0" )] |
768 | #[rustc_const_stable (feature = "const_ptr_sub_ptr" , since = "1.87.0" )] |
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 = 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 = "1.87.0" )] |
813 | #[rustc_const_stable (feature = "const_ptr_sub_ptr" , since = "1.87.0" )] |
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 | /// # unsafe { |
1379 | /// let x = [5_u8, 6, 7, 8, 9]; |
1380 | /// let ptr = x.as_ptr(); |
1381 | /// let offset = ptr.align_offset(align_of::<u16>()); |
1382 | /// |
1383 | /// if offset < x.len() - 1 { |
1384 | /// let u16_ptr = ptr.add(offset).cast::<u16>(); |
1385 | /// assert!(*u16_ptr == u16::from_ne_bytes([5, 6]) || *u16_ptr == u16::from_ne_bytes([6, 7])); |
1386 | /// } else { |
1387 | /// // while the pointer can be aligned via `offset`, it would point |
1388 | /// // outside the allocation |
1389 | /// } |
1390 | /// # } |
1391 | /// ``` |
1392 | #[must_use ] |
1393 | #[inline ] |
1394 | #[stable (feature = "align_offset" , since = "1.36.0" )] |
1395 | pub fn align_offset(self, align: usize) -> usize |
1396 | where |
1397 | T: Sized, |
1398 | { |
1399 | if !align.is_power_of_two() { |
1400 | panic!("align_offset: align is not a power-of-two" ); |
1401 | } |
1402 | |
1403 | // SAFETY: `align` has been checked to be a power of 2 above |
1404 | let ret = unsafe { align_offset(self, align) }; |
1405 | |
1406 | // Inform Miri that we want to consider the resulting pointer to be suitably aligned. |
1407 | #[cfg (miri)] |
1408 | if ret != usize::MAX { |
1409 | intrinsics::miri_promise_symbolic_alignment(self.wrapping_add(ret).cast(), align); |
1410 | } |
1411 | |
1412 | ret |
1413 | } |
1414 | |
1415 | /// Returns whether the pointer is properly aligned for `T`. |
1416 | /// |
1417 | /// # Examples |
1418 | /// |
1419 | /// ``` |
1420 | /// // On some platforms, the alignment of i32 is less than 4. |
1421 | /// #[repr(align(4))] |
1422 | /// struct AlignedI32(i32); |
1423 | /// |
1424 | /// let data = AlignedI32(42); |
1425 | /// let ptr = &data as *const AlignedI32; |
1426 | /// |
1427 | /// assert!(ptr.is_aligned()); |
1428 | /// assert!(!ptr.wrapping_byte_add(1).is_aligned()); |
1429 | /// ``` |
1430 | #[must_use ] |
1431 | #[inline ] |
1432 | #[stable (feature = "pointer_is_aligned" , since = "1.79.0" )] |
1433 | pub fn is_aligned(self) -> bool |
1434 | where |
1435 | T: Sized, |
1436 | { |
1437 | self.is_aligned_to(align_of::<T>()) |
1438 | } |
1439 | |
1440 | /// Returns whether the pointer is aligned to `align`. |
1441 | /// |
1442 | /// For non-`Sized` pointees this operation considers only the data pointer, |
1443 | /// ignoring the metadata. |
1444 | /// |
1445 | /// # Panics |
1446 | /// |
1447 | /// The function panics if `align` is not a power-of-two (this includes 0). |
1448 | /// |
1449 | /// # Examples |
1450 | /// |
1451 | /// ``` |
1452 | /// #![feature(pointer_is_aligned_to)] |
1453 | /// |
1454 | /// // On some platforms, the alignment of i32 is less than 4. |
1455 | /// #[repr(align(4))] |
1456 | /// struct AlignedI32(i32); |
1457 | /// |
1458 | /// let data = AlignedI32(42); |
1459 | /// let ptr = &data as *const AlignedI32; |
1460 | /// |
1461 | /// assert!(ptr.is_aligned_to(1)); |
1462 | /// assert!(ptr.is_aligned_to(2)); |
1463 | /// assert!(ptr.is_aligned_to(4)); |
1464 | /// |
1465 | /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2)); |
1466 | /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4)); |
1467 | /// |
1468 | /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8)); |
1469 | /// ``` |
1470 | #[must_use ] |
1471 | #[inline ] |
1472 | #[unstable (feature = "pointer_is_aligned_to" , issue = "96284" )] |
1473 | pub fn is_aligned_to(self, align: usize) -> bool { |
1474 | if !align.is_power_of_two() { |
1475 | panic!("is_aligned_to: align is not a power-of-two" ); |
1476 | } |
1477 | |
1478 | self.addr() & (align - 1) == 0 |
1479 | } |
1480 | } |
1481 | |
1482 | impl<T> *const [T] { |
1483 | /// Returns the length of a raw slice. |
1484 | /// |
1485 | /// The returned value is the number of **elements**, not the number of bytes. |
1486 | /// |
1487 | /// This function is safe, even when the raw slice cannot be cast to a slice |
1488 | /// reference because the pointer is null or unaligned. |
1489 | /// |
1490 | /// # Examples |
1491 | /// |
1492 | /// ```rust |
1493 | /// use std::ptr; |
1494 | /// |
1495 | /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3); |
1496 | /// assert_eq!(slice.len(), 3); |
1497 | /// ``` |
1498 | #[inline ] |
1499 | #[stable (feature = "slice_ptr_len" , since = "1.79.0" )] |
1500 | #[rustc_const_stable (feature = "const_slice_ptr_len" , since = "1.79.0" )] |
1501 | pub const fn len(self) -> usize { |
1502 | metadata(self) |
1503 | } |
1504 | |
1505 | /// Returns `true` if the raw slice has a length of 0. |
1506 | /// |
1507 | /// # Examples |
1508 | /// |
1509 | /// ``` |
1510 | /// use std::ptr; |
1511 | /// |
1512 | /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3); |
1513 | /// assert!(!slice.is_empty()); |
1514 | /// ``` |
1515 | #[inline (always)] |
1516 | #[stable (feature = "slice_ptr_len" , since = "1.79.0" )] |
1517 | #[rustc_const_stable (feature = "const_slice_ptr_len" , since = "1.79.0" )] |
1518 | pub const fn is_empty(self) -> bool { |
1519 | self.len() == 0 |
1520 | } |
1521 | |
1522 | /// Returns a raw pointer to the slice's buffer. |
1523 | /// |
1524 | /// This is equivalent to casting `self` to `*const T`, but more type-safe. |
1525 | /// |
1526 | /// # Examples |
1527 | /// |
1528 | /// ```rust |
1529 | /// #![feature(slice_ptr_get)] |
1530 | /// use std::ptr; |
1531 | /// |
1532 | /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3); |
1533 | /// assert_eq!(slice.as_ptr(), ptr::null()); |
1534 | /// ``` |
1535 | #[inline ] |
1536 | #[unstable (feature = "slice_ptr_get" , issue = "74265" )] |
1537 | pub const fn as_ptr(self) -> *const T { |
1538 | self as *const T |
1539 | } |
1540 | |
1541 | /// Gets a raw pointer to the underlying array. |
1542 | /// |
1543 | /// If `N` is not exactly equal to the length of `self`, then this method returns `None`. |
1544 | #[unstable (feature = "slice_as_array" , issue = "133508" )] |
1545 | #[inline ] |
1546 | #[must_use ] |
1547 | pub const fn as_array<const N: usize>(self) -> Option<*const [T; N]> { |
1548 | if self.len() == N { |
1549 | let me = self.as_ptr() as *const [T; N]; |
1550 | Some(me) |
1551 | } else { |
1552 | None |
1553 | } |
1554 | } |
1555 | |
1556 | /// Returns a raw pointer to an element or subslice, without doing bounds |
1557 | /// checking. |
1558 | /// |
1559 | /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable |
1560 | /// is *[undefined behavior]* even if the resulting pointer is not used. |
1561 | /// |
1562 | /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html |
1563 | /// |
1564 | /// # Examples |
1565 | /// |
1566 | /// ``` |
1567 | /// #![feature(slice_ptr_get)] |
1568 | /// |
1569 | /// let x = &[1, 2, 4] as *const [i32]; |
1570 | /// |
1571 | /// unsafe { |
1572 | /// assert_eq!(x.get_unchecked(1), x.as_ptr().add(1)); |
1573 | /// } |
1574 | /// ``` |
1575 | #[unstable (feature = "slice_ptr_get" , issue = "74265" )] |
1576 | #[inline ] |
1577 | pub unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output |
1578 | where |
1579 | I: SliceIndex<[T]>, |
1580 | { |
1581 | // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds. |
1582 | unsafe { index.get_unchecked(self) } |
1583 | } |
1584 | |
1585 | /// Returns `None` if the pointer is null, or else returns a shared slice to |
1586 | /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require |
1587 | /// that the value has to be initialized. |
1588 | /// |
1589 | /// [`as_ref`]: #method.as_ref |
1590 | /// |
1591 | /// # Safety |
1592 | /// |
1593 | /// When calling this method, you have to ensure that *either* the pointer is null *or* |
1594 | /// all of the following is true: |
1595 | /// |
1596 | /// * The pointer must be [valid] for reads for `ptr.len() * size_of::<T>()` many bytes, |
1597 | /// and it must be properly aligned. This means in particular: |
1598 | /// |
1599 | /// * The entire memory range of this slice must be contained within a single [allocated object]! |
1600 | /// Slices can never span across multiple allocated objects. |
1601 | /// |
1602 | /// * The pointer must be aligned even for zero-length slices. One |
1603 | /// reason for this is that enum layout optimizations may rely on references |
1604 | /// (including slices of any length) being aligned and non-null to distinguish |
1605 | /// them from other data. You can obtain a pointer that is usable as `data` |
1606 | /// for zero-length slices using [`NonNull::dangling()`]. |
1607 | /// |
1608 | /// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`. |
1609 | /// See the safety documentation of [`pointer::offset`]. |
1610 | /// |
1611 | /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is |
1612 | /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. |
1613 | /// In particular, while this reference exists, the memory the pointer points to must |
1614 | /// not get mutated (except inside `UnsafeCell`). |
1615 | /// |
1616 | /// This applies even if the result of this method is unused! |
1617 | /// |
1618 | /// See also [`slice::from_raw_parts`][]. |
1619 | /// |
1620 | /// [valid]: crate::ptr#safety |
1621 | /// [allocated object]: crate::ptr#allocated-object |
1622 | /// |
1623 | /// # Panics during const evaluation |
1624 | /// |
1625 | /// This method will panic during const evaluation if the pointer cannot be |
1626 | /// determined to be null or not. See [`is_null`] for more information. |
1627 | /// |
1628 | /// [`is_null`]: #method.is_null |
1629 | #[inline ] |
1630 | #[unstable (feature = "ptr_as_uninit" , issue = "75402" )] |
1631 | pub const unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> { |
1632 | if self.is_null() { |
1633 | None |
1634 | } else { |
1635 | // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`. |
1636 | Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) }) |
1637 | } |
1638 | } |
1639 | } |
1640 | |
1641 | impl<T, const N: usize> *const [T; N] { |
1642 | /// Returns a raw pointer to the array's buffer. |
1643 | /// |
1644 | /// This is equivalent to casting `self` to `*const T`, but more type-safe. |
1645 | /// |
1646 | /// # Examples |
1647 | /// |
1648 | /// ```rust |
1649 | /// #![feature(array_ptr_get)] |
1650 | /// use std::ptr; |
1651 | /// |
1652 | /// let arr: *const [i8; 3] = ptr::null(); |
1653 | /// assert_eq!(arr.as_ptr(), ptr::null()); |
1654 | /// ``` |
1655 | #[inline ] |
1656 | #[unstable (feature = "array_ptr_get" , issue = "119834" )] |
1657 | pub const fn as_ptr(self) -> *const T { |
1658 | self as *const T |
1659 | } |
1660 | |
1661 | /// Returns a raw pointer to a slice containing the entire array. |
1662 | /// |
1663 | /// # Examples |
1664 | /// |
1665 | /// ``` |
1666 | /// #![feature(array_ptr_get)] |
1667 | /// |
1668 | /// let arr: *const [i32; 3] = &[1, 2, 4] as *const [i32; 3]; |
1669 | /// let slice: *const [i32] = arr.as_slice(); |
1670 | /// assert_eq!(slice.len(), 3); |
1671 | /// ``` |
1672 | #[inline ] |
1673 | #[unstable (feature = "array_ptr_get" , issue = "119834" )] |
1674 | pub const fn as_slice(self) -> *const [T] { |
1675 | self |
1676 | } |
1677 | } |
1678 | |
1679 | /// Pointer equality is by address, as produced by the [`<*const T>::addr`](pointer::addr) method. |
1680 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1681 | impl<T: ?Sized> PartialEq for *const T { |
1682 | #[inline ] |
1683 | #[allow (ambiguous_wide_pointer_comparisons)] |
1684 | fn eq(&self, other: &*const T) -> bool { |
1685 | *self == *other |
1686 | } |
1687 | } |
1688 | |
1689 | /// Pointer equality is an equivalence relation. |
1690 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1691 | impl<T: ?Sized> Eq for *const T {} |
1692 | |
1693 | /// Pointer comparison is by address, as produced by the `[`<*const T>::addr`](pointer::addr)` method. |
1694 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1695 | impl<T: ?Sized> Ord for *const T { |
1696 | #[inline ] |
1697 | #[allow (ambiguous_wide_pointer_comparisons)] |
1698 | fn cmp(&self, other: &*const T) -> Ordering { |
1699 | if self < other { |
1700 | Less |
1701 | } else if self == other { |
1702 | Equal |
1703 | } else { |
1704 | Greater |
1705 | } |
1706 | } |
1707 | } |
1708 | |
1709 | /// Pointer comparison is by address, as produced by the `[`<*const T>::addr`](pointer::addr)` method. |
1710 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1711 | impl<T: ?Sized> PartialOrd for *const T { |
1712 | #[inline ] |
1713 | #[allow (ambiguous_wide_pointer_comparisons)] |
1714 | fn partial_cmp(&self, other: &*const T) -> Option<Ordering> { |
1715 | Some(self.cmp(other)) |
1716 | } |
1717 | |
1718 | #[inline ] |
1719 | #[allow (ambiguous_wide_pointer_comparisons)] |
1720 | fn lt(&self, other: &*const T) -> bool { |
1721 | *self < *other |
1722 | } |
1723 | |
1724 | #[inline ] |
1725 | #[allow (ambiguous_wide_pointer_comparisons)] |
1726 | fn le(&self, other: &*const T) -> bool { |
1727 | *self <= *other |
1728 | } |
1729 | |
1730 | #[inline ] |
1731 | #[allow (ambiguous_wide_pointer_comparisons)] |
1732 | fn gt(&self, other: &*const T) -> bool { |
1733 | *self > *other |
1734 | } |
1735 | |
1736 | #[inline ] |
1737 | #[allow (ambiguous_wide_pointer_comparisons)] |
1738 | fn ge(&self, other: &*const T) -> bool { |
1739 | *self >= *other |
1740 | } |
1741 | } |
1742 | |