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