Skip to main content

core/ptr/
mod.rs

1//! Manually manage memory through raw pointers.
2//!
3//! *[See also the pointer primitive types](pointer).*
4//!
5//! # Safety
6//!
7//! Many functions in this module take raw pointers as arguments and read from or write to them. For
8//! this to be safe, these pointers must be *valid* for the given access. Whether a pointer is valid
9//! depends on the operation it is used for (read or write), and the extent of the memory that is
10//! accessed (i.e., how many bytes are read/written) -- it makes no sense to ask "is this pointer
11//! valid"; one has to ask "is this pointer valid for a given access". Most functions use `*mut T`
12//! and `*const T` to access only a single value, in which case the documentation omits the size and
13//! implicitly assumes it to be `size_of::<T>()` bytes.
14//!
15//! The precise rules for validity are not determined yet. The guarantees that are
16//! provided at this point are very minimal:
17//!
18//! * A [null] pointer is *never* valid for reads/writes.
19//! * For memory accesses of [size zero][zst], *every* non-null pointer is valid for reads/writes.
20//!   The following points are only concerned with non-zero-sized accesses.
21//! * For a pointer to be valid for reads/writes, it is necessary, but not always sufficient, that
22//!   the pointer be *dereferenceable*. The [provenance] of the pointer is used to determine which
23//!   [allocation] it is derived from; a pointer is dereferenceable if the memory range of the given
24//!   size starting at the pointer is entirely contained within the bounds of that allocation. Note
25//!   that in Rust, every (stack-allocated) variable is considered a separate allocation.
26//! * All accesses performed by functions in this module are *non-atomic* in the sense
27//!   of [atomic operations] used to synchronize between threads. This means it is
28//!   undefined behavior to perform two concurrent accesses to the same location from different
29//!   threads unless both accesses only read from memory.
30//! * The result of casting a reference to a pointer is valid for reads/writes for as long as the
31//!   underlying allocation is live and no reference (just raw pointers) is used to
32//!   access the same memory. That is, reference and pointer accesses cannot be
33//!   interleaved.
34//!
35//! These axioms, along with careful use of [`offset`] for pointer arithmetic,
36//! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
37//! will be provided eventually, as the [aliasing] rules are being determined. For more
38//! information, see the [book] as well as the section in the reference devoted
39//! to [undefined behavior][ub].
40//!
41//! Note that some operations such as [`read`] and [`write`][`write()`] do allow null pointers if
42//! the total size of the access is zero. However, other operations internally convert pointers into
43//! references. Therefore, the general notion of "valid for reads/writes" excludes null pointers,
44//! and the specific operations that permit null pointers mention that as an exception. Furthermore,
45//! [`read_volatile`] and [`write_volatile`] can be used in even more situations; see their
46//! documentation for details.
47//!
48//! We say that a pointer is "dangling" if it is not valid for any non-zero-sized accesses. This
49//! means out-of-bounds pointers, pointers to freed memory, null pointers, and pointers created with
50//! [`NonNull::dangling`] are all dangling.
51//!
52//! ## Alignment
53//!
54//! Valid raw pointers as defined above are not necessarily properly aligned (where
55//! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
56//! aligned to `align_of::<T>()`). However, most functions require their
57//! arguments to be properly aligned, and will explicitly state
58//! this requirement in their documentation. Notable exceptions to this are
59//! [`read_unaligned`] and [`write_unaligned`].
60//!
61//! When a function requires proper alignment, it does so even if the access
62//! has size 0, i.e., even if memory is not actually touched. Consider using
63//! [`NonNull::dangling`] in such cases.
64//!
65//! ## Pointer to reference conversion
66//!
67//! When converting a pointer to a reference (e.g. via `&*ptr` or `&mut *ptr`),
68//! there are several rules that must be followed:
69//!
70//! * The pointer must be properly aligned.
71//!
72//! * It must be non-null.
73//!
74//! * It must be "dereferenceable" in the sense defined above.
75//!
76//! * The pointer must point to a [valid value] of type `T`.
77//!
78//! * You must enforce Rust's aliasing rules. The exact aliasing rules are not decided yet, so we
79//!   only give a rough overview here. The rules also depend on whether a mutable or a shared
80//!   reference is being created.
81//!   * When creating a mutable reference, then while this reference exists, the memory it points to
82//!     must not get accessed (read or written) through any other pointer or reference not derived
83//!     from this reference.
84//!   * When creating a shared reference, then while this reference exists, the memory it points to
85//!     must not get mutated (except inside `UnsafeCell`).
86//!
87//! If a pointer follows all of these rules, it is said to be
88//! *convertible to a (mutable or shared) reference*.
89// ^ we use this term instead of saying that the produced reference must
90// be valid, as the validity of a reference is easily confused for the
91// validity of the thing it refers to, and while the two concepts are
92// closely related, they are not identical.
93//!
94//! These rules apply even if the result is unused!
95//! (The part about being initialized is not yet fully decided, but until
96//! it is, the only safe approach is to ensure that they are indeed initialized.)
97//!
98//! An example of the implications of the above rules is that an expression such
99//! as `unsafe { &*(0 as *const u8) }` is Immediate Undefined Behavior.
100//!
101//! [valid value]: ../../reference/behavior-considered-undefined.html#invalid-values
102//!
103//! ## Allocation
104//!
105//! <a id="allocated-object"></a> <!-- keep old URLs working -->
106//!
107//! An *allocation* is a subset of program memory which is addressable
108//! from Rust, and within which pointer arithmetic is possible. Examples of
109//! allocations include heap allocations, stack-allocated variables,
110//! statics, and consts. The safety preconditions of some Rust operations -
111//! such as `offset` and field projections (`expr.field`) - are defined in
112//! terms of the allocations on which they operate.
113//!
114//! An allocation has a base address, a size, and a set of memory
115//! addresses. It is possible for an allocation to have zero size, but
116//! such an allocation will still have a base address. The base address
117//! of an allocation is not necessarily unique. While it is currently the
118//! case that an allocation always has a set of memory addresses which is
119//! fully contiguous (i.e., has no "holes"), there is no guarantee that this
120//! will not change in the future.
121//!
122//! Allocations must behave like "normal" memory: in particular, reads must not have
123//! side-effects, and writes must become visible to other threads using the usual synchronization
124//! primitives.
125//!
126//! For any allocation with `base` address, `size`, and a set of
127//! `addresses`, the following are guaranteed:
128//! - For all addresses `a` in `addresses`, `a` is in the range `base .. (base +
129//!   size)` (note that this requires `a < base + size`, not `a <= base + size`)
130//! - `base` is not equal to [`null()`] (i.e., the address with the numerical
131//!   value 0)
132//! - `base + size <= usize::MAX`
133//! - `size <= isize::MAX`
134//!
135//! As a consequence of these guarantees, given any address `a` within the set
136//! of addresses of an allocation:
137//! - It is guaranteed that `a - base` does not overflow `isize`
138//! - It is guaranteed that `a - base` is non-negative
139//! - It is guaranteed that, given `o = a - base` (i.e., the offset of `a` within
140//!   the allocation), `base + o` will not wrap around the address space (in
141//!   other words, will not overflow `usize`)
142//!
143//! [`null()`]: null
144//!
145//! # Provenance
146//!
147//! Pointers are not *simply* an "integer" or "address". For instance, it's uncontroversial
148//! to say that a Use After Free is clearly Undefined Behavior, even if you "get lucky"
149//! and the freed memory gets reallocated before your read/write (in fact this is the
150//! worst-case scenario, UAFs would be much less concerning if this didn't happen!).
151//! As another example, consider that [`wrapping_offset`] is documented to "remember"
152//! the allocation that the original pointer points to, even if it is offset far
153//! outside the memory range occupied by that allocation.
154//! To rationalize claims like this, pointers need to somehow be *more* than just their addresses:
155//! they must have **provenance**.
156//!
157//! A pointer value in Rust semantically contains the following information:
158//!
159//! * The **address** it points to, which can be represented by a `usize`.
160//! * The **provenance** it has, defining the memory it has permission to access. Provenance can be
161//!   absent, in which case the pointer does not have permission to access any memory.
162//!
163//! The exact structure of provenance is not yet specified, but the permission defined by a
164//! pointer's provenance have a *spatial* component, a *temporal* component, and a *mutability*
165//! component:
166//!
167//! * Spatial: The set of memory addresses that the pointer is allowed to access.
168//! * Temporal: The timespan during which the pointer is allowed to access those memory addresses.
169//! * Mutability: Whether the pointer may only access the memory for reads, or also access it for
170//!   writes. Note that this can interact with the other components, e.g. a pointer might permit
171//!   mutation only for a subset of addresses, or only for a subset of its maximal timespan.
172//!
173//! When an [allocation] is created, it has a unique Original Pointer. For alloc
174//! APIs this is literally the pointer the call returns, and for local variables and statics,
175//! this is the name of the variable/static. (This is mildly overloading the term "pointer"
176//! for the sake of brevity/exposition.)
177//!
178//! The Original Pointer for an allocation has provenance that constrains the *spatial*
179//! permissions of this pointer to the memory range of the allocation, and the *temporal*
180//! permissions to the lifetime of the allocation. Provenance is implicitly inherited by all
181//! pointers transitively derived from the Original Pointer through operations like [`offset`],
182//! borrowing, and pointer casts. Some operations may *shrink* the permissions of the derived
183//! provenance, limiting how much memory it can access or how long it's valid for (i.e. borrowing a
184//! subfield and subslicing can shrink the spatial component of provenance, and all borrowing can
185//! shrink the temporal component of provenance). However, no operation can ever *grow* the
186//! permissions of the derived provenance: even if you "know" there is a larger allocation, you
187//! can't derive a pointer with a larger provenance. Similarly, you cannot "recombine" two
188//! contiguous provenances back into one (i.e. with a `fn merge(&[T], &[T]) -> &[T]`).
189//!
190//! A reference to a place always has provenance over at least the memory that place occupies.
191//! A reference to a slice always has provenance over at least the range that slice describes.
192//! Whether and when exactly the provenance of a reference gets "shrunk" to *exactly* fit
193//! the memory it points to is not yet determined.
194//!
195//! A *shared* reference only ever has provenance that permits reading from memory,
196//! and never permits writes, except inside [`UnsafeCell`].
197//!
198//! Provenance can affect whether a program has undefined behavior:
199//!
200//! * It is undefined behavior to access memory through a pointer that does not have provenance over
201//!   that memory. Note that a pointer "at the end" of its provenance is not actually outside its
202//!   provenance, it just has 0 bytes it can load/store. Zero-sized accesses do not require any
203//!   provenance since they access an empty range of memory.
204//!
205//! * It is undefined behavior to [`offset`] a pointer across a memory range that is not contained
206//!   in the allocation it is derived from, or to [`offset_from`] two pointers not derived
207//!   from the same allocation. Provenance is used to say what exactly "derived from" even
208//!   means: the lineage of a pointer is traced back to the Original Pointer it descends from, and
209//!   that identifies the relevant allocation. In particular, it's always UB to offset a
210//!   pointer derived from something that is now deallocated, except if the offset is 0.
211//!
212//! But it *is* still sound to:
213//!
214//! * Create a pointer without provenance from just an address (see [`without_provenance`]). Such a
215//!   pointer cannot be used for memory accesses (except for zero-sized accesses). This can still be
216//!   useful for sentinel values like `null` *or* to represent a tagged pointer that will never be
217//!   dereferenceable. In general, it is always sound for an integer to pretend to be a pointer "for
218//!   fun" as long as you don't use operations on it which require it to be valid (non-zero-sized
219//!   offset, read, write, etc).
220//!
221//! * Forge an allocation of size zero at any sufficiently aligned non-null address.
222//!   i.e. the usual "ZSTs are fake, do what you want" rules apply.
223//!
224//! * [`wrapping_offset`] a pointer outside its provenance. This includes pointers
225//!   which have "no" provenance. In particular, this makes it sound to do pointer tagging tricks.
226//!
227//! * Compare arbitrary pointers by address. Pointer comparison ignores provenance and addresses
228//!   *are* just integers, so there is always a coherent answer, even if the pointers are dangling
229//!   or from different provenances. Note that if you get "lucky" and notice that a pointer at the
230//!   end of one allocation is the "same" address as the start of another allocation,
231//!   anything you do with that fact is *probably* going to be gibberish. The scope of that
232//!   gibberish is kept under control by the fact that the two pointers *still* aren't allowed to
233//!   access the other's allocation (bytes), because they still have different provenance.
234//!
235//! Note that the full definition of provenance in Rust is not decided yet, as this interacts
236//! with the as-yet undecided [aliasing] rules.
237//!
238//! ## Pointers Vs Integers
239//!
240//! From this discussion, it becomes very clear that a `usize` *cannot* accurately represent a pointer,
241//! and converting from a pointer to a `usize` is generally an operation which *only* extracts the
242//! address. Converting this address back into pointer requires somehow answering the question:
243//! which provenance should the resulting pointer have?
244//!
245//! Rust provides two ways of dealing with this situation: *Strict Provenance* and *Exposed Provenance*.
246//!
247//! Note that a pointer *can* represent a `usize` (via [`without_provenance`]), so the right type to
248//! use in situations where a value is "sometimes a pointer and sometimes a bare `usize`" is a
249//! pointer type.
250//!
251//! ## Strict Provenance
252//!
253//! "Strict Provenance" refers to a set of APIs designed to make working with provenance more
254//! explicit. They are intended as substitutes for casting a pointer to an integer and back.
255//!
256//! Entirely avoiding integer-to-pointer casts successfully side-steps the inherent ambiguity of
257//! that operation. This benefits compiler optimizations, and it is pretty much a requirement for
258//! using tools like [Miri] and architectures like [CHERI] that aim to detect and diagnose pointer
259//! misuse.
260//!
261//! The key insight to making programming without integer-to-pointer casts *at all* viable is the
262//! [`with_addr`] method:
263//!
264//! ```text
265//! /// Creates a new pointer with the given address and the provenance  of `self`.
266//! ///
267//! /// This is similar to a `addr as *const T` cast,
268//! /// but copies the provenance of `self` to the new pointer.
269//! /// This avoids the inherent ambiguity of the unary cast.
270//! ///
271//! /// This is equivalent to using `wrapping_offset` to offset `self` to the given address,
272//! /// and therefore has all the same capabilities and restrictions.
273//! pub fn with_addr(self, addr: usize) -> Self;
274//! ```
275//!
276//! So you're still able to drop down to the address representation and do whatever
277//! clever bit tricks you want *as long as* you're able to keep around a pointer
278//! into the allocation you care about that can "reconstitute" the provenance.
279//! Usually this is very easy, because you only are taking a pointer, messing with the address,
280//! and then immediately converting back to a pointer. To make this use case more ergonomic,
281//! we provide the [`map_addr`] method.
282//!
283//! To help make it clear that code is "following" Strict Provenance semantics, we also provide an
284//! [`addr`] method which promises that the returned address is not part of a
285//! pointer-integer-pointer roundtrip. In the future we may provide a lint for pointer<->integer
286//! casts to help you audit if your code conforms to strict provenance.
287//!
288//! ### Using Strict Provenance
289//!
290//! Most code needs no changes to conform to strict provenance, as the only really concerning
291//! operation is casts from `usize` to a pointer. For code which *does* cast a `usize` to a pointer,
292//! the scope of the change depends on exactly what you're doing.
293//!
294//! In general, you just need to make sure that if you want to convert a `usize` address to a
295//! pointer and then use that pointer to read/write memory, you need to keep around a pointer
296//! that has sufficient provenance to perform that read/write itself. In this way all of your
297//! casts from an address to a pointer are essentially just applying offsets/indexing.
298//!
299//! This is generally trivial to do for simple cases like tagged pointers *as long as you
300//! represent the tagged pointer as an actual pointer and not a `usize`*. For instance:
301//!
302//! ```
303//! unsafe {
304//!     // A flag we want to pack into our pointer
305//!     static HAS_DATA: usize = 0x1;
306//!     static FLAG_MASK: usize = !HAS_DATA;
307//!
308//!     // Our value, which must have enough alignment to have spare least-significant-bits.
309//!     let my_precious_data: u32 = 17;
310//!     assert!(align_of::<u32>() > 1);
311//!
312//!     // Create a tagged pointer
313//!     let ptr = &my_precious_data as *const u32;
314//!     let tagged = ptr.map_addr(|addr| addr | HAS_DATA);
315//!
316//!     // Check the flag:
317//!     if tagged.addr() & HAS_DATA != 0 {
318//!         // Untag and read the pointer
319//!         let data = *tagged.map_addr(|addr| addr & FLAG_MASK);
320//!         assert_eq!(data, 17);
321//!     } else {
322//!         unreachable!()
323//!     }
324//! }
325//! ```
326//!
327//! (Yes, if you've been using [`AtomicUsize`] for pointers in concurrent datastructures, you should
328//! be using [`AtomicPtr`] instead. If that messes up the way you atomically manipulate pointers,
329//! we would like to know why, and what needs to be done to fix it.)
330//!
331//! Situations where a valid pointer *must* be created from just an address, such as baremetal code
332//! accessing a memory-mapped interface at a fixed address, cannot currently be handled with strict
333//! provenance APIs and should use [exposed provenance](#exposed-provenance).
334//!
335//! ## Exposed Provenance
336//!
337//! As discussed above, integer-to-pointer casts are not possible with Strict Provenance APIs.
338//! This is by design: the goal of Strict Provenance is to provide a clear specification that we are
339//! confident can be formalized unambiguously and can be subject to precise formal reasoning.
340//! Integer-to-pointer casts do not (currently) have such a clear specification.
341//!
342//! However, there exist situations where integer-to-pointer casts cannot be avoided, or
343//! where avoiding them would require major refactoring. Legacy platform APIs also regularly assume
344//! that `usize` can capture all the information that makes up a pointer.
345//! Bare-metal platforms can also require the synthesis of a pointer "out of thin air" without
346//! anywhere to obtain proper provenance from.
347//!
348//! Rust's model for dealing with integer-to-pointer casts is called *Exposed Provenance*. However,
349//! the semantics of Exposed Provenance are on much less solid footing than Strict Provenance, and
350//! at this point it is not yet clear whether a satisfying unambiguous semantics can be defined for
351//! Exposed Provenance. (If that sounds bad, be reassured that other popular languages that provide
352//! integer-to-pointer casts are not faring any better.) Furthermore, Exposed Provenance will not
353//! work (well) with tools like [Miri] and [CHERI].
354//!
355//! Exposed Provenance is provided by the [`expose_provenance`] and [`with_exposed_provenance`] methods,
356//! which are equivalent to `as` casts between pointers and integers.
357//! - [`expose_provenance`] is a lot like [`addr`], but additionally adds the provenance of the
358//!   pointer to a global list of 'exposed' provenances. (This list is purely conceptual, it exists
359//!   for the purpose of specifying Rust but is not materialized in actual executions, except in
360//!   tools like [Miri].)
361//!   Memory which is outside the control of the Rust abstract machine (MMIO registers, for example)
362//!   is always considered to be exposed, so long as this memory is disjoint from memory that will
363//!   be used by the abstract machine such as the stack, heap, and statics.
364//! - [`with_exposed_provenance`] can be used to construct a pointer with one of these previously
365//!   'exposed' provenances. [`with_exposed_provenance`] takes only `addr: usize` as arguments, so
366//!   unlike in [`with_addr`] there is no indication of what the correct provenance for the returned
367//!   pointer is -- and that is exactly what makes integer-to-pointer casts so tricky to rigorously
368//!   specify! The compiler will do its best to pick the right provenance for you, but currently we
369//!   cannot provide any guarantees about which provenance the resulting pointer will have. Only one
370//!   thing is clear: if there is *no* previously 'exposed' provenance that justifies the way the
371//!   returned pointer will be used, the program has undefined behavior.
372//!
373//! If at all possible, we encourage code to be ported to [Strict Provenance] APIs, thus avoiding
374//! the need for Exposed Provenance. Maximizing the amount of such code is a major win for avoiding
375//! specification complexity and to facilitate adoption of tools like [CHERI] and [Miri] that can be
376//! a big help in increasing the confidence in (unsafe) Rust code. However, we acknowledge that this
377//! is not always possible, and offer Exposed Provenance as a way to explicit "opt out" of the
378//! well-defined semantics of Strict Provenance, and "opt in" to the unclear semantics of
379//! integer-to-pointer casts.
380//!
381//! [aliasing]: ../../nomicon/aliasing.html
382//! [allocation]: #allocation
383//! [provenance]: #provenance
384//! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
385//! [ub]: ../../reference/behavior-considered-undefined.html
386//! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
387//! [atomic operations]: crate::sync::atomic
388//! [`offset`]: pointer::offset
389//! [`offset_from`]: pointer::offset_from
390//! [`wrapping_offset`]: pointer::wrapping_offset
391//! [`with_addr`]: pointer::with_addr
392//! [`map_addr`]: pointer::map_addr
393//! [`addr`]: pointer::addr
394//! [`AtomicUsize`]: crate::sync::atomic::AtomicUsize
395//! [`AtomicPtr`]: crate::sync::atomic::AtomicPtr
396//! [`expose_provenance`]: pointer::expose_provenance
397//! [`with_exposed_provenance`]: with_exposed_provenance
398//! [Miri]: https://github.com/rust-lang/miri
399//! [CHERI]: https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/
400//! [Strict Provenance]: #strict-provenance
401//! [`UnsafeCell`]: core::cell::UnsafeCell
402
403#![stable(feature = "rust1", since = "1.0.0")]
404// There are many unsafe functions taking pointers that don't dereference them.
405#![allow(clippy::not_unsafe_ptr_arg_deref)]
406
407use crate::cmp::Ordering;
408use crate::intrinsics::const_eval_select;
409use crate::marker::{Destruct, FnPtr, PointeeSized};
410use crate::mem::{self, MaybeUninit, SizedTypeProperties};
411use crate::num::NonZero;
412use crate::{fmt, hash, intrinsics, ub_checks};
413
414#[unstable(feature = "ptr_alignment_type", issue = "102070")]
415#[deprecated(since = "1.96.0", note = "moved from `ptr` to `mem`")]
416/// Deprecated re-export of [mem::Alignment].
417pub type Alignment = mem::Alignment;
418
419mod metadata;
420#[unstable(feature = "ptr_metadata", issue = "81513")]
421pub use metadata::{DynMetadata, Pointee, Thin, from_raw_parts, from_raw_parts_mut, metadata};
422
423mod non_null;
424#[stable(feature = "nonnull", since = "1.25.0")]
425pub use non_null::NonNull;
426
427mod unique;
428#[unstable(feature = "ptr_internals", issue = "none")]
429pub use unique::Unique;
430
431mod const_ptr;
432mod mut_ptr;
433
434// Some functions are defined here because they accidentally got made
435// available in this module on stable. See <https://github.com/rust-lang/rust/issues/15702>.
436// (`transmute` also falls into this category, but it cannot be wrapped due to the
437// check that `T` and `U` have the same size.)
438
439/// Copies `count * size_of::<T>()` bytes from `src` to `dst`. The source
440/// and destination must *not* overlap.
441///
442/// For regions of memory which might overlap, use [`copy`] instead.
443///
444/// `copy_nonoverlapping` is semantically equivalent to C's [`memcpy`], but
445/// with the source and destination arguments swapped,
446/// and `count` counting the number of `T`s instead of bytes.
447///
448/// The copy is "untyped" in the sense that data may be uninitialized or otherwise violate the
449/// requirements of `T`. The initialization state is preserved exactly.
450///
451/// [`memcpy`]: https://en.cppreference.com/w/c/string/byte/memcpy
452///
453/// # Safety
454///
455/// Behavior is undefined if any of the following conditions are violated:
456///
457/// * `src` must be [valid] for reads of `count * size_of::<T>()` bytes or that number must be 0.
458///
459/// * `dst` must be [valid] for writes of `count * size_of::<T>()` bytes or that number must be 0.
460///
461/// * Both `src` and `dst` must be properly aligned.
462///
463/// * The region of memory beginning at `src` with a size of `count *
464///   size_of::<T>()` bytes must *not* overlap with the region of memory
465///   beginning at `dst` with the same size.
466///
467/// Like [`read`], `copy_nonoverlapping` creates a bitwise copy of `T`, regardless of
468/// whether `T` is [`Copy`]. If `T` is not [`Copy`], using *both* the values
469/// in the region beginning at `*src` and the region beginning at `*dst` can
470/// [violate memory safety][read-ownership].
471///
472/// Note that even if the effectively copied size (`count * size_of::<T>()`) is
473/// `0`, the pointers must be properly aligned.
474///
475/// [`read`]: crate::ptr::read
476/// [read-ownership]: crate::ptr::read#ownership-of-the-returned-value
477/// [valid]: crate::ptr#safety
478///
479/// # Examples
480///
481/// Manually implement [`Vec::append`]:
482///
483/// ```
484/// use std::ptr;
485///
486/// /// Moves all the elements of `src` into `dst`, leaving `src` empty.
487/// fn append<T>(dst: &mut Vec<T>, src: &mut Vec<T>) {
488///     let src_len = src.len();
489///     let dst_len = dst.len();
490///
491///     // Ensure that `dst` has enough capacity to hold all of `src`.
492///     dst.reserve(src_len);
493///
494///     unsafe {
495///         // The call to add is always safe because `Vec` will never
496///         // allocate more than `isize::MAX` bytes.
497///         let dst_ptr = dst.as_mut_ptr().add(dst_len);
498///         let src_ptr = src.as_ptr();
499///
500///         // Truncate `src` without dropping its contents. We do this first,
501///         // to avoid problems in case something further down panics.
502///         src.set_len(0);
503///
504///         // The two regions cannot overlap because mutable references do
505///         // not alias, and two different vectors cannot own the same
506///         // memory.
507///         ptr::copy_nonoverlapping(src_ptr, dst_ptr, src_len);
508///
509///         // Notify `dst` that it now holds the contents of `src`.
510///         dst.set_len(dst_len + src_len);
511///     }
512/// }
513///
514/// let mut a = vec!['r'];
515/// let mut b = vec!['u', 's', 't'];
516///
517/// append(&mut a, &mut b);
518///
519/// assert_eq!(a, &['r', 'u', 's', 't']);
520/// assert!(b.is_empty());
521/// ```
522///
523/// [`Vec::append`]: ../../std/vec/struct.Vec.html#method.append
524#[doc(alias = "memcpy")]
525#[stable(feature = "rust1", since = "1.0.0")]
526#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
527#[inline(always)]
528#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
529#[rustc_diagnostic_item = "ptr_copy_nonoverlapping"]
530#[ferrocene::prevalidated]
531pub const unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize) {
532    ub_checks::assert_unsafe_precondition!(
533        check_language_ub,
534        "ptr::copy_nonoverlapping requires that both pointer arguments are aligned and non-null \
535        and the specified memory ranges do not overlap",
536        (
537            src: *const () = src as *const (),
538            dst: *mut () = dst as *mut (),
539            size: usize = size_of::<T>(),
540            align: usize = align_of::<T>(),
541            count: usize = count,
542        ) => {
543            let zero_size = count == 0 || size == 0;
544            ub_checks::maybe_is_aligned_and_not_null(src, align, zero_size)
545                && ub_checks::maybe_is_aligned_and_not_null(dst, align, zero_size)
546                && ub_checks::maybe_is_nonoverlapping(src, dst, size, count)
547        }
548    );
549
550    // SAFETY: the safety contract for `copy_nonoverlapping` must be
551    // upheld by the caller.
552    unsafe { crate::intrinsics::copy_nonoverlapping(src, dst, count) }
553}
554
555/// Copies `count * size_of::<T>()` bytes from `src` to `dst`. The source
556/// and destination may overlap.
557///
558/// If the source and destination will *never* overlap,
559/// [`copy_nonoverlapping`] can be used instead.
560///
561/// `copy` is semantically equivalent to C's [`memmove`], but
562/// with the source and destination arguments swapped,
563/// and `count` counting the number of `T`s instead of bytes.
564/// Copying takes place as if the bytes were copied from `src`
565/// to a temporary array and then copied from the array to `dst`.
566///
567/// The copy is "untyped" in the sense that data may be uninitialized or otherwise violate the
568/// requirements of `T`. The initialization state is preserved exactly.
569///
570/// [`memmove`]: https://en.cppreference.com/w/c/string/byte/memmove
571///
572/// # Safety
573///
574/// Behavior is undefined if any of the following conditions are violated:
575///
576/// * `src` must be [valid] for reads of `count * size_of::<T>()` bytes or that number must be 0.
577///
578/// * `dst` must be [valid] for writes of `count * size_of::<T>()` bytes or that number must be 0,
579///   and `dst` must remain valid even when `src` is read for `count * size_of::<T>()` bytes. (This
580///   means if the memory ranges overlap, the `dst` pointer must not be invalidated by `src` reads.)
581///
582/// * Both `src` and `dst` must be properly aligned.
583///
584/// Like [`read`], `copy` creates a bitwise copy of `T`, regardless of
585/// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the values
586/// in the region beginning at `*src` and the region beginning at `*dst` can
587/// [violate memory safety][read-ownership].
588///
589/// Note that even if the effectively copied size (`count * size_of::<T>()`) is
590/// `0`, the pointers must be properly aligned.
591///
592/// [`read`]: crate::ptr::read
593/// [read-ownership]: crate::ptr::read#ownership-of-the-returned-value
594/// [valid]: crate::ptr#safety
595///
596/// # Examples
597///
598/// Efficiently create a Rust vector from an unsafe buffer:
599///
600/// ```
601/// use std::ptr;
602///
603/// /// # Safety
604/// ///
605/// /// * `ptr` must be correctly aligned for its type and non-zero.
606/// /// * `ptr` must be valid for reads of `elts` contiguous elements of type `T`.
607/// /// * Those elements must not be used after calling this function unless `T: Copy`.
608/// # #[allow(dead_code)]
609/// unsafe fn from_buf_raw<T>(ptr: *const T, elts: usize) -> Vec<T> {
610///     let mut dst = Vec::with_capacity(elts);
611///
612///     // SAFETY: Our precondition ensures the source is aligned and valid,
613///     // and `Vec::with_capacity` ensures that we have usable space to write them.
614///     unsafe { ptr::copy(ptr, dst.as_mut_ptr(), elts); }
615///
616///     // SAFETY: We created it with this much capacity earlier,
617///     // and the previous `copy` has initialized these elements.
618///     unsafe { dst.set_len(elts); }
619///     dst
620/// }
621/// ```
622#[doc(alias = "memmove")]
623#[stable(feature = "rust1", since = "1.0.0")]
624#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
625#[inline(always)]
626#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
627#[rustc_diagnostic_item = "ptr_copy"]
628#[ferrocene::prevalidated]
629pub const unsafe fn copy<T>(src: *const T, dst: *mut T, count: usize) {
630    // SAFETY: the safety contract for `copy` must be upheld by the caller.
631    unsafe {
632        ub_checks::assert_unsafe_precondition!(
633            check_language_ub,
634            "ptr::copy requires that both pointer arguments are aligned and non-null",
635            (
636                src: *const () = src as *const (),
637                dst: *mut () = dst as *mut (),
638                align: usize = align_of::<T>(),
639                zero_size: bool = T::IS_ZST || count == 0,
640            ) =>
641            ub_checks::maybe_is_aligned_and_not_null(src, align, zero_size)
642                && ub_checks::maybe_is_aligned_and_not_null(dst, align, zero_size)
643        );
644        crate::intrinsics::copy(src, dst, count)
645    }
646}
647
648/// Sets `count * size_of::<T>()` bytes of memory starting at `dst` to
649/// `val`.
650///
651/// `write_bytes` is similar to C's [`memset`], but sets `count *
652/// size_of::<T>()` bytes to `val`.
653///
654/// [`memset`]: https://en.cppreference.com/w/c/string/byte/memset
655///
656/// # Safety
657///
658/// Behavior is undefined if any of the following conditions are violated:
659///
660/// * `dst` must be [valid] for writes of `count * size_of::<T>()` bytes.
661///
662/// * `dst` must be properly aligned.
663///
664/// Note that even if the effectively copied size (`count * size_of::<T>()`) is
665/// `0`, the pointer must be properly aligned.
666///
667/// Additionally, note that changing `*dst` in this way can easily lead to undefined behavior (UB)
668/// later if the written bytes are not a valid representation of some `T`. For instance, the
669/// following is an **incorrect** use of this function:
670///
671/// ```rust,no_run
672/// unsafe {
673///     let mut value: u8 = 0;
674///     let ptr: *mut bool = &mut value as *mut u8 as *mut bool;
675///     let _bool = ptr.read(); // This is fine, `ptr` points to a valid `bool`.
676///     ptr.write_bytes(42u8, 1); // This function itself does not cause UB...
677///     let _bool = ptr.read(); // ...but it makes this operation UB! ⚠️
678/// }
679/// ```
680///
681/// [valid]: crate::ptr#safety
682///
683/// # Examples
684///
685/// Basic usage:
686///
687/// ```
688/// use std::ptr;
689///
690/// let mut vec = vec![0u32; 4];
691/// unsafe {
692///     let vec_ptr = vec.as_mut_ptr();
693///     ptr::write_bytes(vec_ptr, 0xfe, 2);
694/// }
695/// assert_eq!(vec, [0xfefefefe, 0xfefefefe, 0, 0]);
696/// ```
697#[doc(alias = "memset")]
698#[stable(feature = "rust1", since = "1.0.0")]
699#[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
700#[inline(always)]
701#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
702#[rustc_diagnostic_item = "ptr_write_bytes"]
703#[ferrocene::prevalidated]
704pub const unsafe fn write_bytes<T>(dst: *mut T, val: u8, count: usize) {
705    // SAFETY: the safety contract for `write_bytes` must be upheld by the caller.
706    unsafe {
707        ub_checks::assert_unsafe_precondition!(
708            check_language_ub,
709            "ptr::write_bytes requires that the destination pointer is aligned and non-null",
710            (
711                addr: *const () = dst as *const (),
712                align: usize = align_of::<T>(),
713                zero_size: bool = T::IS_ZST || count == 0,
714            ) => ub_checks::maybe_is_aligned_and_not_null(addr, align, zero_size)
715        );
716        crate::intrinsics::write_bytes(dst, val, count)
717    }
718}
719
720/// Executes the destructor (if any) of the pointed-to value.
721///
722/// This is almost the same as calling [`ptr::read`] and discarding
723/// the result, but has the following advantages:
724// FIXME: say something more useful than "almost the same"?
725// There are open questions here: `read` requires the value to be fully valid, e.g. if `T` is a
726// `bool` it must be 0 or 1, if it is a reference then it must be dereferenceable. `drop_in_place`
727// only requires that `*to_drop` be "valid for dropping" and we have not defined what that means. In
728// Miri it currently (May 2024) requires nothing at all for types without drop glue.
729///
730/// * It is *required* to use `drop_in_place` to drop unsized types like
731///   trait objects, because they can't be read out onto the stack and
732///   dropped normally.
733///
734/// * It is friendlier to the optimizer to do this over [`ptr::read`] when
735///   dropping manually allocated memory (e.g., in the implementations of
736///   `Box`/`Rc`/`Vec`), as the compiler doesn't need to prove that it's
737///   sound to elide the copy.
738///
739/// * It can be used to drop [pinned] data when `T` is not `repr(packed)`
740///   (pinned data must not be moved before it is dropped).
741///
742/// Unaligned values cannot be dropped in place, they must be copied to an aligned
743/// location first using [`ptr::read_unaligned`]. For packed structs, this move is
744/// done automatically by the compiler. This means the fields of packed structs
745/// are not dropped in-place.
746///
747/// [`ptr::read`]: self::read
748/// [`ptr::read_unaligned`]: self::read_unaligned
749/// [pinned]: crate::pin
750///
751/// # Safety
752///
753/// Behavior is undefined if any of the following conditions are violated:
754///
755/// * `to_drop` must be [valid] for both reads and writes.
756///
757/// * `to_drop` must be properly aligned, even if `T` has size 0.
758///
759/// * `to_drop` must be nonnull, even if `T` has size 0.
760///
761/// * The value `to_drop` points to must be valid for dropping, which may mean
762///   it must uphold additional invariants. These invariants depend on the type
763///   of the value being dropped. For instance, when dropping a Box, the box's
764///   pointer to the heap must be valid.
765///
766/// * While `drop_in_place` is executing, the only way to access parts of
767///   `to_drop` is through the `&mut self` references supplied to the
768///   `Drop::drop` methods that `drop_in_place` invokes.
769///
770/// Additionally, if `T` is not [`Copy`], using the pointed-to value after
771/// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
772/// foo` counts as a use because it will cause the value to be dropped
773/// again. [`write()`] can be used to overwrite data without causing it to be
774/// dropped.
775///
776/// [valid]: self#safety
777///
778/// # Examples
779///
780/// Manually remove the last item from a vector:
781///
782/// ```
783/// use std::ptr;
784/// use std::rc::Rc;
785///
786/// let last = Rc::new(1);
787/// let weak = Rc::downgrade(&last);
788///
789/// let mut v = vec![Rc::new(0), last];
790///
791/// unsafe {
792///     // Get a raw pointer to the last element in `v`.
793///     let ptr = &mut v[1] as *mut _;
794///     // Shorten `v` to prevent the last item from being dropped. We do that first,
795///     // to prevent issues if the `drop_in_place` below panics.
796///     v.set_len(1);
797///     // Without a call `drop_in_place`, the last item would never be dropped,
798///     // and the memory it manages would be leaked.
799///     ptr::drop_in_place(ptr);
800/// }
801///
802/// assert_eq!(v, &[0.into()]);
803///
804/// // Ensure that the last item was dropped.
805/// assert!(weak.upgrade().is_none());
806/// ```
807#[ferrocene::prevalidated]
808#[inline(always)]
809#[stable(feature = "drop_in_place", since = "1.8.0")]
810#[rustc_diagnostic_item = "ptr_drop_in_place"]
811#[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
812pub const unsafe fn drop_in_place<T: PointeeSized>(to_drop: *mut T)
813where
814    T: [const] Destruct,
815{
816    // Due to historic reasons, `drop_in_place` takes a pointer rather than a reference,
817    // which results in worse codegen since we don't apply noalias/dereferenceable llvm
818    // attributes to pointer arguments. To workaround this without breaking public
819    // interface, `drop_in_place` calls the lang item, rather than being one directly.
820
821    // SAFETY:
822    // - compiler glue has the same safety requirements as this function
823    // - the pointer must be valid as per the safety requirement of this function
824    unsafe { drop_glue(&mut *to_drop) }
825}
826
827/// Helper function for `drop_in_place`. The compiler replaces this by the actual drop glue.
828#[ferrocene::prevalidated]
829#[lang = "drop_glue"]
830pub(crate) const unsafe fn drop_glue<T: PointeeSized>(_: &mut T)
831where
832    T: [const] Destruct,
833{
834    // Code here does not matter - this is replaced by the
835    // real drop glue by the compiler.
836}
837
838/// Creates a null raw pointer.
839///
840/// This function is equivalent to zero-initializing the pointer:
841/// `MaybeUninit::<*const T>::zeroed().assume_init()`.
842/// The resulting pointer has the address 0.
843///
844/// # Examples
845///
846/// ```
847/// use std::ptr;
848///
849/// let p: *const i32 = ptr::null();
850/// assert!(p.is_null());
851/// assert_eq!(p as usize, 0); // this pointer has the address 0
852/// ```
853#[inline(always)]
854#[must_use]
855#[stable(feature = "rust1", since = "1.0.0")]
856#[rustc_promotable]
857#[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
858#[rustc_diagnostic_item = "ptr_null"]
859#[ferrocene::prevalidated]
860pub const fn null<T: PointeeSized + Thin>() -> *const T {
861    from_raw_parts(without_provenance::<()>(0), ())
862}
863
864/// Creates a null mutable raw pointer.
865///
866/// This function is equivalent to zero-initializing the pointer:
867/// `MaybeUninit::<*mut T>::zeroed().assume_init()`.
868/// The resulting pointer has the address 0.
869///
870/// # Examples
871///
872/// ```
873/// use std::ptr;
874///
875/// let p: *mut i32 = ptr::null_mut();
876/// assert!(p.is_null());
877/// assert_eq!(p as usize, 0); // this pointer has the address 0
878/// ```
879#[inline(always)]
880#[must_use]
881#[stable(feature = "rust1", since = "1.0.0")]
882#[rustc_promotable]
883#[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
884#[rustc_diagnostic_item = "ptr_null_mut"]
885#[ferrocene::prevalidated]
886pub const fn null_mut<T: PointeeSized + Thin>() -> *mut T {
887    from_raw_parts_mut(without_provenance_mut::<()>(0), ())
888}
889
890/// Creates a pointer with the given address and no [provenance][crate::ptr#provenance].
891///
892/// This is equivalent to `ptr::null().with_addr(addr)`.
893///
894/// Without provenance, this pointer is not associated with any actual allocation. Such a
895/// no-provenance pointer may be used for zero-sized memory accesses (if suitably aligned), but
896/// non-zero-sized memory accesses with a no-provenance pointer are UB. No-provenance pointers are
897/// little more than a `usize` address in disguise.
898///
899/// This is different from `addr as *const T`, which creates a pointer that picks up a previously
900/// exposed provenance. See [`with_exposed_provenance`] for more details on that operation.
901///
902/// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
903#[inline(always)]
904#[must_use]
905#[stable(feature = "strict_provenance", since = "1.84.0")]
906#[rustc_const_stable(feature = "strict_provenance", since = "1.84.0")]
907#[rustc_diagnostic_item = "ptr_without_provenance"]
908#[ferrocene::prevalidated]
909pub const fn without_provenance<T>(addr: usize) -> *const T {
910    without_provenance_mut(addr)
911}
912
913/// Creates a new pointer that is dangling, but non-null and well-aligned.
914///
915/// This is useful for initializing types which lazily allocate, like
916/// `Vec::new` does.
917///
918/// Note that the address of the returned pointer may potentially
919/// be that of a valid pointer, which means this must not be used
920/// as a "not yet initialized" sentinel value.
921/// Types that lazily allocate must track initialization by some other means.
922#[inline(always)]
923#[must_use]
924#[stable(feature = "strict_provenance", since = "1.84.0")]
925#[rustc_const_stable(feature = "strict_provenance", since = "1.84.0")]
926pub const fn dangling<T>() -> *const T {
927    dangling_mut()
928}
929
930/// Creates a pointer with the given address and no [provenance][crate::ptr#provenance].
931///
932/// This is equivalent to `ptr::null_mut().with_addr(addr)`.
933///
934/// Without provenance, this pointer is not associated with any actual allocation. Such a
935/// no-provenance pointer may be used for zero-sized memory accesses (if suitably aligned), but
936/// non-zero-sized memory accesses with a no-provenance pointer are UB. No-provenance pointers are
937/// little more than a `usize` address in disguise.
938///
939/// This is different from `addr as *mut T`, which creates a pointer that picks up a previously
940/// exposed provenance. See [`with_exposed_provenance_mut`] for more details on that operation.
941///
942/// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
943#[inline(always)]
944#[must_use]
945#[stable(feature = "strict_provenance", since = "1.84.0")]
946#[rustc_const_stable(feature = "strict_provenance", since = "1.84.0")]
947#[rustc_diagnostic_item = "ptr_without_provenance_mut"]
948#[allow(integer_to_ptr_transmutes)] // Expected semantics here.
949#[ferrocene::prevalidated]
950pub const fn without_provenance_mut<T>(addr: usize) -> *mut T {
951    // An int-to-pointer transmute currently has exactly the intended semantics: it creates a
952    // pointer without provenance. Note that this is *not* a stable guarantee about transmute
953    // semantics, it relies on sysroot crates having special status.
954    // SAFETY: every valid integer is also a valid pointer (as long as you don't dereference that
955    // pointer).
956    unsafe { mem::transmute(addr) }
957}
958
959/// Creates a new pointer that is dangling, but non-null and well-aligned.
960///
961/// This is useful for initializing types which lazily allocate, like
962/// `Vec::new` does.
963///
964/// Note that the address of the returned pointer may potentially
965/// be that of a valid pointer, which means this must not be used
966/// as a "not yet initialized" sentinel value.
967/// Types that lazily allocate must track initialization by some other means.
968#[inline(always)]
969#[must_use]
970#[stable(feature = "strict_provenance", since = "1.84.0")]
971#[rustc_const_stable(feature = "strict_provenance", since = "1.84.0")]
972pub const fn dangling_mut<T>() -> *mut T {
973    NonNull::dangling().as_ptr()
974}
975
976/// Converts an address back to a pointer, picking up some previously 'exposed'
977/// [provenance][crate::ptr#provenance].
978///
979/// This is fully equivalent to `addr as *const T`. The provenance of the returned pointer is that
980/// of *some* pointer that was previously exposed by passing it to
981/// [`expose_provenance`][pointer::expose_provenance], or a `ptr as usize` cast. In addition, memory
982/// which is outside the control of the Rust abstract machine (MMIO registers, for example) is
983/// always considered to be accessible with an exposed provenance, so long as this memory is disjoint
984/// from memory that will be used by the abstract machine such as the stack, heap, and statics.
985///
986/// The exact provenance that gets picked is not specified. The compiler will do its best to pick
987/// the "right" provenance for you (whatever that may be), but currently we cannot provide any
988/// guarantees about which provenance the resulting pointer will have -- and therefore there
989/// is no definite specification for which memory the resulting pointer may access.
990///
991/// If there is *no* previously 'exposed' provenance that justifies the way the returned pointer
992/// will be used, the program has undefined behavior. In particular, the aliasing rules still apply:
993/// pointers and references that have been invalidated due to aliasing accesses cannot be used
994/// anymore, even if they have been exposed!
995///
996/// Due to its inherent ambiguity, this operation may not be supported by tools that help you to
997/// stay conformant with the Rust memory model. It is recommended to use [Strict
998/// Provenance][self#strict-provenance] APIs such as [`with_addr`][pointer::with_addr] wherever
999/// possible.
1000///
1001/// On most platforms this will produce a value with the same bytes as the address. Platforms
1002/// which need to store additional information in a pointer may not support this operation,
1003/// since it is generally not possible to actually *compute* which provenance the returned
1004/// pointer has to pick up.
1005///
1006/// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
1007#[must_use]
1008#[inline(always)]
1009#[stable(feature = "exposed_provenance", since = "1.84.0")]
1010#[rustc_const_stable(feature = "const_exposed_provenance", since = "1.91.0")]
1011#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1012#[allow(fuzzy_provenance_casts)] // this *is* the explicit provenance API one should use instead
1013pub const fn with_exposed_provenance<T>(addr: usize) -> *const T {
1014    addr as *const T
1015}
1016
1017/// Converts an address back to a mutable pointer, picking up some previously 'exposed'
1018/// [provenance][crate::ptr#provenance].
1019///
1020/// This is fully equivalent to `addr as *mut T`. The provenance of the returned pointer is that
1021/// of *some* pointer that was previously exposed by passing it to
1022/// [`expose_provenance`][pointer::expose_provenance], or a `ptr as usize` cast. In addition, memory
1023/// which is outside the control of the Rust abstract machine (MMIO registers, for example) is
1024/// always considered to be accessible with an exposed provenance, so long as this memory is disjoint
1025/// from memory that will be used by the abstract machine such as the stack, heap, and statics.
1026///
1027/// The exact provenance that gets picked is not specified. The compiler will do its best to pick
1028/// the "right" provenance for you (whatever that may be), but currently we cannot provide any
1029/// guarantees about which provenance the resulting pointer will have -- and therefore there
1030/// is no definite specification for which memory the resulting pointer may access.
1031///
1032/// If there is *no* previously 'exposed' provenance that justifies the way the returned pointer
1033/// will be used, the program has undefined behavior. In particular, the aliasing rules still apply:
1034/// pointers and references that have been invalidated due to aliasing accesses cannot be used
1035/// anymore, even if they have been exposed!
1036///
1037/// Due to its inherent ambiguity, this operation may not be supported by tools that help you to
1038/// stay conformant with the Rust memory model. It is recommended to use [Strict
1039/// Provenance][self#strict-provenance] APIs such as [`with_addr`][pointer::with_addr] wherever
1040/// possible.
1041///
1042/// On most platforms this will produce a value with the same bytes as the address. Platforms
1043/// which need to store additional information in a pointer may not support this operation,
1044/// since it is generally not possible to actually *compute* which provenance the returned
1045/// pointer has to pick up.
1046///
1047/// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
1048#[must_use]
1049#[inline(always)]
1050#[stable(feature = "exposed_provenance", since = "1.84.0")]
1051#[rustc_const_stable(feature = "const_exposed_provenance", since = "1.91.0")]
1052#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1053#[allow(fuzzy_provenance_casts)] // this *is* the explicit provenance API one should use instead
1054pub const fn with_exposed_provenance_mut<T>(addr: usize) -> *mut T {
1055    addr as *mut T
1056}
1057
1058/// Converts a reference to a raw pointer.
1059///
1060/// For `r: &T`, `from_ref(r)` is equivalent to `r as *const T` (except for the caveat noted below),
1061/// but is a bit safer since it will never silently change type or mutability, in particular if the
1062/// code is refactored.
1063///
1064/// The caller must ensure that the pointee outlives the pointer this function returns, or else it
1065/// will end up dangling.
1066///
1067/// The caller must also ensure that the memory the pointer (non-transitively) points to is never
1068/// written to (except inside an `UnsafeCell`) using this pointer or any pointer derived from it. If
1069/// you need to mutate the pointee, use [`from_mut`]. Specifically, to turn a mutable reference `m:
1070/// &mut T` into `*const T`, prefer `from_mut(m).cast_const()` to obtain a pointer that can later be
1071/// used for mutation.
1072///
1073/// ## Interaction with lifetime extension
1074///
1075/// Note that this has subtle interactions with the rules for lifetime extension of temporaries in
1076/// tail expressions. This code is valid, albeit in a non-obvious way:
1077/// ```rust
1078/// # type T = i32;
1079/// # fn foo() -> T { 42 }
1080/// // The temporary holding the return value of `foo` has its lifetime extended,
1081/// // because the surrounding expression involves no function call.
1082/// let p = &foo() as *const T;
1083/// unsafe { p.read() };
1084/// ```
1085/// Naively replacing the cast with `from_ref` is not valid:
1086/// ```rust,no_run
1087/// # use std::ptr;
1088/// # type T = i32;
1089/// # fn foo() -> T { 42 }
1090/// // The temporary holding the return value of `foo` does *not* have its lifetime extended,
1091/// // because the surrounding expression involves a function call.
1092/// let p = ptr::from_ref(&foo());
1093/// unsafe { p.read() }; // UB! Reading from a dangling pointer ⚠️
1094/// ```
1095/// The recommended way to write this code is to avoid relying on lifetime extension
1096/// when raw pointers are involved:
1097/// ```rust
1098/// # use std::ptr;
1099/// # type T = i32;
1100/// # fn foo() -> T { 42 }
1101/// let x = foo();
1102/// let p = ptr::from_ref(&x);
1103/// unsafe { p.read() };
1104/// ```
1105#[inline(always)]
1106#[must_use]
1107#[stable(feature = "ptr_from_ref", since = "1.76.0")]
1108#[rustc_const_stable(feature = "ptr_from_ref", since = "1.76.0")]
1109#[rustc_never_returns_null_ptr]
1110#[rustc_diagnostic_item = "ptr_from_ref"]
1111#[ferrocene::prevalidated]
1112pub const fn from_ref<T: PointeeSized>(r: &T) -> *const T {
1113    r
1114}
1115
1116/// Converts a mutable reference to a raw pointer.
1117///
1118/// For `r: &mut T`, `from_mut(r)` is equivalent to `r as *mut T` (except for the caveat noted
1119/// below), but is a bit safer since it will never silently change type or mutability, in particular
1120/// if the code is refactored.
1121///
1122/// The caller must ensure that the pointee outlives the pointer this function returns, or else it
1123/// will end up dangling.
1124///
1125/// ## Interaction with lifetime extension
1126///
1127/// Note that this has subtle interactions with the rules for lifetime extension of temporaries in
1128/// tail expressions. This code is valid, albeit in a non-obvious way:
1129/// ```rust
1130/// # type T = i32;
1131/// # fn foo() -> T { 42 }
1132/// // The temporary holding the return value of `foo` has its lifetime extended,
1133/// // because the surrounding expression involves no function call.
1134/// let p = &mut foo() as *mut T;
1135/// unsafe { p.write(T::default()) };
1136/// ```
1137/// Naively replacing the cast with `from_mut` is not valid:
1138/// ```rust,no_run
1139/// # use std::ptr;
1140/// # type T = i32;
1141/// # fn foo() -> T { 42 }
1142/// // The temporary holding the return value of `foo` does *not* have its lifetime extended,
1143/// // because the surrounding expression involves a function call.
1144/// let p = ptr::from_mut(&mut foo());
1145/// unsafe { p.write(T::default()) }; // UB! Writing to a dangling pointer ⚠️
1146/// ```
1147/// The recommended way to write this code is to avoid relying on lifetime extension
1148/// when raw pointers are involved:
1149/// ```rust
1150/// # use std::ptr;
1151/// # type T = i32;
1152/// # fn foo() -> T { 42 }
1153/// let mut x = foo();
1154/// let p = ptr::from_mut(&mut x);
1155/// unsafe { p.write(T::default()) };
1156/// ```
1157#[inline(always)]
1158#[must_use]
1159#[stable(feature = "ptr_from_ref", since = "1.76.0")]
1160#[rustc_const_stable(feature = "ptr_from_ref", since = "1.76.0")]
1161#[rustc_never_returns_null_ptr]
1162pub const fn from_mut<T: PointeeSized>(r: &mut T) -> *mut T {
1163    r
1164}
1165
1166/// Forms a raw slice from a pointer and a length.
1167///
1168/// The `len` argument is the number of **elements**, not the number of bytes.
1169///
1170/// This function is safe, but actually using the return value is unsafe.
1171/// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
1172///
1173/// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
1174///
1175/// # Examples
1176///
1177/// ```rust
1178/// use std::ptr;
1179///
1180/// // create a slice pointer when starting out with a pointer to the first element
1181/// let x = [5, 6, 7];
1182/// let raw_pointer = x.as_ptr();
1183/// let slice = ptr::slice_from_raw_parts(raw_pointer, 3);
1184/// assert_eq!(unsafe { &*slice }[2], 7);
1185/// ```
1186///
1187/// You must ensure that the pointer is valid and not null before dereferencing
1188/// the raw slice. A slice reference must never have a null pointer, even if it's empty.
1189///
1190/// ```rust,should_panic
1191/// use std::ptr;
1192/// let danger: *const [u8] = ptr::slice_from_raw_parts(ptr::null(), 0);
1193/// unsafe {
1194///     danger.as_ref().expect("references must not be null");
1195/// }
1196/// ```
1197#[inline]
1198#[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
1199#[rustc_const_stable(feature = "const_slice_from_raw_parts", since = "1.64.0")]
1200#[rustc_diagnostic_item = "ptr_slice_from_raw_parts"]
1201#[ferrocene::prevalidated]
1202pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
1203    from_raw_parts(data, len)
1204}
1205
1206/// Forms a raw mutable slice from a pointer and a length.
1207///
1208/// The `len` argument is the number of **elements**, not the number of bytes.
1209///
1210/// Performs the same functionality as [`slice_from_raw_parts`], except that a
1211/// raw mutable slice is returned, as opposed to a raw immutable slice.
1212///
1213/// This function is safe, but actually using the return value is unsafe.
1214/// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements.
1215///
1216/// [`slice::from_raw_parts_mut`]: crate::slice::from_raw_parts_mut
1217///
1218/// # Examples
1219///
1220/// ```rust
1221/// use std::ptr;
1222///
1223/// let x = &mut [5, 6, 7];
1224/// let raw_pointer = x.as_mut_ptr();
1225/// let slice = ptr::slice_from_raw_parts_mut(raw_pointer, 3);
1226///
1227/// unsafe {
1228///     (*slice)[2] = 99; // assign a value at an index in the slice
1229/// };
1230///
1231/// assert_eq!(unsafe { &*slice }[2], 99);
1232/// ```
1233///
1234/// You must ensure that the pointer is valid and not null before dereferencing
1235/// the raw slice. A slice reference must never have a null pointer, even if it's empty.
1236///
1237/// ```rust,should_panic
1238/// use std::ptr;
1239/// let danger: *mut [u8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 0);
1240/// unsafe {
1241///     danger.as_mut().expect("references must not be null");
1242/// }
1243/// ```
1244#[inline]
1245#[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
1246#[rustc_const_stable(feature = "const_slice_from_raw_parts_mut", since = "1.83.0")]
1247#[rustc_diagnostic_item = "ptr_slice_from_raw_parts_mut"]
1248#[ferrocene::prevalidated]
1249pub const fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
1250    from_raw_parts_mut(data, len)
1251}
1252
1253/// Swaps the values at two mutable locations of the same type, without
1254/// deinitializing either.
1255///
1256/// But for the following exceptions, this function is semantically
1257/// equivalent to [`mem::swap`]:
1258///
1259/// * It operates on raw pointers instead of references. When references are
1260///   available, [`mem::swap`] should be preferred.
1261///
1262/// * The two pointed-to values may overlap. If the values do overlap, then the
1263///   overlapping region of memory from `x` will be used. This is demonstrated
1264///   in the second example below.
1265///
1266/// * The operation is "untyped" in the sense that data may be uninitialized or otherwise violate
1267///   the requirements of `T`. The initialization state is preserved exactly.
1268///
1269/// # Safety
1270///
1271/// Behavior is undefined if any of the following conditions are violated:
1272///
1273/// * Both `x` and `y` must be [valid] for both reads and writes. They must remain valid even when the
1274///   other pointer is written. (This means if the memory ranges overlap, the two pointers must not
1275///   be subject to aliasing restrictions relative to each other.)
1276///
1277/// * Both `x` and `y` must be properly aligned.
1278///
1279/// Note that even if `T` has size `0`, the pointers must be properly aligned.
1280///
1281/// [valid]: self#safety
1282///
1283/// # Examples
1284///
1285/// Swapping two non-overlapping regions:
1286///
1287/// ```
1288/// use std::ptr;
1289///
1290/// let mut array = [0, 1, 2, 3];
1291///
1292/// let (x, y) = array.split_at_mut(2);
1293/// let x = x.as_mut_ptr().cast::<[u32; 2]>(); // this is `array[0..2]`
1294/// let y = y.as_mut_ptr().cast::<[u32; 2]>(); // this is `array[2..4]`
1295///
1296/// unsafe {
1297///     ptr::swap(x, y);
1298///     assert_eq!([2, 3, 0, 1], array);
1299/// }
1300/// ```
1301///
1302/// Swapping two overlapping regions:
1303///
1304/// ```
1305/// use std::ptr;
1306///
1307/// let mut array: [i32; 4] = [0, 1, 2, 3];
1308///
1309/// let array_ptr: *mut i32 = array.as_mut_ptr();
1310///
1311/// let x = array_ptr as *mut [i32; 3]; // this is `array[0..3]`
1312/// let y = unsafe { array_ptr.add(1) } as *mut [i32; 3]; // this is `array[1..4]`
1313///
1314/// unsafe {
1315///     ptr::swap(x, y);
1316///     // The indices `1..3` of the slice overlap between `x` and `y`.
1317///     // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
1318///     // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
1319///     // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
1320///     // This implementation is defined to make the latter choice.
1321///     assert_eq!([1, 0, 1, 2], array);
1322/// }
1323/// ```
1324#[inline]
1325#[stable(feature = "rust1", since = "1.0.0")]
1326#[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
1327#[rustc_diagnostic_item = "ptr_swap"]
1328#[ferrocene::prevalidated]
1329pub const unsafe fn swap<T>(x: *mut T, y: *mut T) {
1330    // Give ourselves some scratch space to work with.
1331    // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
1332    let mut tmp = MaybeUninit::<T>::uninit();
1333
1334    // Perform the swap
1335    // SAFETY: the caller must guarantee that `x` and `y` are
1336    // valid for writes and properly aligned. `tmp` cannot be
1337    // overlapping either `x` or `y` because `tmp` was just allocated
1338    // on the stack as a separate allocation.
1339    unsafe {
1340        copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
1341        copy(y, x, 1); // `x` and `y` may overlap
1342        copy_nonoverlapping(tmp.as_ptr(), y, 1);
1343    }
1344}
1345
1346/// Swaps `count * size_of::<T>()` bytes between the two regions of memory
1347/// beginning at `x` and `y`. The two regions must *not* overlap.
1348///
1349/// The operation is "untyped" in the sense that data may be uninitialized or otherwise violate the
1350/// requirements of `T`. The initialization state is preserved exactly.
1351///
1352/// # Safety
1353///
1354/// Behavior is undefined if any of the following conditions are violated:
1355///
1356/// * Both `x` and `y` must be [valid] for both reads and writes of `count *
1357///   size_of::<T>()` bytes.
1358///
1359/// * Both `x` and `y` must be properly aligned.
1360///
1361/// * The region of memory beginning at `x` with a size of `count *
1362///   size_of::<T>()` bytes must *not* overlap with the region of memory
1363///   beginning at `y` with the same size.
1364///
1365/// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
1366/// the pointers must be properly aligned.
1367///
1368/// [valid]: self#safety
1369///
1370/// # Examples
1371///
1372/// Basic usage:
1373///
1374/// ```
1375/// use std::ptr;
1376///
1377/// let mut x = [1, 2, 3, 4];
1378/// let mut y = [7, 8, 9];
1379///
1380/// unsafe {
1381///     ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
1382/// }
1383///
1384/// assert_eq!(x, [7, 8, 3, 4]);
1385/// assert_eq!(y, [1, 2, 9]);
1386/// ```
1387#[inline]
1388#[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
1389#[rustc_const_stable(feature = "const_swap_nonoverlapping", since = "1.88.0")]
1390#[rustc_diagnostic_item = "ptr_swap_nonoverlapping"]
1391#[rustc_allow_const_fn_unstable(const_eval_select)] // both implementations behave the same
1392#[track_caller]
1393#[ferrocene::prevalidated]
1394pub const unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
1395    ub_checks::assert_unsafe_precondition!(
1396        check_library_ub,
1397        "ptr::swap_nonoverlapping requires that both pointer arguments are aligned and non-null \
1398        and the specified memory ranges do not overlap",
1399        (
1400            x: *mut () = x as *mut (),
1401            y: *mut () = y as *mut (),
1402            size: usize = size_of::<T>(),
1403            align: usize = align_of::<T>(),
1404            count: usize = count,
1405        ) => {
1406            let zero_size = size == 0 || count == 0;
1407            ub_checks::maybe_is_aligned_and_not_null(x, align, zero_size)
1408                && ub_checks::maybe_is_aligned_and_not_null(y, align, zero_size)
1409                && ub_checks::maybe_is_nonoverlapping(x, y, size, count)
1410        }
1411    );
1412
1413    const_eval_select!(
1414        @capture[T] { x: *mut T, y: *mut T, count: usize }:
1415        if const {
1416            // At compile-time we don't need all the special code below.
1417            // SAFETY: Same preconditions as this function
1418            unsafe { swap_nonoverlapping_const(x, y, count) }
1419        } else {
1420            // Going though a slice here helps codegen know the size fits in `isize`
1421            let slice = slice_from_raw_parts_mut(x, count);
1422            // SAFETY: This is all readable from the pointer, meaning it's one
1423            // allocation, and thus cannot be more than isize::MAX bytes.
1424            let bytes = unsafe { mem::size_of_val_raw::<[T]>(slice) };
1425            if let Some(bytes) = NonZero::new(bytes) {
1426                // SAFETY: These are the same ranges, just expressed in a different
1427                // type, so they're still non-overlapping.
1428                unsafe { swap_nonoverlapping_bytes(x.cast(), y.cast(), bytes) };
1429            }
1430        }
1431    )
1432}
1433
1434/// Same behavior and safety conditions as [`swap_nonoverlapping`]
1435#[ferrocene::annotation(
1436    "This function is only called inside `swap_nonoverlapping` as the `const` arm of a `const_eval_select!` so it cannot be covered"
1437)]
1438#[inline]
1439#[ferrocene::prevalidated]
1440const unsafe fn swap_nonoverlapping_const<T>(x: *mut T, y: *mut T, count: usize) {
1441    let mut i = 0;
1442    while i < count {
1443        // SAFETY: By precondition, `i` is in-bounds because it's below `n`
1444        let x = unsafe { x.add(i) };
1445        // SAFETY: By precondition, `i` is in-bounds because it's below `n`
1446        // and it's distinct from `x` since the ranges are non-overlapping
1447        let y = unsafe { y.add(i) };
1448
1449        // SAFETY: we're only ever given pointers that are valid to read/write,
1450        // including being aligned, and nothing here panics so it's drop-safe.
1451        unsafe {
1452            // Note that it's critical that these use `copy_nonoverlapping`,
1453            // rather than `read`/`write`, to avoid #134713 if T has padding.
1454            let mut temp = MaybeUninit::<T>::uninit();
1455            copy_nonoverlapping(x, temp.as_mut_ptr(), 1);
1456            copy_nonoverlapping(y, x, 1);
1457            copy_nonoverlapping(temp.as_ptr(), y, 1);
1458        }
1459
1460        i += 1;
1461    }
1462}
1463
1464// Don't let MIR inline this, because we really want it to keep its noalias metadata
1465#[rustc_no_mir_inline]
1466#[inline]
1467#[ferrocene::prevalidated]
1468fn swap_chunk<const N: usize>(x: &mut MaybeUninit<[u8; N]>, y: &mut MaybeUninit<[u8; N]>) {
1469    let a = *x;
1470    let b = *y;
1471    *x = b;
1472    *y = a;
1473}
1474
1475#[inline]
1476#[ferrocene::prevalidated]
1477unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, bytes: NonZero<usize>) {
1478    // Same as `swap_nonoverlapping::<[u8; N]>`.
1479    #[ferrocene::prevalidated]
1480    unsafe fn swap_nonoverlapping_chunks<const N: usize>(
1481        x: *mut MaybeUninit<[u8; N]>,
1482        y: *mut MaybeUninit<[u8; N]>,
1483        chunks: NonZero<usize>,
1484    ) {
1485        let chunks = chunks.get();
1486        for i in 0..chunks {
1487            // SAFETY: i is in [0, chunks) so the adds and dereferences are in-bounds.
1488            unsafe { swap_chunk(&mut *x.add(i), &mut *y.add(i)) };
1489        }
1490    }
1491
1492    // Same as `swap_nonoverlapping_bytes`, but accepts at most 1+2+4=7 bytes
1493    #[inline]
1494    #[ferrocene::prevalidated]
1495    unsafe fn swap_nonoverlapping_short(x: *mut u8, y: *mut u8, bytes: NonZero<usize>) {
1496        // Tail handling for auto-vectorized code sometimes has element-at-a-time behaviour,
1497        // see <https://github.com/rust-lang/rust/issues/134946>.
1498        // By swapping as different sizes, rather than as a loop over bytes,
1499        // we make sure not to end up with, say, seven byte-at-a-time copies.
1500
1501        let bytes = bytes.get();
1502        let mut i = 0;
1503        macro_rules! swap_prefix {
1504            ($($n:literal)+) => {$(
1505                if (bytes & $n) != 0 {
1506                    // SAFETY: `i` can only have the same bits set as those in bytes,
1507                    // so these `add`s are in-bounds of `bytes`.  But the bit for
1508                    // `$n` hasn't been set yet, so the `$n` bytes that `swap_chunk`
1509                    // will read and write are within the usable range.
1510                    unsafe { swap_chunk::<$n>(&mut*x.add(i).cast(), &mut*y.add(i).cast()) };
1511                    i |= $n;
1512                }
1513            )+};
1514        }
1515        swap_prefix!(4 2 1);
1516        debug_assert_eq!(i, bytes);
1517    }
1518
1519    const CHUNK_SIZE: usize = size_of::<*const ()>();
1520    let bytes = bytes.get();
1521
1522    let chunks = bytes / CHUNK_SIZE;
1523    let tail = bytes % CHUNK_SIZE;
1524    if let Some(chunks) = NonZero::new(chunks) {
1525        // SAFETY: this is bytes/CHUNK_SIZE*CHUNK_SIZE bytes, which is <= bytes,
1526        // so it's within the range of our non-overlapping bytes.
1527        unsafe { swap_nonoverlapping_chunks::<CHUNK_SIZE>(x.cast(), y.cast(), chunks) };
1528    }
1529    if let Some(tail) = NonZero::new(tail) {
1530        const { assert!(CHUNK_SIZE <= 8) };
1531        let delta = chunks * CHUNK_SIZE;
1532        // SAFETY: the tail length is below CHUNK SIZE because of the remainder,
1533        // and CHUNK_SIZE is at most 8 by the const assert, so tail <= 7
1534        unsafe { swap_nonoverlapping_short(x.add(delta), y.add(delta), tail) };
1535    }
1536}
1537
1538/// Moves `src` into the pointed `dst`, returning the previous `dst` value.
1539///
1540/// Neither value is dropped.
1541///
1542/// This function is semantically equivalent to [`mem::replace`] except that it
1543/// operates on raw pointers instead of references. When references are
1544/// available, [`mem::replace`] should be preferred.
1545///
1546/// # Safety
1547///
1548/// Behavior is undefined if any of the following conditions are violated:
1549///
1550/// * `dst` must be [valid] for both reads and writes or `T` must be a ZST.
1551///
1552/// * `dst` must be properly aligned.
1553///
1554/// * `dst` must point to a properly initialized value of type `T`.
1555///
1556/// Note that even if `T` has size `0`, the pointer must be properly aligned.
1557///
1558/// [valid]: self#safety
1559///
1560/// # Examples
1561///
1562/// ```
1563/// use std::ptr;
1564///
1565/// let mut rust = vec!['b', 'u', 's', 't'];
1566///
1567/// // `mem::replace` would have the same effect without requiring the unsafe
1568/// // block.
1569/// let b = unsafe {
1570///     ptr::replace(&mut rust[0], 'r')
1571/// };
1572///
1573/// assert_eq!(b, 'b');
1574/// assert_eq!(rust, &['r', 'u', 's', 't']);
1575/// ```
1576#[inline]
1577#[stable(feature = "rust1", since = "1.0.0")]
1578#[rustc_const_stable(feature = "const_replace", since = "1.83.0")]
1579#[rustc_diagnostic_item = "ptr_replace"]
1580#[track_caller]
1581#[ferrocene::prevalidated]
1582pub const unsafe fn replace<T>(dst: *mut T, src: T) -> T {
1583    // SAFETY: the caller must guarantee that `dst` is valid to be
1584    // cast to a mutable reference (valid for writes, aligned, initialized),
1585    // and cannot overlap `src` since `dst` must point to a distinct
1586    // allocation. We are excluding null (with a ZST check) before creating a reference.
1587    unsafe {
1588        ub_checks::assert_unsafe_precondition!(
1589            check_language_ub,
1590            "ptr::replace requires that the pointer argument is aligned and non-null",
1591            (
1592                addr: *const () = dst as *const (),
1593                align: usize = align_of::<T>(),
1594                is_zst: bool = T::IS_ZST,
1595            ) => ub_checks::maybe_is_aligned_and_not_null(addr, align, is_zst)
1596        );
1597        if T::IS_ZST {
1598            // If `T` is a ZST, `dst` is allowed to be null. However, we also don't have to actually
1599            // do anything since there isn't actually any data to be copied anyway. All values of
1600            // type `T` are bit-identical, so we can just return `src` here.
1601            return src;
1602        }
1603        mem::replace(&mut *dst, src)
1604    }
1605}
1606
1607/// Reads the value from `src` without moving it. This leaves the
1608/// memory in `src` unchanged.
1609///
1610/// # Safety
1611///
1612/// Behavior is undefined if any of the following conditions are violated:
1613///
1614/// * `src` must be [valid] for reads or `T` must be a ZST.
1615///
1616/// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
1617///   case.
1618///
1619/// * `src` must point to a properly initialized value of type `T`.
1620///
1621/// Note that even if `T` has size `0`, the pointer must be properly aligned.
1622///
1623/// # Examples
1624///
1625/// Basic usage:
1626///
1627/// ```
1628/// let x = 12;
1629/// let y = &x as *const i32;
1630///
1631/// unsafe {
1632///     assert_eq!(std::ptr::read(y), 12);
1633/// }
1634/// ```
1635///
1636/// Manually implement [`mem::swap`]:
1637///
1638/// ```
1639/// use std::ptr;
1640///
1641/// fn swap<T>(a: &mut T, b: &mut T) {
1642///     unsafe {
1643///         // Create a bitwise copy of the value at `a` in `tmp`.
1644///         let tmp = ptr::read(a);
1645///
1646///         // Exiting at this point (either by explicitly returning or by
1647///         // calling a function which panics) would cause the value in `tmp` to
1648///         // be dropped while the same value is still referenced by `a`. This
1649///         // could trigger undefined behavior if `T` is not `Copy`.
1650///
1651///         // Create a bitwise copy of the value at `b` in `a`.
1652///         // This is safe because mutable references cannot alias.
1653///         ptr::copy_nonoverlapping(b, a, 1);
1654///
1655///         // As above, exiting here could trigger undefined behavior because
1656///         // the same value is referenced by `a` and `b`.
1657///
1658///         // Move `tmp` into `b`.
1659///         ptr::write(b, tmp);
1660///
1661///         // `tmp` has been moved (`write` takes ownership of its second argument),
1662///         // so nothing is dropped implicitly here.
1663///     }
1664/// }
1665///
1666/// let mut foo = "foo".to_owned();
1667/// let mut bar = "bar".to_owned();
1668///
1669/// swap(&mut foo, &mut bar);
1670///
1671/// assert_eq!(foo, "bar");
1672/// assert_eq!(bar, "foo");
1673/// ```
1674///
1675/// ## Ownership of the Returned Value
1676///
1677/// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
1678/// If `T` is not [`Copy`], using both the returned value and the value at
1679/// `*src` can violate memory safety. Note that assigning to `*src` counts as a
1680/// use because it will attempt to drop the value at `*src`.
1681///
1682/// [`write()`] can be used to overwrite data without causing it to be dropped.
1683///
1684/// ```
1685/// use std::ptr;
1686///
1687/// let mut s = String::from("foo");
1688/// unsafe {
1689///     // `s2` now points to the same underlying memory as `s`.
1690///     let mut s2: String = ptr::read(&s);
1691///
1692///     assert_eq!(s2, "foo");
1693///
1694///     // Assigning to `s2` causes its original value to be dropped. Beyond
1695///     // this point, `s` must no longer be used, as the underlying memory has
1696///     // been freed.
1697///     s2 = String::default();
1698///     assert_eq!(s2, "");
1699///
1700///     // Assigning to `s` would cause the old value to be dropped again,
1701///     // resulting in undefined behavior.
1702///     // s = String::from("bar"); // ERROR
1703///
1704///     // `ptr::write` can be used to overwrite a value without dropping it.
1705///     ptr::write(&mut s, String::from("bar"));
1706/// }
1707///
1708/// assert_eq!(s, "bar");
1709/// ```
1710///
1711/// [valid]: self#safety
1712#[inline]
1713#[stable(feature = "rust1", since = "1.0.0")]
1714#[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1715#[track_caller]
1716#[rustc_diagnostic_item = "ptr_read"]
1717#[ferrocene::prevalidated]
1718pub const unsafe fn read<T>(src: *const T) -> T {
1719    // It would be semantically correct to implement this via `copy_nonoverlapping`
1720    // and `MaybeUninit`, as was done before PR #109035. Calling `assume_init`
1721    // provides enough information to know that this is a typed operation.
1722
1723    // However, as of March 2023 the compiler was not capable of taking advantage
1724    // of that information. Thus, the implementation here switched to an intrinsic,
1725    // which lowers to `_0 = *src` in MIR, to address a few issues:
1726    //
1727    // - Using `MaybeUninit::assume_init` after a `copy_nonoverlapping` was not
1728    //   turning the untyped copy into a typed load. As such, the generated
1729    //   `load` in LLVM didn't get various metadata, such as `!range` (#73258),
1730    //   `!nonnull`, and `!noundef`, resulting in poorer optimization.
1731    // - Going through the extra local resulted in multiple extra copies, even
1732    //   in optimized MIR.  (Ignoring StorageLive/Dead, the intrinsic is one
1733    //   MIR statement, while the previous implementation was eight.)  LLVM
1734    //   could sometimes optimize them away, but because `read` is at the core
1735    //   of so many things, not having them in the first place improves what we
1736    //   hand off to the backend.  For example, `mem::replace::<Big>` previously
1737    //   emitted 4 `alloca` and 6 `memcpy`s, but is now 1 `alloc` and 3 `memcpy`s.
1738    // - In general, this approach keeps us from getting any more bugs (like
1739    //   #106369) that boil down to "`read(p)` is worse than `*p`", as this
1740    //   makes them look identical to the backend (or other MIR consumers).
1741    //
1742    // Future enhancements to MIR optimizations might well allow this to return
1743    // to the previous implementation, rather than using an intrinsic.
1744
1745    // SAFETY: the caller must guarantee that `src` is valid for reads.
1746    unsafe {
1747        #[cfg(debug_assertions)] // Too expensive to always enable (for now?)
1748        ub_checks::assert_unsafe_precondition!(
1749            check_language_ub,
1750            "ptr::read requires that the pointer argument is aligned and non-null",
1751            (
1752                addr: *const () = src as *const (),
1753                align: usize = align_of::<T>(),
1754                is_zst: bool = T::IS_ZST,
1755            ) => ub_checks::maybe_is_aligned_and_not_null(addr, align, is_zst)
1756        );
1757        crate::intrinsics::read_via_copy(src)
1758    }
1759}
1760
1761/// Reads the value from `src` without moving it. This leaves the
1762/// memory in `src` unchanged.
1763///
1764/// Unlike [`read`], `read_unaligned` works with unaligned pointers.
1765///
1766/// # Safety
1767///
1768/// Behavior is undefined if any of the following conditions are violated:
1769///
1770/// * `src` must be [valid] for reads.
1771///
1772/// * `src` must point to a properly initialized value of type `T`.
1773///
1774/// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
1775/// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
1776/// value and the value at `*src` can [violate memory safety][read-ownership].
1777///
1778/// [read-ownership]: read#ownership-of-the-returned-value
1779/// [valid]: self#safety
1780///
1781/// ## On `packed` structs
1782///
1783/// Attempting to create a raw pointer to an `unaligned` struct field with
1784/// an expression such as `&packed.unaligned as *const FieldType` creates an
1785/// intermediate unaligned reference before converting that to a raw pointer.
1786/// That this reference is temporary and immediately cast is inconsequential
1787/// as the compiler always expects references to be properly aligned.
1788/// As a result, using `&packed.unaligned as *const FieldType` causes immediate
1789/// *undefined behavior* in your program.
1790///
1791/// Instead you must use the `&raw const` syntax to create the pointer.
1792/// You may use that constructed pointer together with this function.
1793///
1794/// An example of what not to do and how this relates to `read_unaligned` is:
1795///
1796/// ```
1797/// #[repr(packed, C)]
1798/// struct Packed {
1799///     _padding: u8,
1800///     unaligned: u32,
1801/// }
1802///
1803/// let packed = Packed {
1804///     _padding: 0x00,
1805///     unaligned: 0x01020304,
1806/// };
1807///
1808/// // Take the address of a 32-bit integer which is not aligned.
1809/// // In contrast to `&packed.unaligned as *const _`, this has no undefined behavior.
1810/// let unaligned = &raw const packed.unaligned;
1811///
1812/// let v = unsafe { std::ptr::read_unaligned(unaligned) };
1813/// assert_eq!(v, 0x01020304);
1814/// ```
1815///
1816/// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
1817///
1818/// # Examples
1819///
1820/// Read a `usize` value from a byte buffer:
1821///
1822/// ```
1823/// fn read_usize(x: &[u8]) -> usize {
1824///     assert!(x.len() >= size_of::<usize>());
1825///
1826///     let ptr = x.as_ptr() as *const usize;
1827///
1828///     unsafe { ptr.read_unaligned() }
1829/// }
1830/// ```
1831#[inline]
1832#[stable(feature = "ptr_unaligned", since = "1.17.0")]
1833#[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1834#[track_caller]
1835#[rustc_diagnostic_item = "ptr_read_unaligned"]
1836#[ferrocene::prevalidated]
1837pub const unsafe fn read_unaligned<T>(src: *const T) -> T {
1838    let mut tmp = MaybeUninit::<T>::uninit();
1839    // SAFETY: the caller must guarantee that `src` is valid for reads.
1840    // `src` cannot overlap `tmp` because `tmp` was just allocated on
1841    // the stack as a separate allocation.
1842    //
1843    // Also, since we just wrote a valid value into `tmp`, it is guaranteed
1844    // to be properly initialized.
1845    unsafe {
1846        copy_nonoverlapping(src as *const u8, tmp.as_mut_ptr() as *mut u8, size_of::<T>());
1847        tmp.assume_init()
1848    }
1849}
1850
1851/// Overwrites a memory location with the given value without reading or
1852/// dropping the old value.
1853///
1854/// `write` does not drop the contents of `dst`. This is safe, but it could leak
1855/// allocations or resources, so care should be taken not to overwrite an object
1856/// that should be dropped.
1857///
1858/// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1859/// location pointed to by `dst`.
1860///
1861/// This is appropriate for initializing uninitialized memory, or overwriting
1862/// memory that has previously been [`read`] from.
1863///
1864/// # Safety
1865///
1866/// Behavior is undefined if any of the following conditions are violated:
1867///
1868/// * `dst` must be [valid] for writes or `T` must be a ZST.
1869///
1870/// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
1871///   case.
1872///
1873/// Note that even if `T` has size `0`, the pointer must be properly aligned.
1874///
1875/// [valid]: self#safety
1876///
1877/// # Examples
1878///
1879/// Basic usage:
1880///
1881/// ```
1882/// let mut x = 0;
1883/// let y = &mut x as *mut i32;
1884/// let z = 12;
1885///
1886/// unsafe {
1887///     std::ptr::write(y, z);
1888///     assert_eq!(std::ptr::read(y), 12);
1889/// }
1890/// ```
1891///
1892/// Manually implement [`mem::swap`]:
1893///
1894/// ```
1895/// use std::ptr;
1896///
1897/// fn swap<T>(a: &mut T, b: &mut T) {
1898///     unsafe {
1899///         // Create a bitwise copy of the value at `a` in `tmp`.
1900///         let tmp = ptr::read(a);
1901///
1902///         // Exiting at this point (either by explicitly returning or by
1903///         // calling a function which panics) would cause the value in `tmp` to
1904///         // be dropped while the same value is still referenced by `a`. This
1905///         // could trigger undefined behavior if `T` is not `Copy`.
1906///
1907///         // Create a bitwise copy of the value at `b` in `a`.
1908///         // This is safe because mutable references cannot alias.
1909///         ptr::copy_nonoverlapping(b, a, 1);
1910///
1911///         // As above, exiting here could trigger undefined behavior because
1912///         // the same value is referenced by `a` and `b`.
1913///
1914///         // Move `tmp` into `b`.
1915///         ptr::write(b, tmp);
1916///
1917///         // `tmp` has been moved (`write` takes ownership of its second argument),
1918///         // so nothing is dropped implicitly here.
1919///     }
1920/// }
1921///
1922/// let mut foo = "foo".to_owned();
1923/// let mut bar = "bar".to_owned();
1924///
1925/// swap(&mut foo, &mut bar);
1926///
1927/// assert_eq!(foo, "bar");
1928/// assert_eq!(bar, "foo");
1929/// ```
1930#[inline]
1931#[stable(feature = "rust1", since = "1.0.0")]
1932#[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1933#[rustc_diagnostic_item = "ptr_write"]
1934#[track_caller]
1935#[ferrocene::prevalidated]
1936pub const unsafe fn write<T>(dst: *mut T, src: T) {
1937    // Semantically, it would be fine for this to be implemented as a
1938    // `copy_nonoverlapping` and appropriate drop suppression of `src`.
1939
1940    // However, implementing via that currently produces more MIR than is ideal.
1941    // Using an intrinsic keeps it down to just the simple `*dst = move src` in
1942    // MIR (11 statements shorter, at the time of writing), and also allows
1943    // `src` to stay an SSA value in codegen_ssa, rather than a memory one.
1944
1945    // SAFETY: the caller must guarantee that `dst` is valid for writes.
1946    // `dst` cannot overlap `src` because the caller has mutable access
1947    // to `dst` while `src` is owned by this function.
1948    unsafe {
1949        #[cfg(debug_assertions)] // Too expensive to always enable (for now?)
1950        ub_checks::assert_unsafe_precondition!(
1951            check_language_ub,
1952            "ptr::write requires that the pointer argument is aligned and non-null",
1953            (
1954                addr: *mut () = dst as *mut (),
1955                align: usize = align_of::<T>(),
1956                is_zst: bool = T::IS_ZST,
1957            ) => ub_checks::maybe_is_aligned_and_not_null(addr, align, is_zst)
1958        );
1959        intrinsics::write_via_move(dst, src)
1960    }
1961}
1962
1963/// Overwrites a memory location with the given value without reading or
1964/// dropping the old value.
1965///
1966/// Unlike [`write()`], the pointer may be unaligned.
1967///
1968/// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
1969/// could leak allocations or resources, so care should be taken not to overwrite
1970/// an object that should be dropped.
1971///
1972/// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1973/// location pointed to by `dst`.
1974///
1975/// This is appropriate for initializing uninitialized memory, or overwriting
1976/// memory that has previously been read with [`read_unaligned`].
1977///
1978/// # Safety
1979///
1980/// Behavior is undefined if any of the following conditions are violated:
1981///
1982/// * `dst` must be [valid] for writes.
1983///
1984/// [valid]: self#safety
1985///
1986/// ## On `packed` structs
1987///
1988/// Attempting to create a raw pointer to an `unaligned` struct field with
1989/// an expression such as `&packed.unaligned as *const FieldType` creates an
1990/// intermediate unaligned reference before converting that to a raw pointer.
1991/// That this reference is temporary and immediately cast is inconsequential
1992/// as the compiler always expects references to be properly aligned.
1993/// As a result, using `&packed.unaligned as *const FieldType` causes immediate
1994/// *undefined behavior* in your program.
1995///
1996/// Instead, you must use the `&raw mut` syntax to create the pointer.
1997/// You may use that constructed pointer together with this function.
1998///
1999/// An example of how to do it and how this relates to `write_unaligned` is:
2000///
2001/// ```
2002/// #[repr(packed, C)]
2003/// struct Packed {
2004///     _padding: u8,
2005///     unaligned: u32,
2006/// }
2007///
2008/// let mut packed: Packed = unsafe { std::mem::zeroed() };
2009///
2010/// // Take the address of a 32-bit integer which is not aligned.
2011/// // In contrast to `&packed.unaligned as *mut _`, this has no undefined behavior.
2012/// let unaligned = &raw mut packed.unaligned;
2013///
2014/// unsafe { std::ptr::write_unaligned(unaligned, 42) };
2015///
2016/// assert_eq!({packed.unaligned}, 42); // `{...}` forces copying the field instead of creating a reference.
2017/// ```
2018///
2019/// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however
2020/// (as can be seen in the `assert_eq!` above).
2021///
2022/// # Examples
2023///
2024/// Write a `usize` value to a byte buffer:
2025///
2026/// ```
2027/// fn write_usize(x: &mut [u8], val: usize) {
2028///     assert!(x.len() >= size_of::<usize>());
2029///
2030///     let ptr = x.as_mut_ptr() as *mut usize;
2031///
2032///     unsafe { ptr.write_unaligned(val) }
2033/// }
2034/// ```
2035#[inline]
2036#[stable(feature = "ptr_unaligned", since = "1.17.0")]
2037#[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
2038#[rustc_diagnostic_item = "ptr_write_unaligned"]
2039#[track_caller]
2040#[ferrocene::prevalidated]
2041pub const unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
2042    // SAFETY: the caller must guarantee that `dst` is valid for writes.
2043    // `dst` cannot overlap `src` because the caller has mutable access
2044    // to `dst` while `src` is owned by this function.
2045    unsafe {
2046        copy_nonoverlapping((&raw const src) as *const u8, dst as *mut u8, size_of::<T>());
2047        // We are calling the intrinsic directly to avoid function calls in the generated code.
2048        intrinsics::forget(src);
2049    }
2050}
2051
2052/// Performs a volatile read of the value from `src` without moving it.
2053///
2054/// Volatile operations are intended to act on I/O memory. As such, they are considered externally
2055/// observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or
2056/// reordered by the compiler across other externally observable events. With this in mind, there
2057/// are two cases of usage that need to be distinguished:
2058///
2059/// - When a volatile operation is used for memory inside an [allocation], it behaves exactly like
2060///   [`read`], except for the additional guarantee that it won't be elided or reordered (see
2061///   above). This implies that the operation will actually access memory and not e.g. be lowered to
2062///   reusing data from a previous read. Other than that, all the usual rules for memory accesses
2063///   apply (including provenance).  In particular, just like in C, whether an operation is volatile
2064///   has no bearing whatsoever on questions involving concurrent accesses from multiple threads.
2065///   Volatile accesses behave exactly like non-atomic accesses in that regard.
2066///
2067/// - Volatile operations, however, may also be used to access memory that is _outside_ of any Rust
2068///   allocation. In this use-case, the pointer does *not* have to be [valid] for reads. This is
2069///   typically used for CPU and peripheral registers that must be accessed via an I/O memory
2070///   mapping, most commonly at fixed addresses reserved by the hardware. These often have special
2071///   semantics associated to their manipulation, and cannot be used as general purpose memory.
2072///   Here, any address value is possible, including 0 and [`usize::MAX`], so long as the semantics
2073///   of such a read are well-defined by the target hardware. The provenance of the pointer is
2074///   irrelevant, and it can be created with [`without_provenance`]. The access must not trap. It
2075///   can cause side-effects, but those must not affect Rust-allocated memory in any way. This
2076///   access is still not considered [atomic], and as such it cannot be used for inter-thread
2077///   synchronization.
2078///
2079/// Note that volatile memory operations where T is a zero-sized type are noops and may be ignored.
2080///
2081/// [allocation]: crate::ptr#allocated-object
2082/// [atomic]: crate::sync::atomic#memory-model-for-atomic-accesses
2083///
2084/// # Safety
2085///
2086/// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of whether `T` is
2087/// [`Copy`]. If `T` is not [`Copy`], using both the returned value and the value at `*src` can
2088/// [violate memory safety][read-ownership]. However, storing non-[`Copy`] types in volatile memory
2089/// is almost certainly incorrect.
2090///
2091/// Behavior is undefined if any of the following conditions are violated:
2092///
2093/// * `src` must be either [valid] for reads, or `T` must be a ZST, or `src` must point to memory
2094///   outside of all Rust allocations and reading from that memory must:
2095///   - not trap, and
2096///   - not cause any memory inside a Rust allocation to be modified.
2097///
2098/// * `src` must be properly aligned.
2099///
2100/// * Reading from `src` must produce a properly initialized value of type `T`.
2101///
2102/// Note that even if `T` has size `0`, the pointer must be properly aligned.
2103///
2104/// [valid]: self#safety
2105/// [read-ownership]: read#ownership-of-the-returned-value
2106///
2107/// # Examples
2108///
2109/// Basic usage:
2110///
2111/// ```
2112/// let x = 12;
2113/// let y = &x as *const i32;
2114///
2115/// unsafe {
2116///     assert_eq!(std::ptr::read_volatile(y), 12);
2117/// }
2118/// ```
2119#[inline]
2120#[stable(feature = "volatile", since = "1.9.0")]
2121#[track_caller]
2122#[rustc_diagnostic_item = "ptr_read_volatile"]
2123#[ferrocene::prevalidated]
2124pub unsafe fn read_volatile<T>(src: *const T) -> T {
2125    // SAFETY: the caller must uphold the safety contract for `volatile_load`.
2126    unsafe {
2127        ub_checks::assert_unsafe_precondition!(
2128            check_language_ub,
2129            "ptr::read_volatile requires that the pointer argument is aligned",
2130            (
2131                addr: *const () = src as *const (),
2132                align: usize = align_of::<T>(),
2133            ) => ub_checks::maybe_is_aligned(addr, align)
2134        );
2135        intrinsics::volatile_load(src)
2136    }
2137}
2138
2139/// Performs a volatile write of a memory location with the given value without reading or dropping
2140/// the old value.
2141///
2142/// Volatile operations are intended to act on I/O memory. As such, they are considered externally
2143/// observable events (just like syscalls), and are guaranteed to not be elided or reordered by the
2144/// compiler across other externally observable events. With this in mind, there are two cases of
2145/// usage that need to be distinguished:
2146///
2147/// - When a volatile operation is used for memory inside an [allocation], it behaves exactly like
2148///   [`write`][write()], except for the additional guarantee that it won't be elided or reordered
2149///   (see above). This implies that the operation will actually access memory and not e.g. be
2150///   lowered to a register access. Other than that, all the usual rules for memory accesses apply
2151///   (including provenance). In particular, just like in C, whether an operation is volatile has no
2152///   bearing whatsoever on questions involving concurrent access from multiple threads. Volatile
2153///   accesses behave exactly like non-atomic accesses in that regard.
2154///
2155/// - Volatile operations, however, may also be used to access memory that is _outside_ of any Rust
2156///   allocation. In this use-case, the pointer does *not* have to be [valid] for writes. This is
2157///   typically used for CPU and peripheral registers that must be accessed via an I/O memory
2158///   mapping, most commonly at fixed addresses reserved by the hardware. These often have special
2159///   semantics associated to their manipulation, and cannot be used as general purpose memory.
2160///   Here, any address value is possible, including 0 and [`usize::MAX`], so long as the semantics
2161///   of such a write are well-defined by the target hardware. The provenance of the pointer is
2162///   irrelevant, and it can be created with [`without_provenance`]. The access must not trap. It
2163///   can cause side-effects, but those must not affect Rust-allocated memory in any way. This
2164///   access is still not considered [atomic], and as such it cannot be used for inter-thread
2165///   synchronization.
2166///
2167/// Note that volatile memory operations on zero-sized types (e.g., if a zero-sized type is passed
2168/// to `write_volatile`) are noops and may be ignored.
2169///
2170/// `write_volatile` does not drop the contents of `dst`. This is safe, but it could leak
2171/// allocations or resources, so care should be taken not to overwrite an object that should be
2172/// dropped when operating on Rust memory. Additionally, it does not drop `src`. Semantically, `src`
2173/// is moved into the location pointed to by `dst`.
2174///
2175/// [allocation]: crate::ptr#allocated-object
2176/// [atomic]: crate::sync::atomic#memory-model-for-atomic-accesses
2177///
2178/// # Safety
2179///
2180/// Behavior is undefined if any of the following conditions are violated:
2181///
2182/// * `dst` must be either [valid] for writes, or `T` must be a ZST, or `dst` must point to memory
2183///   outside of all Rust allocations and writing to that memory must:
2184///   - not trap, and
2185///   - not cause any memory inside a Rust allocation to be modified.
2186///
2187/// * `dst` must be properly aligned.
2188///
2189/// Note that even if `T` has size `0`, the pointer must be properly aligned.
2190///
2191/// [valid]: self#safety
2192///
2193/// # Examples
2194///
2195/// Basic usage:
2196///
2197/// ```
2198/// let mut x = 0;
2199/// let y = &mut x as *mut i32;
2200/// let z = 12;
2201///
2202/// unsafe {
2203///     std::ptr::write_volatile(y, z);
2204///     assert_eq!(std::ptr::read_volatile(y), 12);
2205/// }
2206/// ```
2207#[inline]
2208#[stable(feature = "volatile", since = "1.9.0")]
2209#[rustc_diagnostic_item = "ptr_write_volatile"]
2210#[track_caller]
2211#[ferrocene::prevalidated]
2212pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
2213    // SAFETY: the caller must uphold the safety contract for `volatile_store`.
2214    unsafe {
2215        ub_checks::assert_unsafe_precondition!(
2216            check_language_ub,
2217            "ptr::write_volatile requires that the pointer argument is aligned",
2218            (
2219                addr: *mut () = dst as *mut (),
2220                align: usize = align_of::<T>(),
2221            ) => ub_checks::maybe_is_aligned(addr, align)
2222        );
2223        intrinsics::volatile_store(dst, src);
2224    }
2225}
2226
2227/// Calculate an element-offset that increases a pointer's alignment.
2228///
2229/// Calculate an element-offset (not byte-offset) that when added to a given pointer `p`, increases `p`'s alignment to at least the given alignment `a`.
2230///
2231/// # Safety
2232/// `a` must be a power of two.
2233///
2234/// # Notes
2235/// This implementation has been carefully tailored to not panic. It is UB for this to panic.
2236/// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
2237/// constants.
2238///
2239/// If we ever decide to make it possible to call the intrinsic with `a` that is not a
2240/// power-of-two, it will probably be more prudent to just change to a naive implementation rather
2241/// than trying to adapt this to accommodate that change.
2242///
2243/// Any questions go to @nagisa.
2244#[allow(ptr_to_integer_transmute_in_consts)]
2245#[ferrocene::prevalidated]
2246pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
2247    // FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <=
2248    // 1, where the method versions of these operations are not inlined.
2249    use intrinsics::{
2250        assume, cttz_nonzero, exact_div, mul_with_overflow, unchecked_rem, unchecked_shl,
2251        unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub,
2252    };
2253
2254    /// Calculate multiplicative modular inverse of `x` modulo `m`.
2255    ///
2256    /// This implementation is tailored for `align_offset` and has following preconditions:
2257    ///
2258    /// * `m` is a power-of-two;
2259    /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
2260    ///
2261    /// Implementation of this function shall not panic. Ever.
2262    #[inline]
2263    #[ferrocene::prevalidated]
2264    const unsafe fn mod_inv(x: usize, m: usize) -> usize {
2265        /// Multiplicative modular inverse table modulo 2⁴ = 16.
2266        ///
2267        /// Note, that this table does not contain values where inverse does not exist (i.e., for
2268        /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
2269        const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
2270        /// Modulo for which the `INV_TABLE_MOD_16` is intended.
2271        const INV_TABLE_MOD: usize = 16;
2272
2273        // SAFETY: `m` is required to be a power-of-two, hence non-zero.
2274        let m_minus_one = unsafe { unchecked_sub(m, 1) };
2275        let mut inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
2276        let mut mod_gate = INV_TABLE_MOD;
2277        // We iterate "up" using the following formula:
2278        //
2279        // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
2280        //
2281        // This application needs to be applied at least until `2²ⁿ ≥ m`, at which point we can
2282        // finally reduce the computation to our desired `m` by taking `inverse mod m`.
2283        //
2284        // This computation is `O(log log m)`, which is to say, that on 64-bit machines this loop
2285        // will always finish in at most 4 iterations.
2286        loop {
2287            // y = y * (2 - xy) mod n
2288            //
2289            // Note, that we use wrapping operations here intentionally – the original formula
2290            // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
2291            // usize::MAX` instead, because we take the result `mod n` at the end
2292            // anyway.
2293            if mod_gate >= m {
2294                break;
2295            }
2296            inverse = wrapping_mul(inverse, wrapping_sub(2usize, wrapping_mul(x, inverse)));
2297            let (new_gate, overflow) = mul_with_overflow(mod_gate, mod_gate);
2298            if overflow {
2299                break;
2300            }
2301            mod_gate = new_gate;
2302        }
2303        inverse & m_minus_one
2304    }
2305
2306    let stride = size_of::<T>();
2307
2308    let addr: usize = p.addr();
2309
2310    // SAFETY: `a` is a power-of-two, therefore non-zero.
2311    let a_minus_one = unsafe { unchecked_sub(a, 1) };
2312
2313    if stride == 0 {
2314        // SPECIAL_CASE: handle 0-sized types. No matter how many times we step, the address will
2315        // stay the same, so no offset will be able to align the pointer unless it is already
2316        // aligned. This branch _will_ be optimized out as `stride` is known at compile-time.
2317        let p_mod_a = addr & a_minus_one;
2318        return if p_mod_a == 0 { 0 } else { usize::MAX };
2319    }
2320
2321    // SAFETY: `stride == 0` case has been handled by the special case above.
2322    let a_mod_stride = unsafe { unchecked_rem(a, stride) };
2323    if a_mod_stride == 0 {
2324        // SPECIAL_CASE: In cases where the `a` is divisible by `stride`, byte offset to align a
2325        // pointer can be computed more simply through `-p (mod a)`. In the off-chance the byte
2326        // offset is not a multiple of `stride`, the input pointer was misaligned and no pointer
2327        // offset will be able to produce a `p` aligned to the specified `a`.
2328        //
2329        // The naive `-p (mod a)` equation inhibits LLVM's ability to select instructions
2330        // like `lea`. We compute `(round_up_to_next_alignment(p, a) - p)` instead. This
2331        // redistributes operations around the load-bearing, but pessimizing `and` instruction
2332        // sufficiently for LLVM to be able to utilize the various optimizations it knows about.
2333        //
2334        // LLVM handles the branch here particularly nicely. If this branch needs to be evaluated
2335        // at runtime, it will produce a mask `if addr_mod_stride == 0 { 0 } else { usize::MAX }`
2336        // in a branch-free way and then bitwise-OR it with whatever result the `-p mod a`
2337        // computation produces.
2338
2339        let aligned_address = wrapping_add(addr, a_minus_one) & wrapping_sub(0, a);
2340        let byte_offset = wrapping_sub(aligned_address, addr);
2341        // FIXME: Remove the assume after <https://github.com/llvm/llvm-project/issues/62502>
2342        // SAFETY: Masking by `-a` can only affect the low bits, and thus cannot have reduced
2343        // the value by more than `a-1`, so even though the intermediate values might have
2344        // wrapped, the byte_offset is always in `[0, a)`.
2345        unsafe { assume(byte_offset < a) };
2346
2347        // SAFETY: `stride == 0` case has been handled by the special case above.
2348        let addr_mod_stride = unsafe { unchecked_rem(addr, stride) };
2349
2350        return if addr_mod_stride == 0 {
2351            // SAFETY: `stride` is non-zero. This is guaranteed to divide exactly as well, because
2352            // addr has been verified to be aligned to the original type’s alignment requirements.
2353            unsafe { exact_div(byte_offset, stride) }
2354        } else {
2355            usize::MAX
2356        };
2357    }
2358
2359    // GENERAL_CASE: From here on we’re handling the very general case where `addr` may be
2360    // misaligned, there isn’t an obvious relationship between `stride` and `a` that we can take an
2361    // advantage of, etc. This case produces machine code that isn’t particularly high quality,
2362    // compared to the special cases above. The code produced here is still within the realm of
2363    // miracles, given the situations this case has to deal with.
2364
2365    // SAFETY: a is power-of-two hence non-zero. stride == 0 case is handled above.
2366    // FIXME(const-hack) replace with min
2367    let gcdpow = unsafe {
2368        let x = cttz_nonzero(stride);
2369        let y = cttz_nonzero(a);
2370        if x < y { x } else { y }
2371    };
2372    // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a `usize`.
2373    let gcd = unsafe { unchecked_shl(1usize, gcdpow) };
2374    // SAFETY: gcd is always greater or equal to 1.
2375    if addr & unsafe { unchecked_sub(gcd, 1) } == 0 {
2376        // This branch solves for the following linear congruence equation:
2377        //
2378        // ` p + so = 0 mod a `
2379        //
2380        // `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
2381        // requested alignment.
2382        //
2383        // With `g = gcd(a, s)`, and the above condition asserting that `p` is also divisible by
2384        // `g`, we can denote `a' = a/g`, `s' = s/g`, `p' = p/g`, then this becomes equivalent to:
2385        //
2386        // ` p' + s'o = 0 mod a' `
2387        // ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
2388        //
2389        // The first term is "the relative alignment of `p` to `a`" (divided by the `g`), the
2390        // second term is "how does incrementing `p` by `s` bytes change the relative alignment of
2391        // `p`" (again divided by `g`). Division by `g` is necessary to make the inverse well
2392        // formed if `a` and `s` are not co-prime.
2393        //
2394        // Furthermore, the result produced by this solution is not "minimal", so it is necessary
2395        // to take the result `o mod lcm(s, a)`. This `lcm(s, a)` is the same as `a'`.
2396
2397        // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
2398        // `a`.
2399        let a2 = unsafe { unchecked_shr(a, gcdpow) };
2400        // SAFETY: `a2` is non-zero. Shifting `a` by `gcdpow` cannot shift out any of the set bits
2401        // in `a` (of which it has exactly one).
2402        let a2minus1 = unsafe { unchecked_sub(a2, 1) };
2403        // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
2404        // `a`.
2405        let s2 = unsafe { unchecked_shr(stride & a_minus_one, gcdpow) };
2406        // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
2407        // `a`. Furthermore, the subtraction cannot overflow, because `a2 = a >> gcdpow` will
2408        // always be strictly greater than `(p % a) >> gcdpow`.
2409        let minusp2 = unsafe { unchecked_sub(a2, unchecked_shr(addr & a_minus_one, gcdpow)) };
2410        // SAFETY: `a2` is a power-of-two, as proven above. `s2` is strictly less than `a2`
2411        // because `(s % a) >> gcdpow` is strictly less than `a >> gcdpow`.
2412        return wrapping_mul(minusp2, unsafe { mod_inv(s2, a2) }) & a2minus1;
2413    }
2414
2415    // Cannot be aligned at all.
2416    usize::MAX
2417}
2418
2419/// Compares raw pointers for equality.
2420///
2421/// This is the same as using the `==` operator, but less generic:
2422/// the arguments have to be `*const T` raw pointers,
2423/// not anything that implements `PartialEq`.
2424///
2425/// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
2426/// by their address rather than comparing the values they point to
2427/// (which is what the `PartialEq for &T` implementation does).
2428///
2429/// When comparing wide pointers, both the address and the metadata are tested for equality.
2430/// However, note that comparing trait object pointers (`*const dyn Trait`) is unreliable: pointers
2431/// to values of the same underlying type can compare inequal (because vtables are duplicated in
2432/// multiple codegen units), and pointers to values of *different* underlying type can compare equal
2433/// (since identical vtables can be deduplicated within a codegen unit).
2434///
2435/// # Examples
2436///
2437/// ```
2438/// use std::ptr;
2439///
2440/// let five = 5;
2441/// let other_five = 5;
2442/// let five_ref = &five;
2443/// let same_five_ref = &five;
2444/// let other_five_ref = &other_five;
2445///
2446/// assert!(five_ref == same_five_ref);
2447/// assert!(ptr::eq(five_ref, same_five_ref));
2448///
2449/// assert!(five_ref == other_five_ref);
2450/// assert!(!ptr::eq(five_ref, other_five_ref));
2451/// ```
2452///
2453/// Slices are also compared by their length (fat pointers):
2454///
2455/// ```
2456/// let a = [1, 2, 3];
2457/// assert!(std::ptr::eq(&a[..3], &a[..3]));
2458/// assert!(!std::ptr::eq(&a[..2], &a[..3]));
2459/// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
2460/// ```
2461#[stable(feature = "ptr_eq", since = "1.17.0")]
2462#[inline(always)]
2463#[must_use = "pointer comparison produces a value"]
2464#[rustc_diagnostic_item = "ptr_eq"]
2465#[allow(ambiguous_wide_pointer_comparisons)] // it's actually clear here
2466pub fn eq<T: PointeeSized>(a: *const T, b: *const T) -> bool {
2467    a == b
2468}
2469
2470/// Compares the *addresses* of the two pointers for equality,
2471/// ignoring any metadata in fat pointers.
2472///
2473/// If the arguments are thin pointers of the same type,
2474/// then this is the same as [`eq`].
2475///
2476/// # Examples
2477///
2478/// ```
2479/// use std::ptr;
2480///
2481/// let whole: &[i32; 3] = &[1, 2, 3];
2482/// let first: &i32 = &whole[0];
2483///
2484/// assert!(ptr::addr_eq(whole, first));
2485/// assert!(!ptr::eq::<dyn std::fmt::Debug>(whole, first));
2486/// ```
2487#[stable(feature = "ptr_addr_eq", since = "1.76.0")]
2488#[inline(always)]
2489#[must_use = "pointer comparison produces a value"]
2490pub fn addr_eq<T: PointeeSized, U: PointeeSized>(p: *const T, q: *const U) -> bool {
2491    (p as *const ()) == (q as *const ())
2492}
2493
2494/// Compares the *addresses* of the two function pointers for equality.
2495///
2496/// This is the same as `f == g`, but using this function makes clear that the potentially
2497/// surprising semantics of function pointer comparison are involved.
2498///
2499/// There are **very few guarantees** about how functions are compiled and they have no intrinsic
2500/// “identity”; in particular, this comparison:
2501///
2502/// * May return `true` unexpectedly, in cases where functions are equivalent.
2503///
2504///   For example, the following program is likely (but not guaranteed) to print `(true, true)`
2505///   when compiled with optimization:
2506///
2507///   ```
2508///   let f: fn(i32) -> i32 = |x| x;
2509///   let g: fn(i32) -> i32 = |x| x + 0;  // different closure, different body
2510///   let h: fn(u32) -> u32 = |x| x + 0;  // different signature too
2511///   dbg!(std::ptr::fn_addr_eq(f, g), std::ptr::fn_addr_eq(f, h)); // not guaranteed to be equal
2512///   ```
2513///
2514/// * May return `false` in any case.
2515///
2516///   This is particularly likely with generic functions but may happen with any function.
2517///   (From an implementation perspective, this is possible because functions may sometimes be
2518///   processed more than once by the compiler, resulting in duplicate machine code.)
2519///
2520/// Despite these false positives and false negatives, this comparison can still be useful.
2521/// Specifically, if
2522///
2523/// * `T` is the same type as `U`, `T` is a [subtype] of `U`, or `U` is a [subtype] of `T`, and
2524/// * `ptr::fn_addr_eq(f, g)` returns true,
2525///
2526/// then calling `f` and calling `g` will be equivalent.
2527///
2528///
2529/// # Examples
2530///
2531/// ```
2532/// use std::ptr;
2533///
2534/// fn a() { println!("a"); }
2535/// fn b() { println!("b"); }
2536/// assert!(!ptr::fn_addr_eq(a as fn(), b as fn()));
2537/// ```
2538///
2539/// [subtype]: https://doc.rust-lang.org/reference/subtyping.html
2540#[stable(feature = "ptr_fn_addr_eq", since = "1.85.0")]
2541#[inline(always)]
2542#[must_use = "function pointer comparison produces a value"]
2543pub fn fn_addr_eq<T: FnPtr, U: FnPtr>(f: T, g: U) -> bool {
2544    f.addr() == g.addr()
2545}
2546
2547/// Hash a raw pointer.
2548///
2549/// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
2550/// by its address rather than the value it points to
2551/// (which is what the `Hash for &T` implementation does).
2552///
2553/// # Examples
2554///
2555/// ```
2556/// use std::hash::{DefaultHasher, Hash, Hasher};
2557/// use std::ptr;
2558///
2559/// let five = 5;
2560/// let five_ref = &five;
2561///
2562/// let mut hasher = DefaultHasher::new();
2563/// ptr::hash(five_ref, &mut hasher);
2564/// let actual = hasher.finish();
2565///
2566/// let mut hasher = DefaultHasher::new();
2567/// (five_ref as *const i32).hash(&mut hasher);
2568/// let expected = hasher.finish();
2569///
2570/// assert_eq!(actual, expected);
2571/// ```
2572#[stable(feature = "ptr_hash", since = "1.35.0")]
2573pub fn hash<T: PointeeSized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
2574    use crate::hash::Hash;
2575    hashee.hash(into);
2576}
2577
2578#[stable(feature = "fnptr_impls", since = "1.4.0")]
2579#[diagnostic::on_const(
2580    message = "pointers cannot be reliably compared during const eval",
2581    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2582)]
2583impl<F: FnPtr> PartialEq for F {
2584    #[inline]
2585    fn eq(&self, other: &Self) -> bool {
2586        self.addr() == other.addr()
2587    }
2588}
2589#[stable(feature = "fnptr_impls", since = "1.4.0")]
2590#[diagnostic::on_const(
2591    message = "pointers cannot be reliably compared during const eval",
2592    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2593)]
2594impl<F: FnPtr> Eq for F {}
2595
2596#[stable(feature = "fnptr_impls", since = "1.4.0")]
2597#[diagnostic::on_const(
2598    message = "pointers cannot be reliably compared during const eval",
2599    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2600)]
2601impl<F: FnPtr> PartialOrd for F {
2602    #[inline]
2603    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2604        self.addr().partial_cmp(&other.addr())
2605    }
2606}
2607#[stable(feature = "fnptr_impls", since = "1.4.0")]
2608#[diagnostic::on_const(
2609    message = "pointers cannot be reliably compared during const eval",
2610    note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2611)]
2612impl<F: FnPtr> Ord for F {
2613    #[inline]
2614    fn cmp(&self, other: &Self) -> Ordering {
2615        self.addr().cmp(&other.addr())
2616    }
2617}
2618
2619#[stable(feature = "fnptr_impls", since = "1.4.0")]
2620impl<F: FnPtr> hash::Hash for F {
2621    fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
2622        state.write_usize(self.addr() as _)
2623    }
2624}
2625
2626#[stable(feature = "fnptr_impls", since = "1.4.0")]
2627impl<F: FnPtr> fmt::Pointer for F {
2628    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2629        fmt::pointer_fmt_inner(self.addr() as _, f)
2630    }
2631}
2632
2633#[stable(feature = "fnptr_impls", since = "1.4.0")]
2634impl<F: FnPtr> fmt::Debug for F {
2635    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2636        fmt::pointer_fmt_inner(self.addr() as _, f)
2637    }
2638}
2639
2640/// Creates a `const` raw pointer to a place, without creating an intermediate reference.
2641///
2642/// `addr_of!(expr)` is equivalent to `&raw const expr`. The macro is *soft-deprecated*;
2643/// use `&raw const` instead.
2644///
2645/// It is still an open question under which conditions writing through an `addr_of!`-created
2646/// pointer is permitted. If the place `expr` evaluates to is based on a raw pointer, then the
2647/// result of `addr_of!` inherits all permissions from that raw pointer. However, if the place is
2648/// based on a reference, local variable, or `static`, then until all details are decided, the same
2649/// rules as for shared references apply: it is UB to write through a pointer created with this
2650/// operation, except for bytes located inside an `UnsafeCell`. Use `&raw mut` (or [`addr_of_mut`])
2651/// to create a raw pointer that definitely permits mutation.
2652///
2653/// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
2654/// and points to initialized data. For cases where those requirements do not hold,
2655/// raw pointers should be used instead. However, `&expr as *const _` creates a reference
2656/// before casting it to a raw pointer, and that reference is subject to the same rules
2657/// as all other references. This macro can create a raw pointer *without* creating
2658/// a reference first.
2659///
2660/// See [`addr_of_mut`] for how to create a pointer to uninitialized data.
2661/// Doing that with `addr_of` would not make much sense since one could only
2662/// read the data, and that would be Undefined Behavior.
2663///
2664/// # Safety
2665///
2666/// The `expr` in `addr_of!(expr)` is evaluated as a place expression, but never loads from the
2667/// place or requires the place to be dereferenceable. This means that `addr_of!((*ptr).field)`
2668/// still requires the projection to `field` to be in-bounds, using the same rules as [`offset`].
2669/// However, `addr_of!(*ptr)` is defined behavior even if `ptr` is null, dangling, or misaligned.
2670///
2671/// Note that `Deref`/`Index` coercions (and their mutable counterparts) are applied inside
2672/// `addr_of!` like everywhere else, in which case a reference is created to call `Deref::deref` or
2673/// `Index::index`, respectively. The statements above only apply when no such coercions are
2674/// applied.
2675///
2676/// [`offset`]: pointer::offset
2677///
2678/// # Example
2679///
2680/// **Correct usage: Creating a pointer to unaligned data**
2681///
2682/// ```
2683/// use std::ptr;
2684///
2685/// #[repr(packed)]
2686/// struct Packed {
2687///     f1: u8,
2688///     f2: u16,
2689/// }
2690///
2691/// let packed = Packed { f1: 1, f2: 2 };
2692/// // `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
2693/// let raw_f2 = ptr::addr_of!(packed.f2);
2694/// assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
2695/// ```
2696///
2697/// **Incorrect usage: Out-of-bounds fields projection**
2698///
2699/// ```rust,no_run
2700/// use std::ptr;
2701///
2702/// #[repr(C)]
2703/// struct MyStruct {
2704///     field1: i32,
2705///     field2: i32,
2706/// }
2707///
2708/// let ptr: *const MyStruct = ptr::null();
2709/// let fieldptr = unsafe { ptr::addr_of!((*ptr).field2) }; // Undefined Behavior ⚠️
2710/// ```
2711///
2712/// The field projection `.field2` would offset the pointer by 4 bytes,
2713/// but the pointer is not in-bounds of an allocation for 4 bytes,
2714/// so this offset is Undefined Behavior.
2715/// See the [`offset`] docs for a full list of requirements for inbounds pointer arithmetic; the
2716/// same requirements apply to field projections, even inside `addr_of!`. (In particular, it makes
2717/// no difference whether the pointer is null or dangling.)
2718#[stable(feature = "raw_ref_macros", since = "1.51.0")]
2719#[rustc_macro_transparency = "semiopaque"]
2720pub macro addr_of($place:expr) {
2721    &raw const $place
2722}
2723
2724/// Creates a `mut` raw pointer to a place, without creating an intermediate reference.
2725///
2726/// `addr_of_mut!(expr)` is equivalent to `&raw mut expr`. The macro is *soft-deprecated*;
2727/// use `&raw mut` instead.
2728///
2729/// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
2730/// and points to initialized data. For cases where those requirements do not hold,
2731/// raw pointers should be used instead. However, `&mut expr as *mut _` creates a reference
2732/// before casting it to a raw pointer, and that reference is subject to the same rules
2733/// as all other references. This macro can create a raw pointer *without* creating
2734/// a reference first.
2735///
2736/// # Safety
2737///
2738/// The `expr` in `addr_of_mut!(expr)` is evaluated as a place expression, but never loads from the
2739/// place or requires the place to be dereferenceable. This means that `addr_of_mut!((*ptr).field)`
2740/// still requires the projection to `field` to be in-bounds, using the same rules as [`offset`].
2741/// However, `addr_of_mut!(*ptr)` is defined behavior even if `ptr` is null, dangling, or misaligned.
2742///
2743/// Note that `Deref`/`Index` coercions (and their mutable counterparts) are applied inside
2744/// `addr_of_mut!` like everywhere else, in which case a reference is created to call `Deref::deref`
2745/// or `Index::index`, respectively. The statements above only apply when no such coercions are
2746/// applied.
2747///
2748/// [`offset`]: pointer::offset
2749///
2750/// # Examples
2751///
2752/// **Correct usage: Creating a pointer to unaligned data**
2753///
2754/// ```
2755/// use std::ptr;
2756///
2757/// #[repr(packed)]
2758/// struct Packed {
2759///     f1: u8,
2760///     f2: u16,
2761/// }
2762///
2763/// let mut packed = Packed { f1: 1, f2: 2 };
2764/// // `&mut packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
2765/// let raw_f2 = ptr::addr_of_mut!(packed.f2);
2766/// unsafe { raw_f2.write_unaligned(42); }
2767/// assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
2768/// ```
2769///
2770/// **Correct usage: Creating a pointer to uninitialized data**
2771///
2772/// ```rust
2773/// use std::{ptr, mem::MaybeUninit};
2774///
2775/// struct Demo {
2776///     field: bool,
2777/// }
2778///
2779/// let mut uninit = MaybeUninit::<Demo>::uninit();
2780/// // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
2781/// // and thus be Undefined Behavior!
2782/// let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) };
2783/// unsafe { f1_ptr.write(true); }
2784/// let init = unsafe { uninit.assume_init() };
2785/// ```
2786///
2787/// **Incorrect usage: Out-of-bounds fields projection**
2788///
2789/// ```rust,no_run
2790/// use std::ptr;
2791///
2792/// #[repr(C)]
2793/// struct MyStruct {
2794///     field1: i32,
2795///     field2: i32,
2796/// }
2797///
2798/// let ptr: *mut MyStruct = ptr::null_mut();
2799/// let fieldptr = unsafe { ptr::addr_of_mut!((*ptr).field2) }; // Undefined Behavior ⚠️
2800/// ```
2801///
2802/// The field projection `.field2` would offset the pointer by 4 bytes,
2803/// but the pointer is not in-bounds of an allocation for 4 bytes,
2804/// so this offset is Undefined Behavior.
2805/// See the [`offset`] docs for a full list of requirements for inbounds pointer arithmetic; the
2806/// same requirements apply to field projections, even inside `addr_of_mut!`. (In particular, it
2807/// makes no difference whether the pointer is null or dangling.)
2808#[stable(feature = "raw_ref_macros", since = "1.51.0")]
2809#[rustc_macro_transparency = "semiopaque"]
2810pub macro addr_of_mut($place:expr) {
2811    &raw mut $place
2812}