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