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