]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/mod.rs
Auto merge of #106121 - RalfJung:miri, r=RalfJung
[rust.git] / library / core / src / 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
8 //! or write to them. For this to be safe, these pointers must be *valid*.
9 //! Whether a pointer is valid depends on the operation it is used for
10 //! (read or write), and the extent of the memory that is accessed (i.e.,
11 //! how many bytes are read/written). Most functions use `*mut T` and `*const T`
12 //! to access only a single value, in which case the documentation omits the size
13 //! and 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, not even for accesses of [size zero][zst].
19 //! * For a pointer to be valid, it is necessary, but not always sufficient, that the pointer
20 //!   be *dereferenceable*: the memory range of the given size starting at the pointer must all be
21 //!   within the bounds of a single allocated object. Note that in Rust,
22 //!   every (stack-allocated) variable is considered a separate allocated object.
23 //! * Even for operations of [size zero][zst], the pointer must not be pointing to deallocated
24 //!   memory, i.e., deallocation makes pointers invalid even for zero-sized operations. However,
25 //!   casting any non-zero integer *literal* to a pointer is valid for zero-sized accesses, even if
26 //!   some memory happens to exist at that address and gets deallocated. This corresponds to writing
27 //!   your own allocator: allocating zero-sized objects is not very hard. The canonical way to
28 //!   obtain a pointer that is valid for zero-sized accesses is [`NonNull::dangling`].
29 //FIXME: mention `ptr::invalid` above, once it is stable.
30 //! * All accesses performed by functions in this module are *non-atomic* in the sense
31 //!   of [atomic operations] used to synchronize between threads. This means it is
32 //!   undefined behavior to perform two concurrent accesses to the same location from different
33 //!   threads unless both accesses only read from memory. Notice that this explicitly
34 //!   includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
35 //!   be used for inter-thread synchronization.
36 //! * The result of casting a reference to a pointer is valid for as long as the
37 //!   underlying object is live and no reference (just raw pointers) is used to
38 //!   access the same memory. That is, reference and pointer accesses cannot be
39 //!   interleaved.
40 //!
41 //! These axioms, along with careful use of [`offset`] for pointer arithmetic,
42 //! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
43 //! will be provided eventually, as the [aliasing] rules are being determined. For more
44 //! information, see the [book] as well as the section in the reference devoted
45 //! to [undefined behavior][ub].
46 //!
47 //! ## Alignment
48 //!
49 //! Valid raw pointers as defined above are not necessarily properly aligned (where
50 //! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
51 //! aligned to `mem::align_of::<T>()`). However, most functions require their
52 //! arguments to be properly aligned, and will explicitly state
53 //! this requirement in their documentation. Notable exceptions to this are
54 //! [`read_unaligned`] and [`write_unaligned`].
55 //!
56 //! When a function requires proper alignment, it does so even if the access
57 //! has size 0, i.e., even if memory is not actually touched. Consider using
58 //! [`NonNull::dangling`] in such cases.
59 //!
60 //! ## Allocated object
61 //!
62 //! For several operations, such as [`offset`] or field projections (`expr.field`), the notion of an
63 //! "allocated object" becomes relevant. An allocated object is a contiguous region of memory.
64 //! Common examples of allocated objects include stack-allocated variables (each variable is a
65 //! separate allocated object), heap allocations (each allocation created by the global allocator is
66 //! a separate allocated object), and `static` variables.
67 //!
68 //! # Strict Provenance
69 //!
70 //! **The following text is non-normative, insufficiently formal, and is an extremely strict
71 //! interpretation of provenance. It's ok if your code doesn't strictly conform to it.**
72 //!
73 //! [Strict Provenance][] is an experimental set of APIs that help tools that try
74 //! to validate the memory-safety of your program's execution. Notably this includes [Miri][]
75 //! and [CHERI][], which can detect when you access out of bounds memory or otherwise violate
76 //! Rust's memory model.
77 //!
78 //! Provenance must exist in some form for any programming
79 //! language compiled for modern computer architectures, but specifying a model for provenance
80 //! in a way that is useful to both compilers and programmers is an ongoing challenge.
81 //! The [Strict Provenance][] experiment seeks to explore the question: *what if we just said you
82 //! couldn't do all the nasty operations that make provenance so messy?*
83 //!
84 //! What APIs would have to be removed? What APIs would have to be added? How much would code
85 //! have to change, and is it worse or better now? Would any patterns become truly inexpressible?
86 //! Could we carve out special exceptions for those patterns? Should we?
87 //!
88 //! A secondary goal of this project is to see if we can disambiguate the many functions of
89 //! pointer<->integer casts enough for the definition of `usize` to be loosened so that it
90 //! isn't *pointer*-sized but address-space/offset/allocation-sized (we'll probably continue
91 //! to conflate these notions). This would potentially make it possible to more efficiently
92 //! target platforms where pointers are larger than offsets, such as CHERI and maybe some
93 //! segmented architectures.
94 //!
95 //! ## Provenance
96 //!
97 //! **This section is *non-normative* and is part of the [Strict Provenance][] experiment.**
98 //!
99 //! Pointers are not *simply* an "integer" or "address". For instance, it's uncontroversial
100 //! to say that a Use After Free is clearly Undefined Behaviour, even if you "get lucky"
101 //! and the freed memory gets reallocated before your read/write (in fact this is the
102 //! worst-case scenario, UAFs would be much less concerning if this didn't happen!).
103 //! To rationalize this claim, pointers need to somehow be *more* than just their addresses:
104 //! they must have provenance.
105 //!
106 //! When an allocation is created, that allocation has a unique Original Pointer. For alloc
107 //! APIs this is literally the pointer the call returns, and for local variables and statics,
108 //! this is the name of the variable/static. This is mildly overloading the term "pointer"
109 //! for the sake of brevity/exposition.
110 //!
111 //! The Original Pointer for an allocation is guaranteed to have unique access to the entire
112 //! allocation and *only* that allocation. In this sense, an allocation can be thought of
113 //! as a "sandbox" that cannot be broken into or out of. *Provenance* is the permission
114 //! to access an allocation's sandbox and has both a *spatial* and *temporal* component:
115 //!
116 //! * Spatial: A range of bytes that the pointer is allowed to access.
117 //! * Temporal: The lifetime (of the allocation) that access to these bytes is tied to.
118 //!
119 //! Spatial provenance makes sure you don't go beyond your sandbox, while temporal provenance
120 //! makes sure that you can't "get lucky" after your permission to access some memory
121 //! has been revoked (either through deallocations or borrows expiring).
122 //!
123 //! Provenance is implicitly shared with all pointers transitively derived from
124 //! The Original Pointer through operations like [`offset`], borrowing, and pointer casts.
125 //! Some operations may *shrink* the derived provenance, limiting how much memory it can
126 //! access or how long it's valid for (i.e. borrowing a subfield and subslicing).
127 //!
128 //! Shrinking provenance cannot be undone: even if you "know" there is a larger allocation, you
129 //! can't derive a pointer with a larger provenance. Similarly, you cannot "recombine"
130 //! two contiguous provenances back into one (i.e. with a `fn merge(&[T], &[T]) -> &[T]`).
131 //!
132 //! A reference to a value always has provenance over exactly the memory that field occupies.
133 //! A reference to a slice always has provenance over exactly the range that slice describes.
134 //!
135 //! If an allocation is deallocated, all pointers with provenance to that allocation become
136 //! invalidated, and effectively lose their provenance.
137 //!
138 //! The strict provenance experiment is mostly only interested in exploring stricter *spatial*
139 //! provenance. In this sense it can be thought of as a subset of the more ambitious and
140 //! formal [Stacked Borrows][] research project, which is what tools like [Miri][] are based on.
141 //! In particular, Stacked Borrows is necessary to properly describe what borrows are allowed
142 //! to do and when they become invalidated. This necessarily involves much more complex
143 //! *temporal* reasoning than simply identifying allocations. Adjusting APIs and code
144 //! for the strict provenance experiment will also greatly help Stacked Borrows.
145 //!
146 //!
147 //! ## Pointer Vs Addresses
148 //!
149 //! **This section is *non-normative* and is part of the [Strict Provenance][] experiment.**
150 //!
151 //! One of the largest historical issues with trying to define provenance is that programmers
152 //! freely convert between pointers and integers. Once you allow for this, it generally becomes
153 //! impossible to accurately track and preserve provenance information, and you need to appeal
154 //! to very complex and unreliable heuristics. But of course, converting between pointers and
155 //! integers is very useful, so what can we do?
156 //!
157 //! Also did you know WASM is actually a "Harvard Architecture"? As in function pointers are
158 //! handled completely differently from data pointers? And we kind of just shipped Rust on WASM
159 //! without really addressing the fact that we let you freely convert between function pointers
160 //! and data pointers, because it mostly Just Works? Let's just put that on the "pointer casts
161 //! are dubious" pile.
162 //!
163 //! Strict Provenance attempts to square these circles by decoupling Rust's traditional conflation
164 //! of pointers and `usize` (and `isize`), and defining a pointer to semantically contain the
165 //! following information:
166 //!
167 //! * The **address-space** it is part of (e.g. "data" vs "code" in WASM).
168 //! * The **address** it points to, which can be represented by a `usize`.
169 //! * The **provenance** it has, defining the memory it has permission to access.
170 //!
171 //! Under Strict Provenance, a usize *cannot* accurately represent a pointer, and converting from
172 //! a pointer to a usize is generally an operation which *only* extracts the address. It is
173 //! therefore *impossible* to construct a valid pointer from a usize because there is no way
174 //! to restore the address-space and provenance. In other words, pointer-integer-pointer
175 //! roundtrips are not possible (in the sense that the resulting pointer is not dereferenceable).
176 //!
177 //! The key insight to making this model *at all* viable is the [`with_addr`][] method:
178 //!
179 //! ```text
180 //!     /// Creates a new pointer with the given address.
181 //!     ///
182 //!     /// This performs the same operation as an `addr as ptr` cast, but copies
183 //!     /// the *address-space* and *provenance* of `self` to the new pointer.
184 //!     /// This allows us to dynamically preserve and propagate this important
185 //!     /// information in a way that is otherwise impossible with a unary cast.
186 //!     ///
187 //!     /// This is equivalent to using `wrapping_offset` to offset `self` to the
188 //!     /// given address, and therefore has all the same capabilities and restrictions.
189 //!     pub fn with_addr(self, addr: usize) -> Self;
190 //! ```
191 //!
192 //! So you're still able to drop down to the address representation and do whatever
193 //! clever bit tricks you want *as long as* you're able to keep around a pointer
194 //! into the allocation you care about that can "reconstitute" the other parts of the pointer.
195 //! Usually this is very easy, because you only are taking a pointer, messing with the address,
196 //! and then immediately converting back to a pointer. To make this use case more ergonomic,
197 //! we provide the [`map_addr`][] method.
198 //!
199 //! To help make it clear that code is "following" Strict Provenance semantics, we also provide an
200 //! [`addr`][] method which promises that the returned address is not part of a
201 //! pointer-usize-pointer roundtrip. In the future we may provide a lint for pointer<->integer
202 //! casts to help you audit if your code conforms to strict provenance.
203 //!
204 //!
205 //! ## Using Strict Provenance
206 //!
207 //! Most code needs no changes to conform to strict provenance, as the only really concerning
208 //! operation that *wasn't* obviously already Undefined Behaviour is casts from usize to a
209 //! pointer. For code which *does* cast a usize to a pointer, the scope of the change depends
210 //! on exactly what you're doing.
211 //!
212 //! In general you just need to make sure that if you want to convert a usize address to a
213 //! pointer and then use that pointer to read/write memory, you need to keep around a pointer
214 //! that has sufficient provenance to perform that read/write itself. In this way all of your
215 //! casts from an address to a pointer are essentially just applying offsets/indexing.
216 //!
217 //! This is generally trivial to do for simple cases like tagged pointers *as long as you
218 //! represent the tagged pointer as an actual pointer and not a usize*. For instance:
219 //!
220 //! ```
221 //! #![feature(strict_provenance)]
222 //!
223 //! unsafe {
224 //!     // A flag we want to pack into our pointer
225 //!     static HAS_DATA: usize = 0x1;
226 //!     static FLAG_MASK: usize = !HAS_DATA;
227 //!
228 //!     // Our value, which must have enough alignment to have spare least-significant-bits.
229 //!     let my_precious_data: u32 = 17;
230 //!     assert!(core::mem::align_of::<u32>() > 1);
231 //!
232 //!     // Create a tagged pointer
233 //!     let ptr = &my_precious_data as *const u32;
234 //!     let tagged = ptr.map_addr(|addr| addr | HAS_DATA);
235 //!
236 //!     // Check the flag:
237 //!     if tagged.addr() & HAS_DATA != 0 {
238 //!         // Untag and read the pointer
239 //!         let data = *tagged.map_addr(|addr| addr & FLAG_MASK);
240 //!         assert_eq!(data, 17);
241 //!     } else {
242 //!         unreachable!()
243 //!     }
244 //! }
245 //! ```
246 //!
247 //! (Yes, if you've been using AtomicUsize for pointers in concurrent datastructures, you should
248 //! be using AtomicPtr instead. If that messes up the way you atomically manipulate pointers,
249 //! we would like to know why, and what needs to be done to fix it.)
250 //!
251 //! Something more complicated and just generally *evil* like an XOR-List requires more significant
252 //! changes like allocating all nodes in a pre-allocated Vec or Arena and using a pointer
253 //! to the whole allocation to reconstitute the XORed addresses.
254 //!
255 //! Situations where a valid pointer *must* be created from just an address, such as baremetal code
256 //! accessing a memory-mapped interface at a fixed address, are an open question on how to support.
257 //! These situations *will* still be allowed, but we might require some kind of "I know what I'm
258 //! doing" annotation to explain the situation to the compiler. It's also possible they need no
259 //! special attention at all, because they're generally accessing memory outside the scope of
260 //! "the abstract machine", or already using "I know what I'm doing" annotations like "volatile".
261 //!
262 //! Under [Strict Provenance] it is Undefined Behaviour to:
263 //!
264 //! * Access memory through a pointer that does not have provenance over that memory.
265 //!
266 //! * [`offset`] a pointer to or from an address it doesn't have provenance over.
267 //!   This means it's always UB to offset a pointer derived from something deallocated,
268 //!   even if the offset is 0. Note that a pointer "one past the end" of its provenance
269 //!   is not actually outside its provenance, it just has 0 bytes it can load/store.
270 //!
271 //! But it *is* still sound to:
272 //!
273 //! * Create an invalid pointer from just an address (see [`ptr::invalid`][]). This can
274 //!   be used for sentinel values like `null` *or* to represent a tagged pointer that will
275 //!   never be dereferenceable. In general, it is always sound for an integer to pretend
276 //!   to be a pointer "for fun" as long as you don't use operations on it which require
277 //!   it to be valid (offset, read, write, etc).
278 //!
279 //! * Forge an allocation of size zero at any sufficiently aligned non-null address.
280 //!   i.e. the usual "ZSTs are fake, do what you want" rules apply *but* this only applies
281 //!   for actual forgery (integers cast to pointers). If you borrow some struct's field
282 //!   that *happens* to be zero-sized, the resulting pointer will have provenance tied to
283 //!   that allocation and it will still get invalidated if the allocation gets deallocated.
284 //!   In the future we may introduce an API to make such a forged allocation explicit.
285 //!
286 //! * [`wrapping_offset`][] a pointer outside its provenance. This includes invalid pointers
287 //!   which have "no" provenance. Unfortunately there may be practical limits on this for a
288 //!   particular platform, and it's an open question as to how to specify this (if at all).
289 //!   Notably, [CHERI][] relies on a compression scheme that can't handle a
290 //!   pointer getting offset "too far" out of bounds. If this happens, the address
291 //!   returned by `addr` will be the value you expect, but the provenance will get invalidated
292 //!   and using it to read/write will fault. The details of this are architecture-specific
293 //!   and based on alignment, but the buffer on either side of the pointer's range is pretty
294 //!   generous (think kilobytes, not bytes).
295 //!
296 //! * Compare arbitrary pointers by address. Addresses *are* just integers and so there is
297 //!   always a coherent answer, even if the pointers are invalid or from different
298 //!   address-spaces/provenances. Of course, comparing addresses from different address-spaces
299 //!   is generally going to be *meaningless*, but so is comparing Kilograms to Meters, and Rust
300 //!   doesn't prevent that either. Similarly, if you get "lucky" and notice that a pointer
301 //!   one-past-the-end is the "same" address as the start of an unrelated allocation, anything
302 //!   you do with that fact is *probably* going to be gibberish. The scope of that gibberish
303 //!   is kept under control by the fact that the two pointers *still* aren't allowed to access
304 //!   the other's allocation (bytes), because they still have different provenance.
305 //!
306 //! * Perform pointer tagging tricks. This falls out of [`wrapping_offset`] but is worth
307 //!   mentioning in more detail because of the limitations of [CHERI][]. Low-bit tagging
308 //!   is very robust, and often doesn't even go out of bounds because types ensure
309 //!   size >= align (and over-aligning actually gives CHERI more flexibility). Anything
310 //!   more complex than this rapidly enters "extremely platform-specific" territory as
311 //!   certain things may or may not be allowed based on specific supported operations.
312 //!   For instance, ARM explicitly supports high-bit tagging, and so CHERI on ARM inherits
313 //!   that and should support it.
314 //!
315 //! ## Pointer-usize-pointer roundtrips and 'exposed' provenance
316 //!
317 //! **This section is *non-normative* and is part of the [Strict Provenance] experiment.**
318 //!
319 //! As discussed above, pointer-usize-pointer roundtrips are not possible under [Strict Provenance].
320 //! However, there exists legacy Rust code that is full of such roundtrips, and legacy platform APIs
321 //! regularly assume that `usize` can capture all the information that makes up a pointer. There
322 //! also might be code that cannot be ported to Strict Provenance (which is something we would [like
323 //! to hear about][Strict Provenance]).
324 //!
325 //! For situations like this, there is a fallback plan, a way to 'opt out' of Strict Provenance.
326 //! However, note that this makes your code a lot harder to specify, and the code will not work
327 //! (well) with tools like [Miri] and [CHERI].
328 //!
329 //! This fallback plan is provided by the [`expose_addr`] and [`from_exposed_addr`] methods (which
330 //! are equivalent to `as` casts between pointers and integers). [`expose_addr`] is a lot like
331 //! [`addr`], but additionally adds the provenance of the pointer to a global list of 'exposed'
332 //! provenances. (This list is purely conceptual, it exists for the purpose of specifying Rust but
333 //! is not materialized in actual executions, except in tools like [Miri].) [`from_exposed_addr`]
334 //! can be used to construct a pointer with one of these previously 'exposed' provenances.
335 //! [`from_exposed_addr`] takes only `addr: usize` as arguments, so unlike in [`with_addr`] there is
336 //! no indication of what the correct provenance for the returned pointer is -- and that is exactly
337 //! what makes pointer-usize-pointer roundtrips so tricky to rigorously specify! There is no
338 //! algorithm that decides which provenance will be used. You can think of this as "guessing" the
339 //! right provenance, and the guess will be "maximally in your favor", in the sense that if there is
340 //! any way to avoid undefined behavior, then that is the guess that will be taken. However, if
341 //! there is *no* previously 'exposed' provenance that justifies the way the returned pointer will
342 //! be used, the program has undefined behavior.
343 //!
344 //! Using [`expose_addr`] or [`from_exposed_addr`] (or the equivalent `as` casts) means that code is
345 //! *not* following Strict Provenance rules. The goal of the Strict Provenance experiment is to
346 //! determine whether it is possible to use Rust without [`expose_addr`] and [`from_exposed_addr`].
347 //! If this is successful, it would be a major win for avoiding specification complexity and to
348 //! facilitate adoption of tools like [CHERI] and [Miri] that can be a big help in increasing the
349 //! confidence in (unsafe) Rust code.
350 //!
351 //! [aliasing]: ../../nomicon/aliasing.html
352 //! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
353 //! [ub]: ../../reference/behavior-considered-undefined.html
354 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
355 //! [atomic operations]: crate::sync::atomic
356 //! [`offset`]: pointer::offset
357 //! [`wrapping_offset`]: pointer::wrapping_offset
358 //! [`with_addr`]: pointer::with_addr
359 //! [`map_addr`]: pointer::map_addr
360 //! [`addr`]: pointer::addr
361 //! [`ptr::invalid`]: core::ptr::invalid
362 //! [`expose_addr`]: pointer::expose_addr
363 //! [`from_exposed_addr`]: from_exposed_addr
364 //! [Miri]: https://github.com/rust-lang/miri
365 //! [CHERI]: https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/
366 //! [Strict Provenance]: https://github.com/rust-lang/rust/issues/95228
367 //! [Stacked Borrows]: https://plv.mpi-sws.org/rustbelt/stacked-borrows/
368
369 #![stable(feature = "rust1", since = "1.0.0")]
370
371 use crate::cmp::Ordering;
372 use crate::fmt;
373 use crate::hash;
374 use crate::intrinsics::{
375     self, assert_unsafe_precondition, is_aligned_and_not_null, is_nonoverlapping,
376 };
377
378 use crate::mem::{self, MaybeUninit};
379
380 mod alignment;
381 #[unstable(feature = "ptr_alignment_type", issue = "102070")]
382 pub use alignment::Alignment;
383
384 #[stable(feature = "rust1", since = "1.0.0")]
385 #[doc(inline)]
386 pub use crate::intrinsics::copy_nonoverlapping;
387
388 #[stable(feature = "rust1", since = "1.0.0")]
389 #[doc(inline)]
390 pub use crate::intrinsics::copy;
391
392 #[stable(feature = "rust1", since = "1.0.0")]
393 #[doc(inline)]
394 pub use crate::intrinsics::write_bytes;
395
396 mod metadata;
397 #[unstable(feature = "ptr_metadata", issue = "81513")]
398 pub use metadata::{from_raw_parts, from_raw_parts_mut, metadata, DynMetadata, Pointee, Thin};
399
400 mod non_null;
401 #[stable(feature = "nonnull", since = "1.25.0")]
402 pub use non_null::NonNull;
403
404 mod unique;
405 #[unstable(feature = "ptr_internals", issue = "none")]
406 pub use unique::Unique;
407
408 mod const_ptr;
409 mod mut_ptr;
410
411 /// Executes the destructor (if any) of the pointed-to value.
412 ///
413 /// This is semantically equivalent to calling [`ptr::read`] and discarding
414 /// the result, but has the following advantages:
415 ///
416 /// * It is *required* to use `drop_in_place` to drop unsized types like
417 ///   trait objects, because they can't be read out onto the stack and
418 ///   dropped normally.
419 ///
420 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
421 ///   dropping manually allocated memory (e.g., in the implementations of
422 ///   `Box`/`Rc`/`Vec`), as the compiler doesn't need to prove that it's
423 ///   sound to elide the copy.
424 ///
425 /// * It can be used to drop [pinned] data when `T` is not `repr(packed)`
426 ///   (pinned data must not be moved before it is dropped).
427 ///
428 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
429 /// location first using [`ptr::read_unaligned`]. For packed structs, this move is
430 /// done automatically by the compiler. This means the fields of packed structs
431 /// are not dropped in-place.
432 ///
433 /// [`ptr::read`]: self::read
434 /// [`ptr::read_unaligned`]: self::read_unaligned
435 /// [pinned]: crate::pin
436 ///
437 /// # Safety
438 ///
439 /// Behavior is undefined if any of the following conditions are violated:
440 ///
441 /// * `to_drop` must be [valid] for both reads and writes.
442 ///
443 /// * `to_drop` must be properly aligned.
444 ///
445 /// * The value `to_drop` points to must be valid for dropping, which may mean it must uphold
446 ///   additional invariants - this is type-dependent.
447 ///
448 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
449 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
450 /// foo` counts as a use because it will cause the value to be dropped
451 /// again. [`write()`] can be used to overwrite data without causing it to be
452 /// dropped.
453 ///
454 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
455 ///
456 /// [valid]: self#safety
457 ///
458 /// # Examples
459 ///
460 /// Manually remove the last item from a vector:
461 ///
462 /// ```
463 /// use std::ptr;
464 /// use std::rc::Rc;
465 ///
466 /// let last = Rc::new(1);
467 /// let weak = Rc::downgrade(&last);
468 ///
469 /// let mut v = vec![Rc::new(0), last];
470 ///
471 /// unsafe {
472 ///     // Get a raw pointer to the last element in `v`.
473 ///     let ptr = &mut v[1] as *mut _;
474 ///     // Shorten `v` to prevent the last item from being dropped. We do that first,
475 ///     // to prevent issues if the `drop_in_place` below panics.
476 ///     v.set_len(1);
477 ///     // Without a call `drop_in_place`, the last item would never be dropped,
478 ///     // and the memory it manages would be leaked.
479 ///     ptr::drop_in_place(ptr);
480 /// }
481 ///
482 /// assert_eq!(v, &[0.into()]);
483 ///
484 /// // Ensure that the last item was dropped.
485 /// assert!(weak.upgrade().is_none());
486 /// ```
487 #[stable(feature = "drop_in_place", since = "1.8.0")]
488 #[lang = "drop_in_place"]
489 #[allow(unconditional_recursion)]
490 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
491     // Code here does not matter - this is replaced by the
492     // real drop glue by the compiler.
493
494     // SAFETY: see comment above
495     unsafe { drop_in_place(to_drop) }
496 }
497
498 /// Creates a null raw pointer.
499 ///
500 /// # Examples
501 ///
502 /// ```
503 /// use std::ptr;
504 ///
505 /// let p: *const i32 = ptr::null();
506 /// assert!(p.is_null());
507 /// ```
508 #[inline(always)]
509 #[must_use]
510 #[stable(feature = "rust1", since = "1.0.0")]
511 #[rustc_promotable]
512 #[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
513 #[rustc_allow_const_fn_unstable(ptr_metadata)]
514 #[rustc_diagnostic_item = "ptr_null"]
515 pub const fn null<T: ?Sized + Thin>() -> *const T {
516     from_raw_parts(invalid(0), ())
517 }
518
519 /// Creates a null mutable raw pointer.
520 ///
521 /// # Examples
522 ///
523 /// ```
524 /// use std::ptr;
525 ///
526 /// let p: *mut i32 = ptr::null_mut();
527 /// assert!(p.is_null());
528 /// ```
529 #[inline(always)]
530 #[must_use]
531 #[stable(feature = "rust1", since = "1.0.0")]
532 #[rustc_promotable]
533 #[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
534 #[rustc_allow_const_fn_unstable(ptr_metadata)]
535 #[rustc_diagnostic_item = "ptr_null_mut"]
536 pub const fn null_mut<T: ?Sized + Thin>() -> *mut T {
537     from_raw_parts_mut(invalid_mut(0), ())
538 }
539
540 /// Creates an invalid pointer with the given address.
541 ///
542 /// This is different from `addr as *const T`, which creates a pointer that picks up a previously
543 /// exposed provenance. See [`from_exposed_addr`] for more details on that operation.
544 ///
545 /// The module's top-level documentation discusses the precise meaning of an "invalid"
546 /// pointer but essentially this expresses that the pointer is not associated
547 /// with any actual allocation and is little more than a usize address in disguise.
548 ///
549 /// This pointer will have no provenance associated with it and is therefore
550 /// UB to read/write/offset. This mostly exists to facilitate things
551 /// like `ptr::null` and `NonNull::dangling` which make invalid pointers.
552 ///
553 /// (Standard "Zero-Sized-Types get to cheat and lie" caveats apply, although it
554 /// may be desirable to give them their own API just to make that 100% clear.)
555 ///
556 /// This API and its claimed semantics are part of the Strict Provenance experiment,
557 /// see the [module documentation][crate::ptr] for details.
558 #[inline(always)]
559 #[must_use]
560 #[rustc_const_stable(feature = "stable_things_using_strict_provenance", since = "1.61.0")]
561 #[unstable(feature = "strict_provenance", issue = "95228")]
562 pub const fn invalid<T>(addr: usize) -> *const T {
563     // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
564     // We use transmute rather than a cast so tools like Miri can tell that this
565     // is *not* the same as from_exposed_addr.
566     // SAFETY: every valid integer is also a valid pointer (as long as you don't dereference that
567     // pointer).
568     unsafe { mem::transmute(addr) }
569 }
570
571 /// Creates an invalid mutable pointer with the given address.
572 ///
573 /// This is different from `addr as *mut T`, which creates a pointer that picks up a previously
574 /// exposed provenance. See [`from_exposed_addr_mut`] for more details on that operation.
575 ///
576 /// The module's top-level documentation discusses the precise meaning of an "invalid"
577 /// pointer but essentially this expresses that the pointer is not associated
578 /// with any actual allocation and is little more than a usize address in disguise.
579 ///
580 /// This pointer will have no provenance associated with it and is therefore
581 /// UB to read/write/offset. This mostly exists to facilitate things
582 /// like `ptr::null` and `NonNull::dangling` which make invalid pointers.
583 ///
584 /// (Standard "Zero-Sized-Types get to cheat and lie" caveats apply, although it
585 /// may be desirable to give them their own API just to make that 100% clear.)
586 ///
587 /// This API and its claimed semantics are part of the Strict Provenance experiment,
588 /// see the [module documentation][crate::ptr] for details.
589 #[inline(always)]
590 #[must_use]
591 #[rustc_const_stable(feature = "stable_things_using_strict_provenance", since = "1.61.0")]
592 #[unstable(feature = "strict_provenance", issue = "95228")]
593 pub const fn invalid_mut<T>(addr: usize) -> *mut T {
594     // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
595     // We use transmute rather than a cast so tools like Miri can tell that this
596     // is *not* the same as from_exposed_addr.
597     // SAFETY: every valid integer is also a valid pointer (as long as you don't dereference that
598     // pointer).
599     unsafe { mem::transmute(addr) }
600 }
601
602 /// Convert an address back to a pointer, picking up a previously 'exposed' provenance.
603 ///
604 /// This is equivalent to `addr as *const T`. The provenance of the returned pointer is that of *any*
605 /// pointer that was previously exposed by passing it to [`expose_addr`][pointer::expose_addr],
606 /// or a `ptr as usize` cast. In addition, memory which is outside the control of the Rust abstract
607 /// machine (MMIO registers, for example) is always considered to be exposed, so long as this memory
608 /// is disjoint from memory that will be used by the abstract machine such as the stack, heap,
609 /// and statics.
610 ///
611 /// If there is no 'exposed' provenance that justifies the way this pointer will be used,
612 /// the program has undefined behavior. In particular, the aliasing rules still apply: pointers
613 /// and references that have been invalidated due to aliasing accesses cannot be used any more,
614 /// even if they have been exposed!
615 ///
616 /// Note that there is no algorithm that decides which provenance will be used. You can think of this
617 /// as "guessing" the right provenance, and the guess will be "maximally in your favor", in the sense
618 /// that if there is any way to avoid undefined behavior (while upholding all aliasing requirements),
619 /// then that is the guess that will be taken.
620 ///
621 /// On platforms with multiple address spaces, it is your responsibility to ensure that the
622 /// address makes sense in the address space that this pointer will be used with.
623 ///
624 /// Using this method means that code is *not* following strict provenance rules. "Guessing" a
625 /// suitable provenance complicates specification and reasoning and may not be supported by
626 /// tools that help you to stay conformant with the Rust memory model, so it is recommended to
627 /// use [`with_addr`][pointer::with_addr] wherever possible.
628 ///
629 /// On most platforms this will produce a value with the same bytes as the address. Platforms
630 /// which need to store additional information in a pointer may not support this operation,
631 /// since it is generally not possible to actually *compute* which provenance the returned
632 /// pointer has to pick up.
633 ///
634 /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
635 /// [module documentation][crate::ptr] for details.
636 #[must_use]
637 #[inline(always)]
638 #[unstable(feature = "strict_provenance", issue = "95228")]
639 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
640 #[allow(fuzzy_provenance_casts)] // this *is* the strict provenance API one should use instead
641 pub fn from_exposed_addr<T>(addr: usize) -> *const T
642 where
643     T: Sized,
644 {
645     // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
646     addr as *const T
647 }
648
649 /// Convert an address back to a mutable pointer, picking up a previously 'exposed' provenance.
650 ///
651 /// This is equivalent to `addr as *mut T`. The provenance of the returned pointer is that of *any*
652 /// pointer that was previously passed to [`expose_addr`][pointer::expose_addr] or a `ptr as usize`
653 /// cast. If there is no previously 'exposed' provenance that justifies the way this pointer will be
654 /// used, the program has undefined behavior. Note that there is no algorithm that decides which
655 /// provenance will be used. You can think of this as "guessing" the right provenance, and the guess
656 /// will be "maximally in your favor", in the sense that if there is any way to avoid undefined
657 /// behavior, then that is the guess that will be taken.
658 ///
659 /// On platforms with multiple address spaces, it is your responsibility to ensure that the
660 /// address makes sense in the address space that this pointer will be used with.
661 ///
662 /// Using this method means that code is *not* following strict provenance rules. "Guessing" a
663 /// suitable provenance complicates specification and reasoning and may not be supported by
664 /// tools that help you to stay conformant with the Rust memory model, so it is recommended to
665 /// use [`with_addr`][pointer::with_addr] wherever possible.
666 ///
667 /// On most platforms this will produce a value with the same bytes as the address. Platforms
668 /// which need to store additional information in a pointer may not support this operation,
669 /// since it is generally not possible to actually *compute* which provenance the returned
670 /// pointer has to pick up.
671 ///
672 /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
673 /// [module documentation][crate::ptr] for details.
674 #[must_use]
675 #[inline(always)]
676 #[unstable(feature = "strict_provenance", issue = "95228")]
677 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
678 #[allow(fuzzy_provenance_casts)] // this *is* the strict provenance API one should use instead
679 pub fn from_exposed_addr_mut<T>(addr: usize) -> *mut T
680 where
681     T: Sized,
682 {
683     // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
684     addr as *mut T
685 }
686
687 /// Convert a reference to a raw pointer.
688 ///
689 /// This is equivalent to `r as *const T`, but is a bit safer since it will never silently change
690 /// type or mutability, in particular if the code is refactored.
691 #[inline(always)]
692 #[must_use]
693 #[unstable(feature = "ptr_from_ref", issue = "106116")]
694 pub fn from_ref<T: ?Sized>(r: &T) -> *const T {
695     r
696 }
697
698 /// Convert a mutable reference to a raw pointer.
699 ///
700 /// This is equivalent to `r as *mut T`, but is a bit safer since it will never silently change
701 /// type or mutability, in particular if the code is refactored.
702 #[inline(always)]
703 #[must_use]
704 #[unstable(feature = "ptr_from_ref", issue = "106116")]
705 pub fn from_mut<T: ?Sized>(r: &mut T) -> *mut T {
706     r
707 }
708
709 /// Forms a raw slice from a pointer and a length.
710 ///
711 /// The `len` argument is the number of **elements**, not the number of bytes.
712 ///
713 /// This function is safe, but actually using the return value is unsafe.
714 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
715 ///
716 /// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
717 ///
718 /// # Examples
719 ///
720 /// ```rust
721 /// use std::ptr;
722 ///
723 /// // create a slice pointer when starting out with a pointer to the first element
724 /// let x = [5, 6, 7];
725 /// let raw_pointer = x.as_ptr();
726 /// let slice = ptr::slice_from_raw_parts(raw_pointer, 3);
727 /// assert_eq!(unsafe { &*slice }[2], 7);
728 /// ```
729 #[inline]
730 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
731 #[rustc_const_stable(feature = "const_slice_from_raw_parts", since = "1.64.0")]
732 #[rustc_allow_const_fn_unstable(ptr_metadata)]
733 pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
734     from_raw_parts(data.cast(), len)
735 }
736
737 /// Performs the same functionality as [`slice_from_raw_parts`], except that a
738 /// raw mutable slice is returned, as opposed to a raw immutable slice.
739 ///
740 /// See the documentation of [`slice_from_raw_parts`] for more details.
741 ///
742 /// This function is safe, but actually using the return value is unsafe.
743 /// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements.
744 ///
745 /// [`slice::from_raw_parts_mut`]: crate::slice::from_raw_parts_mut
746 ///
747 /// # Examples
748 ///
749 /// ```rust
750 /// use std::ptr;
751 ///
752 /// let x = &mut [5, 6, 7];
753 /// let raw_pointer = x.as_mut_ptr();
754 /// let slice = ptr::slice_from_raw_parts_mut(raw_pointer, 3);
755 ///
756 /// unsafe {
757 ///     (*slice)[2] = 99; // assign a value at an index in the slice
758 /// };
759 ///
760 /// assert_eq!(unsafe { &*slice }[2], 99);
761 /// ```
762 #[inline]
763 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
764 #[rustc_const_unstable(feature = "const_slice_from_raw_parts_mut", issue = "67456")]
765 pub const fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
766     from_raw_parts_mut(data.cast(), len)
767 }
768
769 /// Swaps the values at two mutable locations of the same type, without
770 /// deinitializing either.
771 ///
772 /// But for the following exceptions, this function is semantically
773 /// equivalent to [`mem::swap`]:
774 ///
775 /// * It operates on raw pointers instead of references. When references are
776 ///   available, [`mem::swap`] should be preferred.
777 ///
778 /// * The two pointed-to values may overlap. If the values do overlap, then the
779 ///   overlapping region of memory from `x` will be used. This is demonstrated
780 ///   in the second example below.
781 ///
782 /// * The operation is "untyped" in the sense that data may be uninitialized or otherwise violate
783 ///   the requirements of `T`. The initialization state is preserved exactly.
784 ///
785 /// # Safety
786 ///
787 /// Behavior is undefined if any of the following conditions are violated:
788 ///
789 /// * Both `x` and `y` must be [valid] for both reads and writes.
790 ///
791 /// * Both `x` and `y` must be properly aligned.
792 ///
793 /// Note that even if `T` has size `0`, the pointers must be non-null and properly aligned.
794 ///
795 /// [valid]: self#safety
796 ///
797 /// # Examples
798 ///
799 /// Swapping two non-overlapping regions:
800 ///
801 /// ```
802 /// use std::ptr;
803 ///
804 /// let mut array = [0, 1, 2, 3];
805 ///
806 /// let (x, y) = array.split_at_mut(2);
807 /// let x = x.as_mut_ptr().cast::<[u32; 2]>(); // this is `array[0..2]`
808 /// let y = y.as_mut_ptr().cast::<[u32; 2]>(); // this is `array[2..4]`
809 ///
810 /// unsafe {
811 ///     ptr::swap(x, y);
812 ///     assert_eq!([2, 3, 0, 1], array);
813 /// }
814 /// ```
815 ///
816 /// Swapping two overlapping regions:
817 ///
818 /// ```
819 /// use std::ptr;
820 ///
821 /// let mut array: [i32; 4] = [0, 1, 2, 3];
822 ///
823 /// let array_ptr: *mut i32 = array.as_mut_ptr();
824 ///
825 /// let x = array_ptr as *mut [i32; 3]; // this is `array[0..3]`
826 /// let y = unsafe { array_ptr.add(1) } as *mut [i32; 3]; // this is `array[1..4]`
827 ///
828 /// unsafe {
829 ///     ptr::swap(x, y);
830 ///     // The indices `1..3` of the slice overlap between `x` and `y`.
831 ///     // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
832 ///     // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
833 ///     // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
834 ///     // This implementation is defined to make the latter choice.
835 ///     assert_eq!([1, 0, 1, 2], array);
836 /// }
837 /// ```
838 #[inline]
839 #[stable(feature = "rust1", since = "1.0.0")]
840 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
841 pub const unsafe fn swap<T>(x: *mut T, y: *mut T) {
842     // Give ourselves some scratch space to work with.
843     // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
844     let mut tmp = MaybeUninit::<T>::uninit();
845
846     // Perform the swap
847     // SAFETY: the caller must guarantee that `x` and `y` are
848     // valid for writes and properly aligned. `tmp` cannot be
849     // overlapping either `x` or `y` because `tmp` was just allocated
850     // on the stack as a separate allocated object.
851     unsafe {
852         copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
853         copy(y, x, 1); // `x` and `y` may overlap
854         copy_nonoverlapping(tmp.as_ptr(), y, 1);
855     }
856 }
857
858 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
859 /// beginning at `x` and `y`. The two regions must *not* overlap.
860 ///
861 /// The operation is "untyped" in the sense that data may be uninitialized or otherwise violate the
862 /// requirements of `T`. The initialization state is preserved exactly.
863 ///
864 /// # Safety
865 ///
866 /// Behavior is undefined if any of the following conditions are violated:
867 ///
868 /// * Both `x` and `y` must be [valid] for both reads and writes of `count *
869 ///   size_of::<T>()` bytes.
870 ///
871 /// * Both `x` and `y` must be properly aligned.
872 ///
873 /// * The region of memory beginning at `x` with a size of `count *
874 ///   size_of::<T>()` bytes must *not* overlap with the region of memory
875 ///   beginning at `y` with the same size.
876 ///
877 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
878 /// the pointers must be non-null and properly aligned.
879 ///
880 /// [valid]: self#safety
881 ///
882 /// # Examples
883 ///
884 /// Basic usage:
885 ///
886 /// ```
887 /// use std::ptr;
888 ///
889 /// let mut x = [1, 2, 3, 4];
890 /// let mut y = [7, 8, 9];
891 ///
892 /// unsafe {
893 ///     ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
894 /// }
895 ///
896 /// assert_eq!(x, [7, 8, 3, 4]);
897 /// assert_eq!(y, [1, 2, 9]);
898 /// ```
899 #[inline]
900 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
901 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
902 pub const unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
903     #[allow(unused)]
904     macro_rules! attempt_swap_as_chunks {
905         ($ChunkTy:ty) => {
906             if mem::align_of::<T>() >= mem::align_of::<$ChunkTy>()
907                 && mem::size_of::<T>() % mem::size_of::<$ChunkTy>() == 0
908             {
909                 let x: *mut $ChunkTy = x.cast();
910                 let y: *mut $ChunkTy = y.cast();
911                 let count = count * (mem::size_of::<T>() / mem::size_of::<$ChunkTy>());
912                 // SAFETY: these are the same bytes that the caller promised were
913                 // ok, just typed as `MaybeUninit<ChunkTy>`s instead of as `T`s.
914                 // The `if` condition above ensures that we're not violating
915                 // alignment requirements, and that the division is exact so
916                 // that we don't lose any bytes off the end.
917                 return unsafe { swap_nonoverlapping_simple_untyped(x, y, count) };
918             }
919         };
920     }
921
922     // SAFETY: the caller must guarantee that `x` and `y` are
923     // valid for writes and properly aligned.
924     unsafe {
925         assert_unsafe_precondition!(
926             "ptr::swap_nonoverlapping requires that both pointer arguments are aligned and non-null \
927             and the specified memory ranges do not overlap",
928             [T](x: *mut T, y: *mut T, count: usize) =>
929             is_aligned_and_not_null(x)
930                 && is_aligned_and_not_null(y)
931                 && is_nonoverlapping(x, y, count)
932         );
933     }
934
935     // Split up the slice into small power-of-two-sized chunks that LLVM is able
936     // to vectorize (unless it's a special type with more-than-pointer alignment,
937     // because we don't want to pessimize things like slices of SIMD vectors.)
938     if mem::align_of::<T>() <= mem::size_of::<usize>()
939         && (!mem::size_of::<T>().is_power_of_two()
940             || mem::size_of::<T>() > mem::size_of::<usize>() * 2)
941     {
942         attempt_swap_as_chunks!(usize);
943         attempt_swap_as_chunks!(u8);
944     }
945
946     // SAFETY: Same preconditions as this function
947     unsafe { swap_nonoverlapping_simple_untyped(x, y, count) }
948 }
949
950 /// Same behaviour and safety conditions as [`swap_nonoverlapping`]
951 ///
952 /// LLVM can vectorize this (at least it can for the power-of-two-sized types
953 /// `swap_nonoverlapping` tries to use) so no need to manually SIMD it.
954 #[inline]
955 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
956 const unsafe fn swap_nonoverlapping_simple_untyped<T>(x: *mut T, y: *mut T, count: usize) {
957     let x = x.cast::<MaybeUninit<T>>();
958     let y = y.cast::<MaybeUninit<T>>();
959     let mut i = 0;
960     while i < count {
961         // SAFETY: By precondition, `i` is in-bounds because it's below `n`
962         let x = unsafe { &mut *x.add(i) };
963         // SAFETY: By precondition, `i` is in-bounds because it's below `n`
964         // and it's distinct from `x` since the ranges are non-overlapping
965         let y = unsafe { &mut *y.add(i) };
966         mem::swap_simple::<MaybeUninit<T>>(x, y);
967
968         i += 1;
969     }
970 }
971
972 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
973 ///
974 /// Neither value is dropped.
975 ///
976 /// This function is semantically equivalent to [`mem::replace`] except that it
977 /// operates on raw pointers instead of references. When references are
978 /// available, [`mem::replace`] should be preferred.
979 ///
980 /// # Safety
981 ///
982 /// Behavior is undefined if any of the following conditions are violated:
983 ///
984 /// * `dst` must be [valid] for both reads and writes.
985 ///
986 /// * `dst` must be properly aligned.
987 ///
988 /// * `dst` must point to a properly initialized value of type `T`.
989 ///
990 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
991 ///
992 /// [valid]: self#safety
993 ///
994 /// # Examples
995 ///
996 /// ```
997 /// use std::ptr;
998 ///
999 /// let mut rust = vec!['b', 'u', 's', 't'];
1000 ///
1001 /// // `mem::replace` would have the same effect without requiring the unsafe
1002 /// // block.
1003 /// let b = unsafe {
1004 ///     ptr::replace(&mut rust[0], 'r')
1005 /// };
1006 ///
1007 /// assert_eq!(b, 'b');
1008 /// assert_eq!(rust, &['r', 'u', 's', 't']);
1009 /// ```
1010 #[inline]
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 #[rustc_const_unstable(feature = "const_replace", issue = "83164")]
1013 pub const unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
1014     // SAFETY: the caller must guarantee that `dst` is valid to be
1015     // cast to a mutable reference (valid for writes, aligned, initialized),
1016     // and cannot overlap `src` since `dst` must point to a distinct
1017     // allocated object.
1018     unsafe {
1019         assert_unsafe_precondition!(
1020             "ptr::replace requires that the pointer argument is aligned and non-null",
1021             [T](dst: *mut T) => is_aligned_and_not_null(dst)
1022         );
1023         mem::swap(&mut *dst, &mut src); // cannot overlap
1024     }
1025     src
1026 }
1027
1028 /// Reads the value from `src` without moving it. This leaves the
1029 /// memory in `src` unchanged.
1030 ///
1031 /// # Safety
1032 ///
1033 /// Behavior is undefined if any of the following conditions are violated:
1034 ///
1035 /// * `src` must be [valid] for reads.
1036 ///
1037 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
1038 ///   case.
1039 ///
1040 /// * `src` must point to a properly initialized value of type `T`.
1041 ///
1042 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
1043 ///
1044 /// # Examples
1045 ///
1046 /// Basic usage:
1047 ///
1048 /// ```
1049 /// let x = 12;
1050 /// let y = &x as *const i32;
1051 ///
1052 /// unsafe {
1053 ///     assert_eq!(std::ptr::read(y), 12);
1054 /// }
1055 /// ```
1056 ///
1057 /// Manually implement [`mem::swap`]:
1058 ///
1059 /// ```
1060 /// use std::ptr;
1061 ///
1062 /// fn swap<T>(a: &mut T, b: &mut T) {
1063 ///     unsafe {
1064 ///         // Create a bitwise copy of the value at `a` in `tmp`.
1065 ///         let tmp = ptr::read(a);
1066 ///
1067 ///         // Exiting at this point (either by explicitly returning or by
1068 ///         // calling a function which panics) would cause the value in `tmp` to
1069 ///         // be dropped while the same value is still referenced by `a`. This
1070 ///         // could trigger undefined behavior if `T` is not `Copy`.
1071 ///
1072 ///         // Create a bitwise copy of the value at `b` in `a`.
1073 ///         // This is safe because mutable references cannot alias.
1074 ///         ptr::copy_nonoverlapping(b, a, 1);
1075 ///
1076 ///         // As above, exiting here could trigger undefined behavior because
1077 ///         // the same value is referenced by `a` and `b`.
1078 ///
1079 ///         // Move `tmp` into `b`.
1080 ///         ptr::write(b, tmp);
1081 ///
1082 ///         // `tmp` has been moved (`write` takes ownership of its second argument),
1083 ///         // so nothing is dropped implicitly here.
1084 ///     }
1085 /// }
1086 ///
1087 /// let mut foo = "foo".to_owned();
1088 /// let mut bar = "bar".to_owned();
1089 ///
1090 /// swap(&mut foo, &mut bar);
1091 ///
1092 /// assert_eq!(foo, "bar");
1093 /// assert_eq!(bar, "foo");
1094 /// ```
1095 ///
1096 /// ## Ownership of the Returned Value
1097 ///
1098 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
1099 /// If `T` is not [`Copy`], using both the returned value and the value at
1100 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
1101 /// use because it will attempt to drop the value at `*src`.
1102 ///
1103 /// [`write()`] can be used to overwrite data without causing it to be dropped.
1104 ///
1105 /// ```
1106 /// use std::ptr;
1107 ///
1108 /// let mut s = String::from("foo");
1109 /// unsafe {
1110 ///     // `s2` now points to the same underlying memory as `s`.
1111 ///     let mut s2: String = ptr::read(&s);
1112 ///
1113 ///     assert_eq!(s2, "foo");
1114 ///
1115 ///     // Assigning to `s2` causes its original value to be dropped. Beyond
1116 ///     // this point, `s` must no longer be used, as the underlying memory has
1117 ///     // been freed.
1118 ///     s2 = String::default();
1119 ///     assert_eq!(s2, "");
1120 ///
1121 ///     // Assigning to `s` would cause the old value to be dropped again,
1122 ///     // resulting in undefined behavior.
1123 ///     // s = String::from("bar"); // ERROR
1124 ///
1125 ///     // `ptr::write` can be used to overwrite a value without dropping it.
1126 ///     ptr::write(&mut s, String::from("bar"));
1127 /// }
1128 ///
1129 /// assert_eq!(s, "bar");
1130 /// ```
1131 ///
1132 /// [valid]: self#safety
1133 #[inline]
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1136 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1137 pub const unsafe fn read<T>(src: *const T) -> T {
1138     // We are calling the intrinsics directly to avoid function calls in the generated code
1139     // as `intrinsics::copy_nonoverlapping` is a wrapper function.
1140     extern "rust-intrinsic" {
1141         #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1142         fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
1143     }
1144
1145     let mut tmp = MaybeUninit::<T>::uninit();
1146     // SAFETY: the caller must guarantee that `src` is valid for reads.
1147     // `src` cannot overlap `tmp` because `tmp` was just allocated on
1148     // the stack as a separate allocated object.
1149     //
1150     // Also, since we just wrote a valid value into `tmp`, it is guaranteed
1151     // to be properly initialized.
1152     unsafe {
1153         assert_unsafe_precondition!(
1154             "ptr::read requires that the pointer argument is aligned and non-null",
1155             [T](src: *const T) => is_aligned_and_not_null(src)
1156         );
1157         copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
1158         tmp.assume_init()
1159     }
1160 }
1161
1162 /// Reads the value from `src` without moving it. This leaves the
1163 /// memory in `src` unchanged.
1164 ///
1165 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
1166 ///
1167 /// # Safety
1168 ///
1169 /// Behavior is undefined if any of the following conditions are violated:
1170 ///
1171 /// * `src` must be [valid] for reads.
1172 ///
1173 /// * `src` must point to a properly initialized value of type `T`.
1174 ///
1175 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
1176 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
1177 /// value and the value at `*src` can [violate memory safety][read-ownership].
1178 ///
1179 /// Note that even if `T` has size `0`, the pointer must be non-null.
1180 ///
1181 /// [read-ownership]: read#ownership-of-the-returned-value
1182 /// [valid]: self#safety
1183 ///
1184 /// ## On `packed` structs
1185 ///
1186 /// Attempting to create a raw pointer to an `unaligned` struct field with
1187 /// an expression such as `&packed.unaligned as *const FieldType` creates an
1188 /// intermediate unaligned reference before converting that to a raw pointer.
1189 /// That this reference is temporary and immediately cast is inconsequential
1190 /// as the compiler always expects references to be properly aligned.
1191 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
1192 /// *undefined behavior* in your program.
1193 ///
1194 /// Instead you must use the [`ptr::addr_of!`](addr_of) macro to
1195 /// create the pointer. You may use that returned pointer together with this
1196 /// function.
1197 ///
1198 /// An example of what not to do and how this relates to `read_unaligned` is:
1199 ///
1200 /// ```
1201 /// #[repr(packed, C)]
1202 /// struct Packed {
1203 ///     _padding: u8,
1204 ///     unaligned: u32,
1205 /// }
1206 ///
1207 /// let packed = Packed {
1208 ///     _padding: 0x00,
1209 ///     unaligned: 0x01020304,
1210 /// };
1211 ///
1212 /// // Take the address of a 32-bit integer which is not aligned.
1213 /// // In contrast to `&packed.unaligned as *const _`, this has no undefined behavior.
1214 /// let unaligned = std::ptr::addr_of!(packed.unaligned);
1215 ///
1216 /// let v = unsafe { std::ptr::read_unaligned(unaligned) };
1217 /// assert_eq!(v, 0x01020304);
1218 /// ```
1219 ///
1220 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
1221 ///
1222 /// # Examples
1223 ///
1224 /// Read a usize value from a byte buffer:
1225 ///
1226 /// ```
1227 /// use std::mem;
1228 ///
1229 /// fn read_usize(x: &[u8]) -> usize {
1230 ///     assert!(x.len() >= mem::size_of::<usize>());
1231 ///
1232 ///     let ptr = x.as_ptr() as *const usize;
1233 ///
1234 ///     unsafe { ptr.read_unaligned() }
1235 /// }
1236 /// ```
1237 #[inline]
1238 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
1239 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1240 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1241 pub const unsafe fn read_unaligned<T>(src: *const T) -> T {
1242     let mut tmp = MaybeUninit::<T>::uninit();
1243     // SAFETY: the caller must guarantee that `src` is valid for reads.
1244     // `src` cannot overlap `tmp` because `tmp` was just allocated on
1245     // the stack as a separate allocated object.
1246     //
1247     // Also, since we just wrote a valid value into `tmp`, it is guaranteed
1248     // to be properly initialized.
1249     unsafe {
1250         copy_nonoverlapping(src as *const u8, tmp.as_mut_ptr() as *mut u8, mem::size_of::<T>());
1251         tmp.assume_init()
1252     }
1253 }
1254
1255 /// Overwrites a memory location with the given value without reading or
1256 /// dropping the old value.
1257 ///
1258 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
1259 /// allocations or resources, so care should be taken not to overwrite an object
1260 /// that should be dropped.
1261 ///
1262 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1263 /// location pointed to by `dst`.
1264 ///
1265 /// This is appropriate for initializing uninitialized memory, or overwriting
1266 /// memory that has previously been [`read`] from.
1267 ///
1268 /// # Safety
1269 ///
1270 /// Behavior is undefined if any of the following conditions are violated:
1271 ///
1272 /// * `dst` must be [valid] for writes.
1273 ///
1274 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
1275 ///   case.
1276 ///
1277 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
1278 ///
1279 /// [valid]: self#safety
1280 ///
1281 /// # Examples
1282 ///
1283 /// Basic usage:
1284 ///
1285 /// ```
1286 /// let mut x = 0;
1287 /// let y = &mut x as *mut i32;
1288 /// let z = 12;
1289 ///
1290 /// unsafe {
1291 ///     std::ptr::write(y, z);
1292 ///     assert_eq!(std::ptr::read(y), 12);
1293 /// }
1294 /// ```
1295 ///
1296 /// Manually implement [`mem::swap`]:
1297 ///
1298 /// ```
1299 /// use std::ptr;
1300 ///
1301 /// fn swap<T>(a: &mut T, b: &mut T) {
1302 ///     unsafe {
1303 ///         // Create a bitwise copy of the value at `a` in `tmp`.
1304 ///         let tmp = ptr::read(a);
1305 ///
1306 ///         // Exiting at this point (either by explicitly returning or by
1307 ///         // calling a function which panics) would cause the value in `tmp` to
1308 ///         // be dropped while the same value is still referenced by `a`. This
1309 ///         // could trigger undefined behavior if `T` is not `Copy`.
1310 ///
1311 ///         // Create a bitwise copy of the value at `b` in `a`.
1312 ///         // This is safe because mutable references cannot alias.
1313 ///         ptr::copy_nonoverlapping(b, a, 1);
1314 ///
1315 ///         // As above, exiting here could trigger undefined behavior because
1316 ///         // the same value is referenced by `a` and `b`.
1317 ///
1318 ///         // Move `tmp` into `b`.
1319 ///         ptr::write(b, tmp);
1320 ///
1321 ///         // `tmp` has been moved (`write` takes ownership of its second argument),
1322 ///         // so nothing is dropped implicitly here.
1323 ///     }
1324 /// }
1325 ///
1326 /// let mut foo = "foo".to_owned();
1327 /// let mut bar = "bar".to_owned();
1328 ///
1329 /// swap(&mut foo, &mut bar);
1330 ///
1331 /// assert_eq!(foo, "bar");
1332 /// assert_eq!(bar, "foo");
1333 /// ```
1334 #[inline]
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1337 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1338 pub const unsafe fn write<T>(dst: *mut T, src: T) {
1339     // We are calling the intrinsics directly to avoid function calls in the generated code
1340     // as `intrinsics::copy_nonoverlapping` is a wrapper function.
1341     extern "rust-intrinsic" {
1342         #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")]
1343         fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
1344     }
1345
1346     // SAFETY: the caller must guarantee that `dst` is valid for writes.
1347     // `dst` cannot overlap `src` because the caller has mutable access
1348     // to `dst` while `src` is owned by this function.
1349     unsafe {
1350         assert_unsafe_precondition!(
1351             "ptr::write requires that the pointer argument is aligned and non-null",
1352             [T](dst: *mut T) => is_aligned_and_not_null(dst)
1353         );
1354         copy_nonoverlapping(&src as *const T, dst, 1);
1355         intrinsics::forget(src);
1356     }
1357 }
1358
1359 /// Overwrites a memory location with the given value without reading or
1360 /// dropping the old value.
1361 ///
1362 /// Unlike [`write()`], the pointer may be unaligned.
1363 ///
1364 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
1365 /// could leak allocations or resources, so care should be taken not to overwrite
1366 /// an object that should be dropped.
1367 ///
1368 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1369 /// location pointed to by `dst`.
1370 ///
1371 /// This is appropriate for initializing uninitialized memory, or overwriting
1372 /// memory that has previously been read with [`read_unaligned`].
1373 ///
1374 /// # Safety
1375 ///
1376 /// Behavior is undefined if any of the following conditions are violated:
1377 ///
1378 /// * `dst` must be [valid] for writes.
1379 ///
1380 /// Note that even if `T` has size `0`, the pointer must be non-null.
1381 ///
1382 /// [valid]: self#safety
1383 ///
1384 /// ## On `packed` structs
1385 ///
1386 /// Attempting to create a raw pointer to an `unaligned` struct field with
1387 /// an expression such as `&packed.unaligned as *const FieldType` creates an
1388 /// intermediate unaligned reference before converting that to a raw pointer.
1389 /// That this reference is temporary and immediately cast is inconsequential
1390 /// as the compiler always expects references to be properly aligned.
1391 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
1392 /// *undefined behavior* in your program.
1393 ///
1394 /// Instead you must use the [`ptr::addr_of_mut!`](addr_of_mut)
1395 /// macro to create the pointer. You may use that returned pointer together with
1396 /// this function.
1397 ///
1398 /// An example of how to do it and how this relates to `write_unaligned` is:
1399 ///
1400 /// ```
1401 /// #[repr(packed, C)]
1402 /// struct Packed {
1403 ///     _padding: u8,
1404 ///     unaligned: u32,
1405 /// }
1406 ///
1407 /// let mut packed: Packed = unsafe { std::mem::zeroed() };
1408 ///
1409 /// // Take the address of a 32-bit integer which is not aligned.
1410 /// // In contrast to `&packed.unaligned as *mut _`, this has no undefined behavior.
1411 /// let unaligned = std::ptr::addr_of_mut!(packed.unaligned);
1412 ///
1413 /// unsafe { std::ptr::write_unaligned(unaligned, 42) };
1414 ///
1415 /// assert_eq!({packed.unaligned}, 42); // `{...}` forces copying the field instead of creating a reference.
1416 /// ```
1417 ///
1418 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however
1419 /// (as can be seen in the `assert_eq!` above).
1420 ///
1421 /// # Examples
1422 ///
1423 /// Write a usize value to a byte buffer:
1424 ///
1425 /// ```
1426 /// use std::mem;
1427 ///
1428 /// fn write_usize(x: &mut [u8], val: usize) {
1429 ///     assert!(x.len() >= mem::size_of::<usize>());
1430 ///
1431 ///     let ptr = x.as_mut_ptr() as *mut usize;
1432 ///
1433 ///     unsafe { ptr.write_unaligned(val) }
1434 /// }
1435 /// ```
1436 #[inline]
1437 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
1438 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1439 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1440 pub const unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
1441     // SAFETY: the caller must guarantee that `dst` is valid for writes.
1442     // `dst` cannot overlap `src` because the caller has mutable access
1443     // to `dst` while `src` is owned by this function.
1444     unsafe {
1445         copy_nonoverlapping(&src as *const T as *const u8, dst as *mut u8, mem::size_of::<T>());
1446         // We are calling the intrinsic directly to avoid function calls in the generated code.
1447         intrinsics::forget(src);
1448     }
1449 }
1450
1451 /// Performs a volatile read of the value from `src` without moving it. This
1452 /// leaves the memory in `src` unchanged.
1453 ///
1454 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1455 /// to not be elided or reordered by the compiler across other volatile
1456 /// operations.
1457 ///
1458 /// # Notes
1459 ///
1460 /// Rust does not currently have a rigorously and formally defined memory model,
1461 /// so the precise semantics of what "volatile" means here is subject to change
1462 /// over time. That being said, the semantics will almost always end up pretty
1463 /// similar to [C11's definition of volatile][c11].
1464 ///
1465 /// The compiler shouldn't change the relative order or number of volatile
1466 /// memory operations. However, volatile memory operations on zero-sized types
1467 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
1468 /// and may be ignored.
1469 ///
1470 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1471 ///
1472 /// # Safety
1473 ///
1474 /// Behavior is undefined if any of the following conditions are violated:
1475 ///
1476 /// * `src` must be [valid] for reads.
1477 ///
1478 /// * `src` must be properly aligned.
1479 ///
1480 /// * `src` must point to a properly initialized value of type `T`.
1481 ///
1482 /// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
1483 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
1484 /// value and the value at `*src` can [violate memory safety][read-ownership].
1485 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
1486 /// incorrect.
1487 ///
1488 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
1489 ///
1490 /// [valid]: self#safety
1491 /// [read-ownership]: read#ownership-of-the-returned-value
1492 ///
1493 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1494 /// on questions involving concurrent access from multiple threads. Volatile
1495 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1496 /// a race between a `read_volatile` and any write operation to the same location
1497 /// is undefined behavior.
1498 ///
1499 /// # Examples
1500 ///
1501 /// Basic usage:
1502 ///
1503 /// ```
1504 /// let x = 12;
1505 /// let y = &x as *const i32;
1506 ///
1507 /// unsafe {
1508 ///     assert_eq!(std::ptr::read_volatile(y), 12);
1509 /// }
1510 /// ```
1511 #[inline]
1512 #[stable(feature = "volatile", since = "1.9.0")]
1513 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1514 pub unsafe fn read_volatile<T>(src: *const T) -> T {
1515     // SAFETY: the caller must uphold the safety contract for `volatile_load`.
1516     unsafe {
1517         assert_unsafe_precondition!(
1518             "ptr::read_volatile requires that the pointer argument is aligned and non-null",
1519             [T](src: *const T) => is_aligned_and_not_null(src)
1520         );
1521         intrinsics::volatile_load(src)
1522     }
1523 }
1524
1525 /// Performs a volatile write of a memory location with the given value without
1526 /// reading or dropping the old value.
1527 ///
1528 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1529 /// to not be elided or reordered by the compiler across other volatile
1530 /// operations.
1531 ///
1532 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
1533 /// could leak allocations or resources, so care should be taken not to overwrite
1534 /// an object that should be dropped.
1535 ///
1536 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1537 /// location pointed to by `dst`.
1538 ///
1539 /// # Notes
1540 ///
1541 /// Rust does not currently have a rigorously and formally defined memory model,
1542 /// so the precise semantics of what "volatile" means here is subject to change
1543 /// over time. That being said, the semantics will almost always end up pretty
1544 /// similar to [C11's definition of volatile][c11].
1545 ///
1546 /// The compiler shouldn't change the relative order or number of volatile
1547 /// memory operations. However, volatile memory operations on zero-sized types
1548 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
1549 /// and may be ignored.
1550 ///
1551 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1552 ///
1553 /// # Safety
1554 ///
1555 /// Behavior is undefined if any of the following conditions are violated:
1556 ///
1557 /// * `dst` must be [valid] for writes.
1558 ///
1559 /// * `dst` must be properly aligned.
1560 ///
1561 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
1562 ///
1563 /// [valid]: self#safety
1564 ///
1565 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1566 /// on questions involving concurrent access from multiple threads. Volatile
1567 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1568 /// a race between a `write_volatile` and any other operation (reading or writing)
1569 /// on the same location is undefined behavior.
1570 ///
1571 /// # Examples
1572 ///
1573 /// Basic usage:
1574 ///
1575 /// ```
1576 /// let mut x = 0;
1577 /// let y = &mut x as *mut i32;
1578 /// let z = 12;
1579 ///
1580 /// unsafe {
1581 ///     std::ptr::write_volatile(y, z);
1582 ///     assert_eq!(std::ptr::read_volatile(y), 12);
1583 /// }
1584 /// ```
1585 #[inline]
1586 #[stable(feature = "volatile", since = "1.9.0")]
1587 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1588 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
1589     // SAFETY: the caller must uphold the safety contract for `volatile_store`.
1590     unsafe {
1591         assert_unsafe_precondition!(
1592             "ptr::write_volatile requires that the pointer argument is aligned and non-null",
1593             [T](dst: *mut T) => is_aligned_and_not_null(dst)
1594         );
1595         intrinsics::volatile_store(dst, src);
1596     }
1597 }
1598
1599 /// Align pointer `p`.
1600 ///
1601 /// Calculate offset (in terms of elements of `size_of::<T>()` stride) that has to be applied
1602 /// to pointer `p` so that pointer `p` would get aligned to `a`.
1603 ///
1604 /// # Safety
1605 /// `a` must be a power of two.
1606 ///
1607 /// # Notes
1608 /// This implementation has been carefully tailored to not panic. It is UB for this to panic.
1609 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
1610 /// constants.
1611 ///
1612 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
1613 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
1614 /// than trying to adapt this to accommodate that change.
1615 ///
1616 /// Any questions go to @nagisa.
1617 #[lang = "align_offset"]
1618 pub(crate) const unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
1619     // FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <=
1620     // 1, where the method versions of these operations are not inlined.
1621     use intrinsics::{
1622         cttz_nonzero, exact_div, mul_with_overflow, unchecked_rem, unchecked_shl, unchecked_shr,
1623         unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub,
1624     };
1625
1626     /// Calculate multiplicative modular inverse of `x` modulo `m`.
1627     ///
1628     /// This implementation is tailored for `align_offset` and has following preconditions:
1629     ///
1630     /// * `m` is a power-of-two;
1631     /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
1632     ///
1633     /// Implementation of this function shall not panic. Ever.
1634     #[inline]
1635     const unsafe fn mod_inv(x: usize, m: usize) -> usize {
1636         /// Multiplicative modular inverse table modulo 2⁴ = 16.
1637         ///
1638         /// Note, that this table does not contain values where inverse does not exist (i.e., for
1639         /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
1640         const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
1641         /// Modulo for which the `INV_TABLE_MOD_16` is intended.
1642         const INV_TABLE_MOD: usize = 16;
1643
1644         // SAFETY: `m` is required to be a power-of-two, hence non-zero.
1645         let m_minus_one = unsafe { unchecked_sub(m, 1) };
1646         let mut inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
1647         let mut mod_gate = INV_TABLE_MOD;
1648         // We iterate "up" using the following formula:
1649         //
1650         // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
1651         //
1652         // This application needs to be applied at least until `2²ⁿ ≥ m`, at which point we can
1653         // finally reduce the computation to our desired `m` by taking `inverse mod m`.
1654         //
1655         // This computation is `O(log log m)`, which is to say, that on 64-bit machines this loop
1656         // will always finish in at most 4 iterations.
1657         loop {
1658             // y = y * (2 - xy) mod n
1659             //
1660             // Note, that we use wrapping operations here intentionally – the original formula
1661             // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
1662             // usize::MAX` instead, because we take the result `mod n` at the end
1663             // anyway.
1664             if mod_gate >= m {
1665                 break;
1666             }
1667             inverse = wrapping_mul(inverse, wrapping_sub(2usize, wrapping_mul(x, inverse)));
1668             let (new_gate, overflow) = mul_with_overflow(mod_gate, mod_gate);
1669             if overflow {
1670                 break;
1671             }
1672             mod_gate = new_gate;
1673         }
1674         inverse & m_minus_one
1675     }
1676
1677     let stride = mem::size_of::<T>();
1678
1679     // SAFETY: This is just an inlined `p.addr()` (which is not
1680     // a `const fn` so we cannot call it).
1681     // During const eval, we hook this function to ensure that the pointer never
1682     // has provenance, making this sound.
1683     let addr: usize = unsafe { mem::transmute(p) };
1684
1685     // SAFETY: `a` is a power-of-two, therefore non-zero.
1686     let a_minus_one = unsafe { unchecked_sub(a, 1) };
1687
1688     if stride == 0 {
1689         // SPECIAL_CASE: handle 0-sized types. No matter how many times we step, the address will
1690         // stay the same, so no offset will be able to align the pointer unless it is already
1691         // aligned. This branch _will_ be optimized out as `stride` is known at compile-time.
1692         let p_mod_a = addr & a_minus_one;
1693         return if p_mod_a == 0 { 0 } else { usize::MAX };
1694     }
1695
1696     // SAFETY: `stride == 0` case has been handled by the special case above.
1697     let a_mod_stride = unsafe { unchecked_rem(a, stride) };
1698     if a_mod_stride == 0 {
1699         // SPECIAL_CASE: In cases where the `a` is divisible by `stride`, byte offset to align a
1700         // pointer can be computed more simply through `-p (mod a)`. In the off-chance the byte
1701         // offset is not a multiple of `stride`, the input pointer was misaligned and no pointer
1702         // offset will be able to produce a `p` aligned to the specified `a`.
1703         //
1704         // The naive `-p (mod a)` equation  inhibits LLVM's ability to select instructions
1705         // like `lea`. We compute `(round_up_to_next_alignment(p, a) - p)` instead. This
1706         // redistributes operations around the load-bearing, but pessimizing `and` instruction
1707         // sufficiently for LLVM to be able to utilize the various optimizations it knows about.
1708         //
1709         // LLVM handles the branch here particularly nicely. If this branch needs to be evaluated
1710         // at runtime, it will produce a mask `if addr_mod_stride == 0 { 0 } else { usize::MAX }`
1711         // in a branch-free way and then bitwise-OR it with whatever result the `-p mod a`
1712         // computation produces.
1713
1714         // SAFETY: `stride == 0` case has been handled by the special case above.
1715         let addr_mod_stride = unsafe { unchecked_rem(addr, stride) };
1716
1717         return if addr_mod_stride == 0 {
1718             let aligned_address = wrapping_add(addr, a_minus_one) & wrapping_sub(0, a);
1719             let byte_offset = wrapping_sub(aligned_address, addr);
1720             // SAFETY: `stride` is non-zero. This is guaranteed to divide exactly as well, because
1721             // addr has been verified to be aligned to the original type’s alignment requirements.
1722             unsafe { exact_div(byte_offset, stride) }
1723         } else {
1724             usize::MAX
1725         };
1726     }
1727
1728     // GENERAL_CASE: From here on we’re handling the very general case where `addr` may be
1729     // misaligned, there isn’t an obvious relationship between `stride` and `a` that we can take an
1730     // advantage of, etc. This case produces machine code that isn’t particularly high quality,
1731     // compared to the special cases above. The code produced here is still within the realm of
1732     // miracles, given the situations this case has to deal with.
1733
1734     // SAFETY: a is power-of-two hence non-zero. stride == 0 case is handled above.
1735     let gcdpow = unsafe { cttz_nonzero(stride).min(cttz_nonzero(a)) };
1736     // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a usize.
1737     let gcd = unsafe { unchecked_shl(1usize, gcdpow) };
1738     // SAFETY: gcd is always greater or equal to 1.
1739     if addr & unsafe { unchecked_sub(gcd, 1) } == 0 {
1740         // This branch solves for the following linear congruence equation:
1741         //
1742         // ` p + so = 0 mod a `
1743         //
1744         // `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
1745         // requested alignment.
1746         //
1747         // With `g = gcd(a, s)`, and the above condition asserting that `p` is also divisible by
1748         // `g`, we can denote `a' = a/g`, `s' = s/g`, `p' = p/g`, then this becomes equivalent to:
1749         //
1750         // ` p' + s'o = 0 mod a' `
1751         // ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
1752         //
1753         // The first term is "the relative alignment of `p` to `a`" (divided by the `g`), the
1754         // second term is "how does incrementing `p` by `s` bytes change the relative alignment of
1755         // `p`" (again divided by `g`). Division by `g` is necessary to make the inverse well
1756         // formed if `a` and `s` are not co-prime.
1757         //
1758         // Furthermore, the result produced by this solution is not "minimal", so it is necessary
1759         // to take the result `o mod lcm(s, a)`. This `lcm(s, a)` is the same as `a'`.
1760
1761         // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1762         // `a`.
1763         let a2 = unsafe { unchecked_shr(a, gcdpow) };
1764         // SAFETY: `a2` is non-zero. Shifting `a` by `gcdpow` cannot shift out any of the set bits
1765         // in `a` (of which it has exactly one).
1766         let a2minus1 = unsafe { unchecked_sub(a2, 1) };
1767         // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1768         // `a`.
1769         let s2 = unsafe { unchecked_shr(stride & a_minus_one, gcdpow) };
1770         // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1771         // `a`. Furthermore, the subtraction cannot overflow, because `a2 = a >> gcdpow` will
1772         // always be strictly greater than `(p % a) >> gcdpow`.
1773         let minusp2 = unsafe { unchecked_sub(a2, unchecked_shr(addr & a_minus_one, gcdpow)) };
1774         // SAFETY: `a2` is a power-of-two, as proven above. `s2` is strictly less than `a2`
1775         // because `(s % a) >> gcdpow` is strictly less than `a >> gcdpow`.
1776         return wrapping_mul(minusp2, unsafe { mod_inv(s2, a2) }) & a2minus1;
1777     }
1778
1779     // Cannot be aligned at all.
1780     usize::MAX
1781 }
1782
1783 /// Compares raw pointers for equality.
1784 ///
1785 /// This is the same as using the `==` operator, but less generic:
1786 /// the arguments have to be `*const T` raw pointers,
1787 /// not anything that implements `PartialEq`.
1788 ///
1789 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
1790 /// by their address rather than comparing the values they point to
1791 /// (which is what the `PartialEq for &T` implementation does).
1792 ///
1793 /// When comparing wide pointers, both the address and the metadata are tested for equality.
1794 /// However, note that comparing trait object pointers (`*const dyn Trait`) is unreliable: pointers
1795 /// to values of the same underlying type can compare inequal (because vtables are duplicated in
1796 /// multiple codegen units), and pointers to values of *different* underlying type can compare equal
1797 /// (since identical vtables can be deduplicated within a codegen unit).
1798 ///
1799 /// # Examples
1800 ///
1801 /// ```
1802 /// use std::ptr;
1803 ///
1804 /// let five = 5;
1805 /// let other_five = 5;
1806 /// let five_ref = &five;
1807 /// let same_five_ref = &five;
1808 /// let other_five_ref = &other_five;
1809 ///
1810 /// assert!(five_ref == same_five_ref);
1811 /// assert!(ptr::eq(five_ref, same_five_ref));
1812 ///
1813 /// assert!(five_ref == other_five_ref);
1814 /// assert!(!ptr::eq(five_ref, other_five_ref));
1815 /// ```
1816 ///
1817 /// Slices are also compared by their length (fat pointers):
1818 ///
1819 /// ```
1820 /// let a = [1, 2, 3];
1821 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
1822 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
1823 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
1824 /// ```
1825 #[stable(feature = "ptr_eq", since = "1.17.0")]
1826 #[inline(always)]
1827 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
1828     a == b
1829 }
1830
1831 /// Hash a raw pointer.
1832 ///
1833 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
1834 /// by its address rather than the value it points to
1835 /// (which is what the `Hash for &T` implementation does).
1836 ///
1837 /// # Examples
1838 ///
1839 /// ```
1840 /// use std::collections::hash_map::DefaultHasher;
1841 /// use std::hash::{Hash, Hasher};
1842 /// use std::ptr;
1843 ///
1844 /// let five = 5;
1845 /// let five_ref = &five;
1846 ///
1847 /// let mut hasher = DefaultHasher::new();
1848 /// ptr::hash(five_ref, &mut hasher);
1849 /// let actual = hasher.finish();
1850 ///
1851 /// let mut hasher = DefaultHasher::new();
1852 /// (five_ref as *const i32).hash(&mut hasher);
1853 /// let expected = hasher.finish();
1854 ///
1855 /// assert_eq!(actual, expected);
1856 /// ```
1857 #[stable(feature = "ptr_hash", since = "1.35.0")]
1858 pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
1859     use crate::hash::Hash;
1860     hashee.hash(into);
1861 }
1862
1863 // If this is a unary fn pointer, it adds a doc comment.
1864 // Otherwise, it hides the docs entirely.
1865 macro_rules! maybe_fnptr_doc {
1866     (@ #[$meta:meta] $item:item) => {
1867         #[doc(hidden)]
1868         #[$meta]
1869         $item
1870     };
1871     ($a:ident @ #[$meta:meta] $item:item) => {
1872         #[doc(fake_variadic)]
1873         #[doc = "This trait is implemented for function pointers with up to twelve arguments."]
1874         #[$meta]
1875         $item
1876     };
1877     ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
1878         #[doc(hidden)]
1879         #[$meta]
1880         $item
1881     };
1882 }
1883
1884 // FIXME(strict_provenance_magic): function pointers have buggy codegen that
1885 // necessitates casting to a usize to get the backend to do the right thing.
1886 // for now I will break AVR to silence *a billion* lints. We should probably
1887 // have a proper "opaque function pointer type" to handle this kind of thing.
1888
1889 // Impls for function pointers
1890 macro_rules! fnptr_impls_safety_abi {
1891     ($FnTy: ty, $($Arg: ident),*) => {
1892         fnptr_impls_safety_abi! { #[stable(feature = "fnptr_impls", since = "1.4.0")] $FnTy, $($Arg),* }
1893     };
1894     (@c_unwind $FnTy: ty, $($Arg: ident),*) => {
1895         fnptr_impls_safety_abi! { #[unstable(feature = "c_unwind", issue = "74990")] $FnTy, $($Arg),* }
1896     };
1897     (#[$meta:meta] $FnTy: ty, $($Arg: ident),*) => {
1898         maybe_fnptr_doc! {
1899             $($Arg)* @
1900             #[$meta]
1901             impl<Ret, $($Arg),*> PartialEq for $FnTy {
1902                 #[inline]
1903                 fn eq(&self, other: &Self) -> bool {
1904                     *self as usize == *other as usize
1905                 }
1906             }
1907         }
1908
1909         maybe_fnptr_doc! {
1910             $($Arg)* @
1911             #[$meta]
1912             impl<Ret, $($Arg),*> Eq for $FnTy {}
1913         }
1914
1915         maybe_fnptr_doc! {
1916             $($Arg)* @
1917             #[$meta]
1918             impl<Ret, $($Arg),*> PartialOrd for $FnTy {
1919                 #[inline]
1920                 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1921                     (*self as usize).partial_cmp(&(*other as usize))
1922                 }
1923             }
1924         }
1925
1926         maybe_fnptr_doc! {
1927             $($Arg)* @
1928             #[$meta]
1929             impl<Ret, $($Arg),*> Ord for $FnTy {
1930                 #[inline]
1931                 fn cmp(&self, other: &Self) -> Ordering {
1932                     (*self as usize).cmp(&(*other as usize))
1933                 }
1934             }
1935         }
1936
1937         maybe_fnptr_doc! {
1938             $($Arg)* @
1939             #[$meta]
1940             impl<Ret, $($Arg),*> hash::Hash for $FnTy {
1941                 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
1942                     state.write_usize(*self as usize)
1943                 }
1944             }
1945         }
1946
1947         maybe_fnptr_doc! {
1948             $($Arg)* @
1949             #[$meta]
1950             impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
1951                 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1952                     fmt::pointer_fmt_inner(*self as usize, f)
1953                 }
1954             }
1955         }
1956
1957         maybe_fnptr_doc! {
1958             $($Arg)* @
1959             #[$meta]
1960             impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
1961                 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1962                     fmt::pointer_fmt_inner(*self as usize, f)
1963                 }
1964             }
1965         }
1966     }
1967 }
1968
1969 macro_rules! fnptr_impls_args {
1970     ($($Arg: ident),+) => {
1971         fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1972         fnptr_impls_safety_abi! { extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1973         fnptr_impls_safety_abi! { extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1974         fnptr_impls_safety_abi! { @c_unwind extern "C-unwind" fn($($Arg),+) -> Ret, $($Arg),+ }
1975         fnptr_impls_safety_abi! { @c_unwind extern "C-unwind" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1976         fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1977         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1978         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1979         fnptr_impls_safety_abi! { @c_unwind unsafe extern "C-unwind" fn($($Arg),+) -> Ret, $($Arg),+ }
1980         fnptr_impls_safety_abi! { @c_unwind unsafe extern "C-unwind" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1981     };
1982     () => {
1983         // No variadic functions with 0 parameters
1984         fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
1985         fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
1986         fnptr_impls_safety_abi! { @c_unwind extern "C-unwind" fn() -> Ret, }
1987         fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
1988         fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
1989         fnptr_impls_safety_abi! { @c_unwind unsafe extern "C-unwind" fn() -> Ret, }
1990     };
1991 }
1992
1993 fnptr_impls_args! {}
1994 fnptr_impls_args! { T }
1995 fnptr_impls_args! { A, B }
1996 fnptr_impls_args! { A, B, C }
1997 fnptr_impls_args! { A, B, C, D }
1998 fnptr_impls_args! { A, B, C, D, E }
1999 fnptr_impls_args! { A, B, C, D, E, F }
2000 fnptr_impls_args! { A, B, C, D, E, F, G }
2001 fnptr_impls_args! { A, B, C, D, E, F, G, H }
2002 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
2003 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
2004 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
2005 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
2006
2007 /// Create a `const` raw pointer to a place, without creating an intermediate reference.
2008 ///
2009 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
2010 /// and points to initialized data. For cases where those requirements do not hold,
2011 /// raw pointers should be used instead. However, `&expr as *const _` creates a reference
2012 /// before casting it to a raw pointer, and that reference is subject to the same rules
2013 /// as all other references. This macro can create a raw pointer *without* creating
2014 /// a reference first.
2015 ///
2016 /// Note, however, that the `expr` in `addr_of!(expr)` is still subject to all
2017 /// the usual rules. In particular, `addr_of!(*ptr::null())` is Undefined
2018 /// Behavior because it dereferences a null pointer.
2019 ///
2020 /// # Example
2021 ///
2022 /// ```
2023 /// use std::ptr;
2024 ///
2025 /// #[repr(packed)]
2026 /// struct Packed {
2027 ///     f1: u8,
2028 ///     f2: u16,
2029 /// }
2030 ///
2031 /// let packed = Packed { f1: 1, f2: 2 };
2032 /// // `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
2033 /// let raw_f2 = ptr::addr_of!(packed.f2);
2034 /// assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
2035 /// ```
2036 ///
2037 /// See [`addr_of_mut`] for how to create a pointer to unininitialized data.
2038 /// Doing that with `addr_of` would not make much sense since one could only
2039 /// read the data, and that would be Undefined Behavior.
2040 #[stable(feature = "raw_ref_macros", since = "1.51.0")]
2041 #[rustc_macro_transparency = "semitransparent"]
2042 #[allow_internal_unstable(raw_ref_op)]
2043 pub macro addr_of($place:expr) {
2044     &raw const $place
2045 }
2046
2047 /// Create a `mut` raw pointer to a place, without creating an intermediate reference.
2048 ///
2049 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
2050 /// and points to initialized data. For cases where those requirements do not hold,
2051 /// raw pointers should be used instead. However, `&mut expr as *mut _` creates a reference
2052 /// before casting it to a raw pointer, and that reference is subject to the same rules
2053 /// as all other references. This macro can create a raw pointer *without* creating
2054 /// a reference first.
2055 ///
2056 /// Note, however, that the `expr` in `addr_of_mut!(expr)` is still subject to all
2057 /// the usual rules. In particular, `addr_of_mut!(*ptr::null_mut())` is Undefined
2058 /// Behavior because it dereferences a null pointer.
2059 ///
2060 /// # Examples
2061 ///
2062 /// **Creating a pointer to unaligned data:**
2063 ///
2064 /// ```
2065 /// use std::ptr;
2066 ///
2067 /// #[repr(packed)]
2068 /// struct Packed {
2069 ///     f1: u8,
2070 ///     f2: u16,
2071 /// }
2072 ///
2073 /// let mut packed = Packed { f1: 1, f2: 2 };
2074 /// // `&mut packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
2075 /// let raw_f2 = ptr::addr_of_mut!(packed.f2);
2076 /// unsafe { raw_f2.write_unaligned(42); }
2077 /// assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
2078 /// ```
2079 ///
2080 /// **Creating a pointer to uninitialized data:**
2081 ///
2082 /// ```rust
2083 /// use std::{ptr, mem::MaybeUninit};
2084 ///
2085 /// struct Demo {
2086 ///     field: bool,
2087 /// }
2088 ///
2089 /// let mut uninit = MaybeUninit::<Demo>::uninit();
2090 /// // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
2091 /// // and thus be Undefined Behavior!
2092 /// let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) };
2093 /// unsafe { f1_ptr.write(true); }
2094 /// let init = unsafe { uninit.assume_init() };
2095 /// ```
2096 #[stable(feature = "raw_ref_macros", since = "1.51.0")]
2097 #[rustc_macro_transparency = "semitransparent"]
2098 #[allow_internal_unstable(raw_ref_op)]
2099 pub macro addr_of_mut($place:expr) {
2100     &raw mut $place
2101 }