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