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