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