core/sync/
atomic.rs

1//! Atomic types
2//!
3//! Atomic types provide primitive shared-memory communication between
4//! threads, and are the building blocks of other concurrent
5//! types.
6//!
7//! This module defines atomic versions of a select number of primitive
8//! types, including [`AtomicBool`], [`AtomicIsize`], [`AtomicUsize`],
9//! [`AtomicI8`], [`AtomicU16`], etc.
10//! Atomic types present operations that, when used correctly, synchronize
11//! updates between threads.
12//!
13//! Atomic variables are safe to share between threads (they implement [`Sync`])
14//! but they do not themselves provide the mechanism for sharing and follow the
15//! [threading model](../../../std/thread/index.html#the-threading-model) of Rust.
16//! The most common way to share an atomic variable is to put it into an [`Arc`][arc] (an
17//! atomically-reference-counted shared pointer).
18//!
19//! [arc]: ../../../std/sync/struct.Arc.html
20//!
21//! Atomic types may be stored in static variables, initialized using
22//! the constant initializers like [`AtomicBool::new`]. Atomic statics
23//! are often used for lazy global initialization.
24//!
25//! ## Memory model for atomic accesses
26//!
27//! Rust atomics currently follow the same rules as [C++20 atomics][cpp], specifically the rules
28//! from the [`intro.races`][cpp-intro.races] section, without the "consume" memory ordering. Since
29//! C++ uses an object-based memory model whereas Rust is access-based, a bit of translation work
30//! has to be done to apply the C++ rules to Rust: whenever C++ talks about "the value of an
31//! object", we understand that to mean the resulting bytes obtained when doing a read. When the C++
32//! standard talks about "the value of an atomic object", this refers to the result of doing an
33//! atomic load (via the operations provided in this module). A "modification of an atomic object"
34//! refers to an atomic store.
35//!
36//! The end result is *almost* equivalent to saying that creating a *shared reference* to one of the
37//! Rust atomic types corresponds to creating an `atomic_ref` in C++, with the `atomic_ref` being
38//! destroyed when the lifetime of the shared reference ends. The main difference is that Rust
39//! permits concurrent atomic and non-atomic reads to the same memory as those cause no issue in the
40//! C++ memory model, they are just forbidden in C++ because memory is partitioned into "atomic
41//! objects" and "non-atomic objects" (with `atomic_ref` temporarily converting a non-atomic object
42//! into an atomic object).
43//!
44//! The most important aspect of this model is that *data races* are undefined behavior. A data race
45//! is defined as conflicting non-synchronized accesses where at least one of the accesses is
46//! non-atomic. Here, accesses are *conflicting* if they affect overlapping regions of memory and at
47//! least one of them is a write. (A `compare_exchange` or `compare_exchange_weak` that does not
48//! succeed is not considered a write.) They are *non-synchronized* if neither of them
49//! *happens-before* the other, according to the happens-before order of the memory model.
50//!
51//! The other possible cause of undefined behavior in the memory model are mixed-size accesses: Rust
52//! inherits the C++ limitation that non-synchronized conflicting atomic accesses may not partially
53//! overlap. In other words, every pair of non-synchronized atomic accesses must be either disjoint,
54//! access the exact same memory (including using the same access size), or both be reads.
55//!
56//! Each atomic access takes an [`Ordering`] which defines how the operation interacts with the
57//! happens-before order. These orderings behave the same as the corresponding [C++20 atomic
58//! orderings][cpp_memory_order]. For more information, see the [nomicon].
59//!
60//! [cpp]: https://en.cppreference.com/w/cpp/atomic
61//! [cpp-intro.races]: https://timsong-cpp.github.io/cppwp/n4868/intro.multithread#intro.races
62//! [cpp_memory_order]: https://en.cppreference.com/w/cpp/atomic/memory_order
63//! [nomicon]: ../../../nomicon/atomics.html
64//!
65//! ```rust,no_run undefined_behavior
66//! use std::sync::atomic::{AtomicU16, AtomicU8, Ordering};
67//! use std::mem::transmute;
68//! use std::thread;
69//!
70//! let atomic = AtomicU16::new(0);
71//!
72//! thread::scope(|s| {
73//!     // This is UB: conflicting non-synchronized accesses, at least one of which is non-atomic.
74//!     s.spawn(|| atomic.store(1, Ordering::Relaxed)); // atomic store
75//!     s.spawn(|| unsafe { atomic.as_ptr().write(2) }); // non-atomic write
76//! });
77//!
78//! thread::scope(|s| {
79//!     // This is fine: the accesses do not conflict (as none of them performs any modification).
80//!     // In C++ this would be disallowed since creating an `atomic_ref` precludes
81//!     // further non-atomic accesses, but Rust does not have that limitation.
82//!     s.spawn(|| atomic.load(Ordering::Relaxed)); // atomic load
83//!     s.spawn(|| unsafe { atomic.as_ptr().read() }); // non-atomic read
84//! });
85//!
86//! thread::scope(|s| {
87//!     // This is fine: `join` synchronizes the code in a way such that the atomic
88//!     // store happens-before the non-atomic write.
89//!     let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed)); // atomic store
90//!     handle.join().expect("thread won't panic"); // synchronize
91//!     s.spawn(|| unsafe { atomic.as_ptr().write(2) }); // non-atomic write
92//! });
93//!
94//! thread::scope(|s| {
95//!     // This is UB: non-synchronized conflicting differently-sized atomic accesses.
96//!     s.spawn(|| atomic.store(1, Ordering::Relaxed));
97//!     s.spawn(|| unsafe {
98//!         let differently_sized = transmute::<&AtomicU16, &AtomicU8>(&atomic);
99//!         differently_sized.store(2, Ordering::Relaxed);
100//!     });
101//! });
102//!
103//! thread::scope(|s| {
104//!     // This is fine: `join` synchronizes the code in a way such that
105//!     // the 1-byte store happens-before the 2-byte store.
106//!     let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed));
107//!     handle.join().expect("thread won't panic");
108//!     s.spawn(|| unsafe {
109//!         let differently_sized = transmute::<&AtomicU16, &AtomicU8>(&atomic);
110//!         differently_sized.store(2, Ordering::Relaxed);
111//!     });
112//! });
113//! ```
114//!
115//! # Portability
116//!
117//! All atomic types in this module are guaranteed to be [lock-free] if they're
118//! available. This means they don't internally acquire a global mutex. Atomic
119//! types and operations are not guaranteed to be wait-free. This means that
120//! operations like `fetch_or` may be implemented with a compare-and-swap loop.
121//!
122//! Atomic operations may be implemented at the instruction layer with
123//! larger-size atomics. For example some platforms use 4-byte atomic
124//! instructions to implement `AtomicI8`. Note that this emulation should not
125//! have an impact on correctness of code, it's just something to be aware of.
126//!
127//! The atomic types in this module might not be available on all platforms. The
128//! atomic types here are all widely available, however, and can generally be
129//! relied upon existing. Some notable exceptions are:
130//!
131//! * PowerPC and MIPS platforms with 32-bit pointers do not have `AtomicU64` or
132//!   `AtomicI64` types.
133//! * Legacy ARM platforms like ARMv4T and ARMv5TE have very limited hardware
134//!   support for atomics. The bare-metal targets disable this module
135//!   entirely, but the Linux targets [use the kernel] to assist (which comes
136//!   with a performance penalty). It's not until ARMv6K onwards that ARM CPUs
137//!   have support for load/store and Compare and Swap (CAS) atomics in hardware.
138//! * ARMv6-M and ARMv8-M baseline targets (`thumbv6m-*` and
139//!   `thumbv8m.base-*`) only provide `load` and `store` operations, and do
140//!   not support Compare and Swap (CAS) operations, such as `swap`,
141//!   `fetch_add`, etc. Full CAS support is available on ARMv7-M and ARMv8-M
142//!   Mainline (`thumbv7m-*`, `thumbv7em*` and `thumbv8m.main-*`).
143//!
144//! [use the kernel]: https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt
145//!
146//! Note that future platforms may be added that also do not have support for
147//! some atomic operations. Maximally portable code will want to be careful
148//! about which atomic types are used. `AtomicUsize` and `AtomicIsize` are
149//! generally the most portable, but even then they're not available everywhere.
150//! For reference, the `std` library requires `AtomicBool`s and pointer-sized atomics, although
151//! `core` does not.
152//!
153//! The `#[cfg(target_has_atomic)]` attribute can be used to conditionally
154//! compile based on the target's supported bit widths. It is a key-value
155//! option set for each supported size, with values "8", "16", "32", "64",
156//! "128", and "ptr" for pointer-sized atomics.
157//!
158//! [lock-free]: https://en.wikipedia.org/wiki/Non-blocking_algorithm
159//!
160//! # Atomic accesses to read-only memory
161//!
162//! In general, *all* atomic accesses on read-only memory are undefined behavior. For instance, attempting
163//! to do a `compare_exchange` that will definitely fail (making it conceptually a read-only
164//! operation) can still cause a segmentation fault if the underlying memory page is mapped read-only. Since
165//! atomic `load`s might be implemented using compare-exchange operations, even a `load` can fault
166//! on read-only memory.
167//!
168//! For the purpose of this section, "read-only memory" is defined as memory that is read-only in
169//! the underlying target, i.e., the pages are mapped with a read-only flag and any attempt to write
170//! will cause a page fault. In particular, an `&u128` reference that points to memory that is
171//! read-write mapped is *not* considered to point to "read-only memory". In Rust, almost all memory
172//! is read-write; the only exceptions are memory created by `const` items or `static` items without
173//! interior mutability, and memory that was specifically marked as read-only by the operating
174//! system via platform-specific APIs.
175//!
176//! As an exception from the general rule stated above, "sufficiently small" atomic loads with
177//! `Ordering::Relaxed` are implemented in a way that works on read-only memory, and are hence not
178//! undefined behavior. The exact size limit for what makes a load "sufficiently small" varies
179//! depending on the target:
180//!
181//! | `target_arch` | Size limit |
182//! |---------------|---------|
183//! | `x86`, `arm`, `loongarch32`, `mips`, `mips32r6`, `powerpc`, `riscv32`, `sparc`, `hexagon` | 4 bytes |
184//! | `x86_64`, `aarch64`, `loongarch64`, `mips64`, `mips64r6`, `powerpc64`, `riscv64`, `sparc64`, `s390x` | 8 bytes |
185//!
186//! Atomics loads that are larger than this limit as well as atomic loads with ordering other
187//! than `Relaxed`, as well as *all* atomic loads on targets not listed in the table, might still be
188//! read-only under certain conditions, but that is not a stable guarantee and should not be relied
189//! upon.
190//!
191//! If you need to do an acquire load on read-only memory, you can do a relaxed load followed by an
192//! acquire fence instead.
193//!
194//! # Examples
195//!
196//! A simple spinlock:
197//!
198//! ```ignore-wasm
199//! use std::sync::Arc;
200//! use std::sync::atomic::{AtomicUsize, Ordering};
201//! use std::{hint, thread};
202//!
203//! fn main() {
204//!     let spinlock = Arc::new(AtomicUsize::new(1));
205//!
206//!     let spinlock_clone = Arc::clone(&spinlock);
207//!
208//!     let thread = thread::spawn(move || {
209//!         spinlock_clone.store(0, Ordering::Release);
210//!     });
211//!
212//!     // Wait for the other thread to release the lock
213//!     while spinlock.load(Ordering::Acquire) != 0 {
214//!         hint::spin_loop();
215//!     }
216//!
217//!     if let Err(panic) = thread.join() {
218//!         println!("Thread had an error: {panic:?}");
219//!     }
220//! }
221//! ```
222//!
223//! Keep a global count of live threads:
224//!
225//! ```
226//! use std::sync::atomic::{AtomicUsize, Ordering};
227//!
228//! static GLOBAL_THREAD_COUNT: AtomicUsize = AtomicUsize::new(0);
229//!
230//! // Note that Relaxed ordering doesn't synchronize anything
231//! // except the global thread counter itself.
232//! let old_thread_count = GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::Relaxed);
233//! // Note that this number may not be true at the moment of printing
234//! // because some other thread may have changed static value already.
235//! println!("live threads: {}", old_thread_count + 1);
236//! ```
237
238#![stable(feature = "rust1", since = "1.0.0")]
239#![cfg_attr(not(target_has_atomic_load_store = "8"), allow(dead_code))]
240#![cfg_attr(not(target_has_atomic_load_store = "8"), allow(unused_imports))]
241#![rustc_diagnostic_item = "atomic_mod"]
242// Clippy complains about the pattern of "safe function calling unsafe function taking pointers".
243// This happens with AtomicPtr intrinsics but is fine, as the pointers clippy is concerned about
244// are just normal values that get loaded/stored, but not dereferenced.
245#![allow(clippy::not_unsafe_ptr_arg_deref)]
246
247use self::Ordering::*;
248use crate::cell::UnsafeCell;
249#[cfg(not(feature = "ferrocene_subset"))]
250use crate::hint::spin_loop;
251use crate::intrinsics::AtomicOrdering as AO;
252#[cfg(not(feature = "ferrocene_subset"))]
253use crate::{fmt, intrinsics};
254
255// Ferrocene addition: imports for certified subset
256#[cfg(feature = "ferrocene_subset")]
257#[rustfmt::skip]
258use crate::intrinsics;
259
260trait Sealed {}
261
262/// A marker trait for primitive types which can be modified atomically.
263///
264/// This is an implementation detail for <code>[Atomic]\<T></code> which may disappear or be replaced at any time.
265///
266/// # Safety
267///
268/// Types implementing this trait must be primitives that can be modified atomically.
269///
270/// The associated `Self::AtomicInner` type must have the same size and bit validity as `Self`,
271/// but may have a higher alignment requirement, so the following `transmute`s are sound:
272///
273/// - `&mut Self::AtomicInner` as `&mut Self`
274/// - `Self` as `Self::AtomicInner` or the reverse
275#[unstable(
276    feature = "atomic_internals",
277    reason = "implementation detail which may disappear or be replaced at any time",
278    issue = "none"
279)]
280#[expect(private_bounds)]
281pub unsafe trait AtomicPrimitive: Sized + Copy + Sealed {
282    /// Temporary implementation detail.
283    type AtomicInner: Sized;
284}
285
286macro impl_atomic_primitive(
287    $Atom:ident $(<$T:ident>)? ($Primitive:ty),
288    size($size:literal),
289    align($align:literal) $(,)?
290) {
291    impl $(<$T>)? Sealed for $Primitive {}
292
293    #[unstable(
294        feature = "atomic_internals",
295        reason = "implementation detail which may disappear or be replaced at any time",
296        issue = "none"
297    )]
298    #[cfg(target_has_atomic_load_store = $size)]
299    unsafe impl $(<$T>)? AtomicPrimitive for $Primitive {
300        type AtomicInner = $Atom $(<$T>)?;
301    }
302}
303
304impl_atomic_primitive!(AtomicBool(bool), size("8"), align(1));
305#[cfg(not(feature = "ferrocene_subset"))]
306impl_atomic_primitive!(AtomicI8(i8), size("8"), align(1));
307impl_atomic_primitive!(AtomicU8(u8), size("8"), align(1));
308#[cfg(not(feature = "ferrocene_subset"))]
309impl_atomic_primitive!(AtomicI16(i16), size("16"), align(2));
310#[cfg(not(feature = "ferrocene_subset"))]
311impl_atomic_primitive!(AtomicU16(u16), size("16"), align(2));
312#[cfg(not(feature = "ferrocene_subset"))]
313impl_atomic_primitive!(AtomicI32(i32), size("32"), align(4));
314impl_atomic_primitive!(AtomicU32(u32), size("32"), align(4));
315#[cfg(not(feature = "ferrocene_subset"))]
316impl_atomic_primitive!(AtomicI64(i64), size("64"), align(8));
317impl_atomic_primitive!(AtomicU64(u64), size("64"), align(8));
318#[cfg(not(feature = "ferrocene_subset"))]
319impl_atomic_primitive!(AtomicI128(i128), size("128"), align(16));
320#[cfg(not(feature = "ferrocene_subset"))]
321impl_atomic_primitive!(AtomicU128(u128), size("128"), align(16));
322
323#[cfg(target_pointer_width = "16")]
324#[cfg(not(feature = "ferrocene_subset"))]
325impl_atomic_primitive!(AtomicIsize(isize), size("ptr"), align(2));
326#[cfg(target_pointer_width = "32")]
327#[cfg(not(feature = "ferrocene_subset"))]
328impl_atomic_primitive!(AtomicIsize(isize), size("ptr"), align(4));
329#[cfg(target_pointer_width = "64")]
330#[cfg(not(feature = "ferrocene_subset"))]
331impl_atomic_primitive!(AtomicIsize(isize), size("ptr"), align(8));
332
333#[cfg(target_pointer_width = "16")]
334impl_atomic_primitive!(AtomicUsize(usize), size("ptr"), align(2));
335#[cfg(target_pointer_width = "32")]
336impl_atomic_primitive!(AtomicUsize(usize), size("ptr"), align(4));
337#[cfg(target_pointer_width = "64")]
338impl_atomic_primitive!(AtomicUsize(usize), size("ptr"), align(8));
339
340#[cfg(target_pointer_width = "16")]
341#[cfg(not(feature = "ferrocene_subset"))]
342impl_atomic_primitive!(AtomicPtr<T>(*mut T), size("ptr"), align(2));
343#[cfg(target_pointer_width = "32")]
344#[cfg(not(feature = "ferrocene_subset"))]
345impl_atomic_primitive!(AtomicPtr<T>(*mut T), size("ptr"), align(4));
346#[cfg(target_pointer_width = "64")]
347#[cfg(not(feature = "ferrocene_subset"))]
348impl_atomic_primitive!(AtomicPtr<T>(*mut T), size("ptr"), align(8));
349
350/// A memory location which can be safely modified from multiple threads.
351///
352/// This has the same size and bit validity as the underlying type `T`. However,
353/// the alignment of this type is always equal to its size, even on targets where
354/// `T` has alignment less than its size.
355///
356/// For more about the differences between atomic types and non-atomic types as
357/// well as information about the portability of this type, please see the
358/// [module-level documentation].
359///
360/// **Note:** This type is only available on platforms that support atomic loads
361/// and stores of `T`.
362///
363/// [module-level documentation]: crate::sync::atomic
364#[unstable(feature = "generic_atomic", issue = "130539")]
365#[cfg(not(feature = "ferrocene_subset"))]
366pub type Atomic<T> = <T as AtomicPrimitive>::AtomicInner;
367
368// Some architectures don't have byte-sized atomics, which results in LLVM
369// emulating them using a LL/SC loop. However for AtomicBool we can take
370// advantage of the fact that it only ever contains 0 or 1 and use atomic OR/AND
371// instead, which LLVM can emulate using a larger atomic OR/AND operation.
372//
373// This list should only contain architectures which have word-sized atomic-or/
374// atomic-and instructions but don't natively support byte-sized atomics.
375#[cfg(target_has_atomic = "8")]
376const EMULATE_ATOMIC_BOOL: bool = cfg!(any(
377    target_arch = "riscv32",
378    target_arch = "riscv64",
379    target_arch = "loongarch32",
380    target_arch = "loongarch64"
381));
382
383/// A boolean type which can be safely shared between threads.
384///
385/// This type has the same size, alignment, and bit validity as a [`bool`].
386///
387/// **Note**: This type is only available on platforms that support atomic
388/// loads and stores of `u8`.
389#[cfg(target_has_atomic_load_store = "8")]
390#[stable(feature = "rust1", since = "1.0.0")]
391#[rustc_diagnostic_item = "AtomicBool"]
392#[repr(C, align(1))]
393pub struct AtomicBool {
394    v: UnsafeCell<u8>,
395}
396
397#[cfg(target_has_atomic_load_store = "8")]
398#[stable(feature = "rust1", since = "1.0.0")]
399#[cfg(not(feature = "ferrocene_subset"))]
400impl Default for AtomicBool {
401    /// Creates an `AtomicBool` initialized to `false`.
402    #[inline]
403    fn default() -> Self {
404        Self::new(false)
405    }
406}
407
408// Send is implicitly implemented for AtomicBool.
409#[cfg(target_has_atomic_load_store = "8")]
410#[stable(feature = "rust1", since = "1.0.0")]
411unsafe impl Sync for AtomicBool {}
412
413/// A raw pointer type which can be safely shared between threads.
414///
415/// This type has the same size and bit validity as a `*mut T`.
416///
417/// **Note**: This type is only available on platforms that support atomic
418/// loads and stores of pointers. Its size depends on the target pointer's size.
419#[cfg(target_has_atomic_load_store = "ptr")]
420#[stable(feature = "rust1", since = "1.0.0")]
421#[rustc_diagnostic_item = "AtomicPtr"]
422#[cfg_attr(target_pointer_width = "16", repr(C, align(2)))]
423#[cfg_attr(target_pointer_width = "32", repr(C, align(4)))]
424#[cfg_attr(target_pointer_width = "64", repr(C, align(8)))]
425#[cfg(not(feature = "ferrocene_subset"))]
426pub struct AtomicPtr<T> {
427    p: UnsafeCell<*mut T>,
428}
429
430#[cfg(target_has_atomic_load_store = "ptr")]
431#[stable(feature = "rust1", since = "1.0.0")]
432#[cfg(not(feature = "ferrocene_subset"))]
433impl<T> Default for AtomicPtr<T> {
434    /// Creates a null `AtomicPtr<T>`.
435    fn default() -> AtomicPtr<T> {
436        AtomicPtr::new(crate::ptr::null_mut())
437    }
438}
439
440#[cfg(target_has_atomic_load_store = "ptr")]
441#[stable(feature = "rust1", since = "1.0.0")]
442#[cfg(not(feature = "ferrocene_subset"))]
443unsafe impl<T> Send for AtomicPtr<T> {}
444#[cfg(target_has_atomic_load_store = "ptr")]
445#[stable(feature = "rust1", since = "1.0.0")]
446#[cfg(not(feature = "ferrocene_subset"))]
447unsafe impl<T> Sync for AtomicPtr<T> {}
448
449/// Atomic memory orderings
450///
451/// Memory orderings specify the way atomic operations synchronize memory.
452/// In its weakest [`Ordering::Relaxed`], only the memory directly touched by the
453/// operation is synchronized. On the other hand, a store-load pair of [`Ordering::SeqCst`]
454/// operations synchronize other memory while additionally preserving a total order of such
455/// operations across all threads.
456///
457/// Rust's memory orderings are [the same as those of
458/// C++20](https://en.cppreference.com/w/cpp/atomic/memory_order).
459///
460/// For more information see the [nomicon].
461///
462/// [nomicon]: ../../../nomicon/atomics.html
463#[stable(feature = "rust1", since = "1.0.0")]
464#[cfg_attr(not(feature = "ferrocene_subset"), derive(Copy, Clone, Debug, Eq, PartialEq, Hash))]
465#[cfg_attr(feature = "ferrocene_subset", derive(Copy, Clone))]
466#[non_exhaustive]
467#[rustc_diagnostic_item = "Ordering"]
468pub enum Ordering {
469    /// No ordering constraints, only atomic operations.
470    ///
471    /// Corresponds to [`memory_order_relaxed`] in C++20.
472    ///
473    /// [`memory_order_relaxed`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Relaxed_ordering
474    #[stable(feature = "rust1", since = "1.0.0")]
475    Relaxed,
476    /// When coupled with a store, all previous operations become ordered
477    /// before any load of this value with [`Acquire`] (or stronger) ordering.
478    /// In particular, all previous writes become visible to all threads
479    /// that perform an [`Acquire`] (or stronger) load of this value.
480    ///
481    /// Notice that using this ordering for an operation that combines loads
482    /// and stores leads to a [`Relaxed`] load operation!
483    ///
484    /// This ordering is only applicable for operations that can perform a store.
485    ///
486    /// Corresponds to [`memory_order_release`] in C++20.
487    ///
488    /// [`memory_order_release`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
489    #[stable(feature = "rust1", since = "1.0.0")]
490    Release,
491    /// When coupled with a load, if the loaded value was written by a store operation with
492    /// [`Release`] (or stronger) ordering, then all subsequent operations
493    /// become ordered after that store. In particular, all subsequent loads will see data
494    /// written before the store.
495    ///
496    /// Notice that using this ordering for an operation that combines loads
497    /// and stores leads to a [`Relaxed`] store operation!
498    ///
499    /// This ordering is only applicable for operations that can perform a load.
500    ///
501    /// Corresponds to [`memory_order_acquire`] in C++20.
502    ///
503    /// [`memory_order_acquire`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
504    #[stable(feature = "rust1", since = "1.0.0")]
505    Acquire,
506    /// Has the effects of both [`Acquire`] and [`Release`] together:
507    /// For loads it uses [`Acquire`] ordering. For stores it uses the [`Release`] ordering.
508    ///
509    /// Notice that in the case of `compare_and_swap`, it is possible that the operation ends up
510    /// not performing any store and hence it has just [`Acquire`] ordering. However,
511    /// `AcqRel` will never perform [`Relaxed`] accesses.
512    ///
513    /// This ordering is only applicable for operations that combine both loads and stores.
514    ///
515    /// Corresponds to [`memory_order_acq_rel`] in C++20.
516    ///
517    /// [`memory_order_acq_rel`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
518    #[stable(feature = "rust1", since = "1.0.0")]
519    AcqRel,
520    /// Like [`Acquire`]/[`Release`]/[`AcqRel`] (for load, store, and load-with-store
521    /// operations, respectively) with the additional guarantee that all threads see all
522    /// sequentially consistent operations in the same order.
523    ///
524    /// Corresponds to [`memory_order_seq_cst`] in C++20.
525    ///
526    /// [`memory_order_seq_cst`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Sequentially-consistent_ordering
527    #[stable(feature = "rust1", since = "1.0.0")]
528    SeqCst,
529}
530
531/// An [`AtomicBool`] initialized to `false`.
532#[cfg(target_has_atomic_load_store = "8")]
533#[stable(feature = "rust1", since = "1.0.0")]
534#[deprecated(
535    since = "1.34.0",
536    note = "the `new` function is now preferred",
537    suggestion = "AtomicBool::new(false)"
538)]
539#[cfg(not(feature = "ferrocene_subset"))]
540pub const ATOMIC_BOOL_INIT: AtomicBool = AtomicBool::new(false);
541
542#[cfg(target_has_atomic_load_store = "8")]
543impl AtomicBool {
544    /// Creates a new `AtomicBool`.
545    ///
546    /// # Examples
547    ///
548    /// ```
549    /// use std::sync::atomic::AtomicBool;
550    ///
551    /// let atomic_true = AtomicBool::new(true);
552    /// let atomic_false = AtomicBool::new(false);
553    /// ```
554    #[inline]
555    #[stable(feature = "rust1", since = "1.0.0")]
556    #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")]
557    #[must_use]
558    pub const fn new(v: bool) -> AtomicBool {
559        AtomicBool { v: UnsafeCell::new(v as u8) }
560    }
561
562    /// Creates a new `AtomicBool` from a pointer.
563    ///
564    /// # Examples
565    ///
566    /// ```
567    /// use std::sync::atomic::{self, AtomicBool};
568    ///
569    /// // Get a pointer to an allocated value
570    /// let ptr: *mut bool = Box::into_raw(Box::new(false));
571    ///
572    /// assert!(ptr.cast::<AtomicBool>().is_aligned());
573    ///
574    /// {
575    ///     // Create an atomic view of the allocated value
576    ///     let atomic = unsafe { AtomicBool::from_ptr(ptr) };
577    ///
578    ///     // Use `atomic` for atomic operations, possibly share it with other threads
579    ///     atomic.store(true, atomic::Ordering::Relaxed);
580    /// }
581    ///
582    /// // It's ok to non-atomically access the value behind `ptr`,
583    /// // since the reference to the atomic ended its lifetime in the block above
584    /// assert_eq!(unsafe { *ptr }, true);
585    ///
586    /// // Deallocate the value
587    /// unsafe { drop(Box::from_raw(ptr)) }
588    /// ```
589    ///
590    /// # Safety
591    ///
592    /// * `ptr` must be aligned to `align_of::<AtomicBool>()` (note that this is always true, since
593    ///   `align_of::<AtomicBool>() == 1`).
594    /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
595    /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
596    ///   allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
597    ///   sizes, without synchronization.
598    ///
599    /// [valid]: crate::ptr#safety
600    /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
601    #[inline]
602    #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
603    #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
604    #[cfg(not(feature = "ferrocene_subset"))]
605    pub const unsafe fn from_ptr<'a>(ptr: *mut bool) -> &'a AtomicBool {
606        // SAFETY: guaranteed by the caller
607        unsafe { &*ptr.cast() }
608    }
609
610    /// Returns a mutable reference to the underlying [`bool`].
611    ///
612    /// This is safe because the mutable reference guarantees that no other threads are
613    /// concurrently accessing the atomic data.
614    ///
615    /// # Examples
616    ///
617    /// ```
618    /// use std::sync::atomic::{AtomicBool, Ordering};
619    ///
620    /// let mut some_bool = AtomicBool::new(true);
621    /// assert_eq!(*some_bool.get_mut(), true);
622    /// *some_bool.get_mut() = false;
623    /// assert_eq!(some_bool.load(Ordering::SeqCst), false);
624    /// ```
625    #[inline]
626    #[stable(feature = "atomic_access", since = "1.15.0")]
627    #[cfg(not(feature = "ferrocene_subset"))]
628    pub fn get_mut(&mut self) -> &mut bool {
629        // SAFETY: the mutable reference guarantees unique ownership.
630        unsafe { &mut *(self.v.get() as *mut bool) }
631    }
632
633    /// Gets atomic access to a `&mut bool`.
634    ///
635    /// # Examples
636    ///
637    /// ```
638    /// #![feature(atomic_from_mut)]
639    /// use std::sync::atomic::{AtomicBool, Ordering};
640    ///
641    /// let mut some_bool = true;
642    /// let a = AtomicBool::from_mut(&mut some_bool);
643    /// a.store(false, Ordering::Relaxed);
644    /// assert_eq!(some_bool, false);
645    /// ```
646    #[inline]
647    #[cfg(target_has_atomic_equal_alignment = "8")]
648    #[unstable(feature = "atomic_from_mut", issue = "76314")]
649    #[cfg(not(feature = "ferrocene_subset"))]
650    pub fn from_mut(v: &mut bool) -> &mut Self {
651        // SAFETY: the mutable reference guarantees unique ownership, and
652        // alignment of both `bool` and `Self` is 1.
653        unsafe { &mut *(v as *mut bool as *mut Self) }
654    }
655
656    /// Gets non-atomic access to a `&mut [AtomicBool]` slice.
657    ///
658    /// This is safe because the mutable reference guarantees that no other threads are
659    /// concurrently accessing the atomic data.
660    ///
661    /// # Examples
662    ///
663    /// ```ignore-wasm
664    /// #![feature(atomic_from_mut)]
665    /// use std::sync::atomic::{AtomicBool, Ordering};
666    ///
667    /// let mut some_bools = [const { AtomicBool::new(false) }; 10];
668    ///
669    /// let view: &mut [bool] = AtomicBool::get_mut_slice(&mut some_bools);
670    /// assert_eq!(view, [false; 10]);
671    /// view[..5].copy_from_slice(&[true; 5]);
672    ///
673    /// std::thread::scope(|s| {
674    ///     for t in &some_bools[..5] {
675    ///         s.spawn(move || assert_eq!(t.load(Ordering::Relaxed), true));
676    ///     }
677    ///
678    ///     for f in &some_bools[5..] {
679    ///         s.spawn(move || assert_eq!(f.load(Ordering::Relaxed), false));
680    ///     }
681    /// });
682    /// ```
683    #[inline]
684    #[unstable(feature = "atomic_from_mut", issue = "76314")]
685    #[cfg(not(feature = "ferrocene_subset"))]
686    pub fn get_mut_slice(this: &mut [Self]) -> &mut [bool] {
687        // SAFETY: the mutable reference guarantees unique ownership.
688        unsafe { &mut *(this as *mut [Self] as *mut [bool]) }
689    }
690
691    /// Gets atomic access to a `&mut [bool]` slice.
692    ///
693    /// # Examples
694    ///
695    /// ```rust,ignore-wasm
696    /// #![feature(atomic_from_mut)]
697    /// use std::sync::atomic::{AtomicBool, Ordering};
698    ///
699    /// let mut some_bools = [false; 10];
700    /// let a = &*AtomicBool::from_mut_slice(&mut some_bools);
701    /// std::thread::scope(|s| {
702    ///     for i in 0..a.len() {
703    ///         s.spawn(move || a[i].store(true, Ordering::Relaxed));
704    ///     }
705    /// });
706    /// assert_eq!(some_bools, [true; 10]);
707    /// ```
708    #[inline]
709    #[cfg(target_has_atomic_equal_alignment = "8")]
710    #[unstable(feature = "atomic_from_mut", issue = "76314")]
711    #[cfg(not(feature = "ferrocene_subset"))]
712    pub fn from_mut_slice(v: &mut [bool]) -> &mut [Self] {
713        // SAFETY: the mutable reference guarantees unique ownership, and
714        // alignment of both `bool` and `Self` is 1.
715        unsafe { &mut *(v as *mut [bool] as *mut [Self]) }
716    }
717
718    /// Consumes the atomic and returns the contained value.
719    ///
720    /// This is safe because passing `self` by value guarantees that no other threads are
721    /// concurrently accessing the atomic data.
722    ///
723    /// # Examples
724    ///
725    /// ```
726    /// use std::sync::atomic::AtomicBool;
727    ///
728    /// let some_bool = AtomicBool::new(true);
729    /// assert_eq!(some_bool.into_inner(), true);
730    /// ```
731    #[inline]
732    #[stable(feature = "atomic_access", since = "1.15.0")]
733    #[rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0")]
734    #[cfg(not(feature = "ferrocene_subset"))]
735    pub const fn into_inner(self) -> bool {
736        self.v.into_inner() != 0
737    }
738
739    /// Loads a value from the bool.
740    ///
741    /// `load` takes an [`Ordering`] argument which describes the memory ordering
742    /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
743    ///
744    /// # Panics
745    ///
746    /// Panics if `order` is [`Release`] or [`AcqRel`].
747    ///
748    /// # Examples
749    ///
750    /// ```
751    /// use std::sync::atomic::{AtomicBool, Ordering};
752    ///
753    /// let some_bool = AtomicBool::new(true);
754    ///
755    /// assert_eq!(some_bool.load(Ordering::Relaxed), true);
756    /// ```
757    #[inline]
758    #[stable(feature = "rust1", since = "1.0.0")]
759    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
760    pub fn load(&self, order: Ordering) -> bool {
761        // SAFETY: any data races are prevented by atomic intrinsics and the raw
762        // pointer passed in is valid because we got it from a reference.
763        unsafe { atomic_load(self.v.get(), order) != 0 }
764    }
765
766    /// Stores a value into the bool.
767    ///
768    /// `store` takes an [`Ordering`] argument which describes the memory ordering
769    /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
770    ///
771    /// # Panics
772    ///
773    /// Panics if `order` is [`Acquire`] or [`AcqRel`].
774    ///
775    /// # Examples
776    ///
777    /// ```
778    /// use std::sync::atomic::{AtomicBool, Ordering};
779    ///
780    /// let some_bool = AtomicBool::new(true);
781    ///
782    /// some_bool.store(false, Ordering::Relaxed);
783    /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
784    /// ```
785    #[inline]
786    #[stable(feature = "rust1", since = "1.0.0")]
787    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
788    #[rustc_should_not_be_called_on_const_items]
789    pub fn store(&self, val: bool, order: Ordering) {
790        // SAFETY: any data races are prevented by atomic intrinsics and the raw
791        // pointer passed in is valid because we got it from a reference.
792        unsafe {
793            atomic_store(self.v.get(), val as u8, order);
794        }
795    }
796
797    /// Stores a value into the bool, returning the previous value.
798    ///
799    /// `swap` takes an [`Ordering`] argument which describes the memory ordering
800    /// of this operation. All ordering modes are possible. Note that using
801    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
802    /// using [`Release`] makes the load part [`Relaxed`].
803    ///
804    /// **Note:** This method is only available on platforms that support atomic
805    /// operations on `u8`.
806    ///
807    /// # Examples
808    ///
809    /// ```
810    /// use std::sync::atomic::{AtomicBool, Ordering};
811    ///
812    /// let some_bool = AtomicBool::new(true);
813    ///
814    /// assert_eq!(some_bool.swap(false, Ordering::Relaxed), true);
815    /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
816    /// ```
817    #[inline]
818    #[stable(feature = "rust1", since = "1.0.0")]
819    #[cfg(target_has_atomic = "8")]
820    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
821    #[rustc_should_not_be_called_on_const_items]
822    pub fn swap(&self, val: bool, order: Ordering) -> bool {
823        if EMULATE_ATOMIC_BOOL {
824            #[ferrocene::annotation(
825                "Cannot be covered as this code does not run in any of the platforms for which we track coverage"
826            )]
827            if val { self.fetch_or(true, order) } else { self.fetch_and(false, order) }
828        } else {
829            // SAFETY: data races are prevented by atomic intrinsics.
830            unsafe { atomic_swap(self.v.get(), val as u8, order) != 0 }
831        }
832    }
833
834    /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
835    ///
836    /// The return value is always the previous value. If it is equal to `current`, then the value
837    /// was updated.
838    ///
839    /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
840    /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
841    /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
842    /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
843    /// happens, and using [`Release`] makes the load part [`Relaxed`].
844    ///
845    /// **Note:** This method is only available on platforms that support atomic
846    /// operations on `u8`.
847    ///
848    /// # Migrating to `compare_exchange` and `compare_exchange_weak`
849    ///
850    /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
851    /// memory orderings:
852    ///
853    /// Original | Success | Failure
854    /// -------- | ------- | -------
855    /// Relaxed  | Relaxed | Relaxed
856    /// Acquire  | Acquire | Acquire
857    /// Release  | Release | Relaxed
858    /// AcqRel   | AcqRel  | Acquire
859    /// SeqCst   | SeqCst  | SeqCst
860    ///
861    /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
862    /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
863    /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
864    /// rather than to infer success vs failure based on the value that was read.
865    ///
866    /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
867    /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
868    /// which allows the compiler to generate better assembly code when the compare and swap
869    /// is used in a loop.
870    ///
871    /// # Examples
872    ///
873    /// ```
874    /// use std::sync::atomic::{AtomicBool, Ordering};
875    ///
876    /// let some_bool = AtomicBool::new(true);
877    ///
878    /// assert_eq!(some_bool.compare_and_swap(true, false, Ordering::Relaxed), true);
879    /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
880    ///
881    /// assert_eq!(some_bool.compare_and_swap(true, true, Ordering::Relaxed), false);
882    /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
883    /// ```
884    #[cfg(not(feature = "ferrocene_subset"))]
885    #[inline]
886    #[stable(feature = "rust1", since = "1.0.0")]
887    #[deprecated(
888        since = "1.50.0",
889        note = "Use `compare_exchange` or `compare_exchange_weak` instead"
890    )]
891    #[cfg(target_has_atomic = "8")]
892    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
893    #[rustc_should_not_be_called_on_const_items]
894    pub fn compare_and_swap(&self, current: bool, new: bool, order: Ordering) -> bool {
895        match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
896            Ok(x) => x,
897            Err(x) => x,
898        }
899    }
900
901    /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
902    ///
903    /// The return value is a result indicating whether the new value was written and containing
904    /// the previous value. On success this value is guaranteed to be equal to `current`.
905    ///
906    /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
907    /// ordering of this operation. `success` describes the required ordering for the
908    /// read-modify-write operation that takes place if the comparison with `current` succeeds.
909    /// `failure` describes the required ordering for the load operation that takes place when
910    /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
911    /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
912    /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
913    ///
914    /// **Note:** This method is only available on platforms that support atomic
915    /// operations on `u8`.
916    ///
917    /// # Examples
918    ///
919    /// ```
920    /// use std::sync::atomic::{AtomicBool, Ordering};
921    ///
922    /// let some_bool = AtomicBool::new(true);
923    ///
924    /// assert_eq!(some_bool.compare_exchange(true,
925    ///                                       false,
926    ///                                       Ordering::Acquire,
927    ///                                       Ordering::Relaxed),
928    ///            Ok(true));
929    /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
930    ///
931    /// assert_eq!(some_bool.compare_exchange(true, true,
932    ///                                       Ordering::SeqCst,
933    ///                                       Ordering::Acquire),
934    ///            Err(false));
935    /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
936    /// ```
937    ///
938    /// # Considerations
939    ///
940    /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
941    /// of CAS operations. In particular, a load of the value followed by a successful
942    /// `compare_exchange` with the previous load *does not ensure* that other threads have not
943    /// changed the value in the interim. This is usually important when the *equality* check in
944    /// the `compare_exchange` is being used to check the *identity* of a value, but equality
945    /// does not necessarily imply identity. In this case, `compare_exchange` can lead to the
946    /// [ABA problem].
947    ///
948    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
949    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
950    #[inline]
951    #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
952    #[doc(alias = "compare_and_swap")]
953    #[cfg(target_has_atomic = "8")]
954    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
955    #[rustc_should_not_be_called_on_const_items]
956    pub fn compare_exchange(
957        &self,
958        current: bool,
959        new: bool,
960        success: Ordering,
961        failure: Ordering,
962    ) -> Result<bool, bool> {
963        if EMULATE_ATOMIC_BOOL {
964            #[ferrocene::annotation(
965                "Cannot be covered as this code does not run in any of the platforms for which we track coverage"
966            )]
967            {
968                // Pick the strongest ordering from success and failure.
969                let order = match (success, failure) {
970                    (SeqCst, _) => SeqCst,
971                    (_, SeqCst) => SeqCst,
972                    (AcqRel, _) => AcqRel,
973                    (_, AcqRel) => {
974                        panic!("there is no such thing as an acquire-release failure ordering")
975                    }
976                    (Release, Acquire) => AcqRel,
977                    (Acquire, _) => Acquire,
978                    (_, Acquire) => Acquire,
979                    (Release, Relaxed) => Release,
980                    (_, Release) => panic!("there is no such thing as a release failure ordering"),
981                    (Relaxed, Relaxed) => Relaxed,
982                };
983                let old = if current == new {
984                    // This is a no-op, but we still need to perform the operation
985                    // for memory ordering reasons.
986                    self.fetch_or(false, order)
987                } else {
988                    // This sets the value to the new one and returns the old one.
989                    self.swap(new, order)
990                };
991                if old == current { Ok(old) } else { Err(old) }
992            }
993        } else {
994            // SAFETY: data races are prevented by atomic intrinsics.
995            match unsafe {
996                atomic_compare_exchange(self.v.get(), current as u8, new as u8, success, failure)
997            } {
998                Ok(x) => Ok(x != 0),
999                Err(x) => Err(x != 0),
1000            }
1001        }
1002    }
1003
1004    /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
1005    ///
1006    /// Unlike [`AtomicBool::compare_exchange`], this function is allowed to spuriously fail even when the
1007    /// comparison succeeds, which can result in more efficient code on some platforms. The
1008    /// return value is a result indicating whether the new value was written and containing the
1009    /// previous value.
1010    ///
1011    /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
1012    /// ordering of this operation. `success` describes the required ordering for the
1013    /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1014    /// `failure` describes the required ordering for the load operation that takes place when
1015    /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1016    /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1017    /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
1018    ///
1019    /// **Note:** This method is only available on platforms that support atomic
1020    /// operations on `u8`.
1021    ///
1022    /// # Examples
1023    ///
1024    /// ```
1025    /// use std::sync::atomic::{AtomicBool, Ordering};
1026    ///
1027    /// let val = AtomicBool::new(false);
1028    ///
1029    /// let new = true;
1030    /// let mut old = val.load(Ordering::Relaxed);
1031    /// loop {
1032    ///     match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
1033    ///         Ok(_) => break,
1034    ///         Err(x) => old = x,
1035    ///     }
1036    /// }
1037    /// ```
1038    ///
1039    /// # Considerations
1040    ///
1041    /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
1042    /// of CAS operations. In particular, a load of the value followed by a successful
1043    /// `compare_exchange` with the previous load *does not ensure* that other threads have not
1044    /// changed the value in the interim. This is usually important when the *equality* check in
1045    /// the `compare_exchange` is being used to check the *identity* of a value, but equality
1046    /// does not necessarily imply identity. In this case, `compare_exchange` can lead to the
1047    /// [ABA problem].
1048    ///
1049    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1050    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1051    #[inline]
1052    #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1053    #[doc(alias = "compare_and_swap")]
1054    #[cfg(target_has_atomic = "8")]
1055    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1056    #[cfg(not(feature = "ferrocene_subset"))]
1057    #[rustc_should_not_be_called_on_const_items]
1058    pub fn compare_exchange_weak(
1059        &self,
1060        current: bool,
1061        new: bool,
1062        success: Ordering,
1063        failure: Ordering,
1064    ) -> Result<bool, bool> {
1065        if EMULATE_ATOMIC_BOOL {
1066            return self.compare_exchange(current, new, success, failure);
1067        }
1068
1069        // SAFETY: data races are prevented by atomic intrinsics.
1070        match unsafe {
1071            atomic_compare_exchange_weak(self.v.get(), current as u8, new as u8, success, failure)
1072        } {
1073            Ok(x) => Ok(x != 0),
1074            Err(x) => Err(x != 0),
1075        }
1076    }
1077
1078    /// Logical "and" with a boolean value.
1079    ///
1080    /// Performs a logical "and" operation on the current value and the argument `val`, and sets
1081    /// the new value to the result.
1082    ///
1083    /// Returns the previous value.
1084    ///
1085    /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
1086    /// of this operation. All ordering modes are possible. Note that using
1087    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1088    /// using [`Release`] makes the load part [`Relaxed`].
1089    ///
1090    /// **Note:** This method is only available on platforms that support atomic
1091    /// operations on `u8`.
1092    ///
1093    /// # Examples
1094    ///
1095    /// ```
1096    /// use std::sync::atomic::{AtomicBool, Ordering};
1097    ///
1098    /// let foo = AtomicBool::new(true);
1099    /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), true);
1100    /// assert_eq!(foo.load(Ordering::SeqCst), false);
1101    ///
1102    /// let foo = AtomicBool::new(true);
1103    /// assert_eq!(foo.fetch_and(true, Ordering::SeqCst), true);
1104    /// assert_eq!(foo.load(Ordering::SeqCst), true);
1105    ///
1106    /// let foo = AtomicBool::new(false);
1107    /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), false);
1108    /// assert_eq!(foo.load(Ordering::SeqCst), false);
1109    /// ```
1110    #[inline]
1111    #[stable(feature = "rust1", since = "1.0.0")]
1112    #[cfg(target_has_atomic = "8")]
1113    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1114    #[rustc_should_not_be_called_on_const_items]
1115    pub fn fetch_and(&self, val: bool, order: Ordering) -> bool {
1116        // SAFETY: data races are prevented by atomic intrinsics.
1117        unsafe { atomic_and(self.v.get(), val as u8, order) != 0 }
1118    }
1119
1120    /// Logical "nand" with a boolean value.
1121    ///
1122    /// Performs a logical "nand" operation on the current value and the argument `val`, and sets
1123    /// the new value to the result.
1124    ///
1125    /// Returns the previous value.
1126    ///
1127    /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
1128    /// of this operation. All ordering modes are possible. Note that using
1129    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1130    /// using [`Release`] makes the load part [`Relaxed`].
1131    ///
1132    /// **Note:** This method is only available on platforms that support atomic
1133    /// operations on `u8`.
1134    ///
1135    /// # Examples
1136    ///
1137    /// ```
1138    /// use std::sync::atomic::{AtomicBool, Ordering};
1139    ///
1140    /// let foo = AtomicBool::new(true);
1141    /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), true);
1142    /// assert_eq!(foo.load(Ordering::SeqCst), true);
1143    ///
1144    /// let foo = AtomicBool::new(true);
1145    /// assert_eq!(foo.fetch_nand(true, Ordering::SeqCst), true);
1146    /// assert_eq!(foo.load(Ordering::SeqCst) as usize, 0);
1147    /// assert_eq!(foo.load(Ordering::SeqCst), false);
1148    ///
1149    /// let foo = AtomicBool::new(false);
1150    /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), false);
1151    /// assert_eq!(foo.load(Ordering::SeqCst), true);
1152    /// ```
1153    #[inline]
1154    #[stable(feature = "rust1", since = "1.0.0")]
1155    #[cfg(target_has_atomic = "8")]
1156    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1157    #[cfg(not(feature = "ferrocene_subset"))]
1158    #[rustc_should_not_be_called_on_const_items]
1159    pub fn fetch_nand(&self, val: bool, order: Ordering) -> bool {
1160        // We can't use atomic_nand here because it can result in a bool with
1161        // an invalid value. This happens because the atomic operation is done
1162        // with an 8-bit integer internally, which would set the upper 7 bits.
1163        // So we just use fetch_xor or swap instead.
1164        if val {
1165            // !(x & true) == !x
1166            // We must invert the bool.
1167            self.fetch_xor(true, order)
1168        } else {
1169            // !(x & false) == true
1170            // We must set the bool to true.
1171            self.swap(true, order)
1172        }
1173    }
1174
1175    /// Logical "or" with a boolean value.
1176    ///
1177    /// Performs a logical "or" operation on the current value and the argument `val`, and sets the
1178    /// new value to the result.
1179    ///
1180    /// Returns the previous value.
1181    ///
1182    /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
1183    /// of this operation. All ordering modes are possible. Note that using
1184    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1185    /// using [`Release`] makes the load part [`Relaxed`].
1186    ///
1187    /// **Note:** This method is only available on platforms that support atomic
1188    /// operations on `u8`.
1189    ///
1190    /// # Examples
1191    ///
1192    /// ```
1193    /// use std::sync::atomic::{AtomicBool, Ordering};
1194    ///
1195    /// let foo = AtomicBool::new(true);
1196    /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), true);
1197    /// assert_eq!(foo.load(Ordering::SeqCst), true);
1198    ///
1199    /// let foo = AtomicBool::new(true);
1200    /// assert_eq!(foo.fetch_or(true, Ordering::SeqCst), true);
1201    /// assert_eq!(foo.load(Ordering::SeqCst), true);
1202    ///
1203    /// let foo = AtomicBool::new(false);
1204    /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), false);
1205    /// assert_eq!(foo.load(Ordering::SeqCst), false);
1206    /// ```
1207    #[inline]
1208    #[stable(feature = "rust1", since = "1.0.0")]
1209    #[cfg(target_has_atomic = "8")]
1210    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1211    #[rustc_should_not_be_called_on_const_items]
1212    pub fn fetch_or(&self, val: bool, order: Ordering) -> bool {
1213        // SAFETY: data races are prevented by atomic intrinsics.
1214        unsafe { atomic_or(self.v.get(), val as u8, order) != 0 }
1215    }
1216
1217    /// Logical "xor" with a boolean value.
1218    ///
1219    /// Performs a logical "xor" operation on the current value and the argument `val`, and sets
1220    /// the new value to the result.
1221    ///
1222    /// Returns the previous value.
1223    ///
1224    /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
1225    /// of this operation. All ordering modes are possible. Note that using
1226    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1227    /// using [`Release`] makes the load part [`Relaxed`].
1228    ///
1229    /// **Note:** This method is only available on platforms that support atomic
1230    /// operations on `u8`.
1231    ///
1232    /// # Examples
1233    ///
1234    /// ```
1235    /// use std::sync::atomic::{AtomicBool, Ordering};
1236    ///
1237    /// let foo = AtomicBool::new(true);
1238    /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), true);
1239    /// assert_eq!(foo.load(Ordering::SeqCst), true);
1240    ///
1241    /// let foo = AtomicBool::new(true);
1242    /// assert_eq!(foo.fetch_xor(true, Ordering::SeqCst), true);
1243    /// assert_eq!(foo.load(Ordering::SeqCst), false);
1244    ///
1245    /// let foo = AtomicBool::new(false);
1246    /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), false);
1247    /// assert_eq!(foo.load(Ordering::SeqCst), false);
1248    /// ```
1249    #[inline]
1250    #[stable(feature = "rust1", since = "1.0.0")]
1251    #[cfg(target_has_atomic = "8")]
1252    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1253    #[cfg(not(feature = "ferrocene_subset"))]
1254    #[rustc_should_not_be_called_on_const_items]
1255    pub fn fetch_xor(&self, val: bool, order: Ordering) -> bool {
1256        // SAFETY: data races are prevented by atomic intrinsics.
1257        unsafe { atomic_xor(self.v.get(), val as u8, order) != 0 }
1258    }
1259
1260    /// Logical "not" with a boolean value.
1261    ///
1262    /// Performs a logical "not" operation on the current value, and sets
1263    /// the new value to the result.
1264    ///
1265    /// Returns the previous value.
1266    ///
1267    /// `fetch_not` takes an [`Ordering`] argument which describes the memory ordering
1268    /// of this operation. All ordering modes are possible. Note that using
1269    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1270    /// using [`Release`] makes the load part [`Relaxed`].
1271    ///
1272    /// **Note:** This method is only available on platforms that support atomic
1273    /// operations on `u8`.
1274    ///
1275    /// # Examples
1276    ///
1277    /// ```
1278    /// use std::sync::atomic::{AtomicBool, Ordering};
1279    ///
1280    /// let foo = AtomicBool::new(true);
1281    /// assert_eq!(foo.fetch_not(Ordering::SeqCst), true);
1282    /// assert_eq!(foo.load(Ordering::SeqCst), false);
1283    ///
1284    /// let foo = AtomicBool::new(false);
1285    /// assert_eq!(foo.fetch_not(Ordering::SeqCst), false);
1286    /// assert_eq!(foo.load(Ordering::SeqCst), true);
1287    /// ```
1288    #[inline]
1289    #[stable(feature = "atomic_bool_fetch_not", since = "1.81.0")]
1290    #[cfg(target_has_atomic = "8")]
1291    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1292    #[cfg(not(feature = "ferrocene_subset"))]
1293    #[rustc_should_not_be_called_on_const_items]
1294    pub fn fetch_not(&self, order: Ordering) -> bool {
1295        self.fetch_xor(true, order)
1296    }
1297
1298    /// Returns a mutable pointer to the underlying [`bool`].
1299    ///
1300    /// Doing non-atomic reads and writes on the resulting boolean can be a data race.
1301    /// This method is mostly useful for FFI, where the function signature may use
1302    /// `*mut bool` instead of `&AtomicBool`.
1303    ///
1304    /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
1305    /// atomic types work with interior mutability. All modifications of an atomic change the value
1306    /// through a shared reference, and can do so safely as long as they use atomic operations. Any
1307    /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
1308    /// requirements of the [memory model].
1309    ///
1310    /// # Examples
1311    ///
1312    /// ```ignore (extern-declaration)
1313    /// # fn main() {
1314    /// use std::sync::atomic::AtomicBool;
1315    ///
1316    /// extern "C" {
1317    ///     fn my_atomic_op(arg: *mut bool);
1318    /// }
1319    ///
1320    /// let mut atomic = AtomicBool::new(true);
1321    /// unsafe {
1322    ///     my_atomic_op(atomic.as_ptr());
1323    /// }
1324    /// # }
1325    /// ```
1326    ///
1327    /// [memory model]: self#memory-model-for-atomic-accesses
1328    #[inline]
1329    #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
1330    #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
1331    #[rustc_never_returns_null_ptr]
1332    #[cfg(not(feature = "ferrocene_subset"))]
1333    #[rustc_should_not_be_called_on_const_items]
1334    pub const fn as_ptr(&self) -> *mut bool {
1335        self.v.get().cast()
1336    }
1337
1338    /// Fetches the value, and applies a function to it that returns an optional
1339    /// new value. Returns a `Result` of `Ok(previous_value)` if the function
1340    /// returned `Some(_)`, else `Err(previous_value)`.
1341    ///
1342    /// Note: This may call the function multiple times if the value has been
1343    /// changed from other threads in the meantime, as long as the function
1344    /// returns `Some(_)`, but the function will have been applied only once to
1345    /// the stored value.
1346    ///
1347    /// `fetch_update` takes two [`Ordering`] arguments to describe the memory
1348    /// ordering of this operation. The first describes the required ordering for
1349    /// when the operation finally succeeds while the second describes the
1350    /// required ordering for loads. These correspond to the success and failure
1351    /// orderings of [`AtomicBool::compare_exchange`] respectively.
1352    ///
1353    /// Using [`Acquire`] as success ordering makes the store part of this
1354    /// operation [`Relaxed`], and using [`Release`] makes the final successful
1355    /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
1356    /// [`Acquire`] or [`Relaxed`].
1357    ///
1358    /// **Note:** This method is only available on platforms that support atomic
1359    /// operations on `u8`.
1360    ///
1361    /// # Considerations
1362    ///
1363    /// This method is not magic; it is not provided by the hardware, and does not act like a
1364    /// critical section or mutex.
1365    ///
1366    /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
1367    /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem].
1368    ///
1369    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1370    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1371    ///
1372    /// # Examples
1373    ///
1374    /// ```rust
1375    /// use std::sync::atomic::{AtomicBool, Ordering};
1376    ///
1377    /// let x = AtomicBool::new(false);
1378    /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(false));
1379    /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(false));
1380    /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(true));
1381    /// assert_eq!(x.load(Ordering::SeqCst), false);
1382    /// ```
1383    #[inline]
1384    #[stable(feature = "atomic_fetch_update", since = "1.53.0")]
1385    #[cfg(target_has_atomic = "8")]
1386    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1387    #[cfg(not(feature = "ferrocene_subset"))]
1388    #[rustc_should_not_be_called_on_const_items]
1389    pub fn fetch_update<F>(
1390        &self,
1391        set_order: Ordering,
1392        fetch_order: Ordering,
1393        mut f: F,
1394    ) -> Result<bool, bool>
1395    where
1396        F: FnMut(bool) -> Option<bool>,
1397    {
1398        let mut prev = self.load(fetch_order);
1399        while let Some(next) = f(prev) {
1400            match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
1401                x @ Ok(_) => return x,
1402                Err(next_prev) => prev = next_prev,
1403            }
1404        }
1405        Err(prev)
1406    }
1407
1408    /// Fetches the value, and applies a function to it that returns an optional
1409    /// new value. Returns a `Result` of `Ok(previous_value)` if the function
1410    /// returned `Some(_)`, else `Err(previous_value)`.
1411    ///
1412    /// See also: [`update`](`AtomicBool::update`).
1413    ///
1414    /// Note: This may call the function multiple times if the value has been
1415    /// changed from other threads in the meantime, as long as the function
1416    /// returns `Some(_)`, but the function will have been applied only once to
1417    /// the stored value.
1418    ///
1419    /// `try_update` takes two [`Ordering`] arguments to describe the memory
1420    /// ordering of this operation. The first describes the required ordering for
1421    /// when the operation finally succeeds while the second describes the
1422    /// required ordering for loads. These correspond to the success and failure
1423    /// orderings of [`AtomicBool::compare_exchange`] respectively.
1424    ///
1425    /// Using [`Acquire`] as success ordering makes the store part of this
1426    /// operation [`Relaxed`], and using [`Release`] makes the final successful
1427    /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
1428    /// [`Acquire`] or [`Relaxed`].
1429    ///
1430    /// **Note:** This method is only available on platforms that support atomic
1431    /// operations on `u8`.
1432    ///
1433    /// # Considerations
1434    ///
1435    /// This method is not magic; it is not provided by the hardware, and does not act like a
1436    /// critical section or mutex.
1437    ///
1438    /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
1439    /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem].
1440    ///
1441    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1442    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1443    ///
1444    /// # Examples
1445    ///
1446    /// ```rust
1447    /// #![feature(atomic_try_update)]
1448    /// use std::sync::atomic::{AtomicBool, Ordering};
1449    ///
1450    /// let x = AtomicBool::new(false);
1451    /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(false));
1452    /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(false));
1453    /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(true));
1454    /// assert_eq!(x.load(Ordering::SeqCst), false);
1455    /// ```
1456    #[inline]
1457    #[unstable(feature = "atomic_try_update", issue = "135894")]
1458    #[cfg(target_has_atomic = "8")]
1459    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1460    #[cfg(not(feature = "ferrocene_subset"))]
1461    #[rustc_should_not_be_called_on_const_items]
1462    pub fn try_update(
1463        &self,
1464        set_order: Ordering,
1465        fetch_order: Ordering,
1466        f: impl FnMut(bool) -> Option<bool>,
1467    ) -> Result<bool, bool> {
1468        // FIXME(atomic_try_update): this is currently an unstable alias to `fetch_update`;
1469        //      when stabilizing, turn `fetch_update` into a deprecated alias to `try_update`.
1470        self.fetch_update(set_order, fetch_order, f)
1471    }
1472
1473    /// Fetches the value, applies a function to it that it return a new value.
1474    /// The new value is stored and the old value is returned.
1475    ///
1476    /// See also: [`try_update`](`AtomicBool::try_update`).
1477    ///
1478    /// Note: This may call the function multiple times if the value has been changed from other threads in
1479    /// the meantime, but the function will have been applied only once to the stored value.
1480    ///
1481    /// `update` takes two [`Ordering`] arguments to describe the memory
1482    /// ordering of this operation. The first describes the required ordering for
1483    /// when the operation finally succeeds while the second describes the
1484    /// required ordering for loads. These correspond to the success and failure
1485    /// orderings of [`AtomicBool::compare_exchange`] respectively.
1486    ///
1487    /// Using [`Acquire`] as success ordering makes the store part
1488    /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
1489    /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
1490    ///
1491    /// **Note:** This method is only available on platforms that support atomic operations on `u8`.
1492    ///
1493    /// # Considerations
1494    ///
1495    /// This method is not magic; it is not provided by the hardware, and does not act like a
1496    /// critical section or mutex.
1497    ///
1498    /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
1499    /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem].
1500    ///
1501    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1502    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1503    ///
1504    /// # Examples
1505    ///
1506    /// ```rust
1507    /// #![feature(atomic_try_update)]
1508    ///
1509    /// use std::sync::atomic::{AtomicBool, Ordering};
1510    ///
1511    /// let x = AtomicBool::new(false);
1512    /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| !x), false);
1513    /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| !x), true);
1514    /// assert_eq!(x.load(Ordering::SeqCst), false);
1515    /// ```
1516    #[inline]
1517    #[unstable(feature = "atomic_try_update", issue = "135894")]
1518    #[cfg(target_has_atomic = "8")]
1519    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1520    #[cfg(not(feature = "ferrocene_subset"))]
1521    #[rustc_should_not_be_called_on_const_items]
1522    pub fn update(
1523        &self,
1524        set_order: Ordering,
1525        fetch_order: Ordering,
1526        mut f: impl FnMut(bool) -> bool,
1527    ) -> bool {
1528        let mut prev = self.load(fetch_order);
1529        loop {
1530            match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
1531                Ok(x) => break x,
1532                Err(next_prev) => prev = next_prev,
1533            }
1534        }
1535    }
1536}
1537
1538#[cfg(target_has_atomic_load_store = "ptr")]
1539#[cfg(not(feature = "ferrocene_subset"))]
1540impl<T> AtomicPtr<T> {
1541    /// Creates a new `AtomicPtr`.
1542    ///
1543    /// # Examples
1544    ///
1545    /// ```
1546    /// use std::sync::atomic::AtomicPtr;
1547    ///
1548    /// let ptr = &mut 5;
1549    /// let atomic_ptr = AtomicPtr::new(ptr);
1550    /// ```
1551    #[inline]
1552    #[stable(feature = "rust1", since = "1.0.0")]
1553    #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")]
1554    pub const fn new(p: *mut T) -> AtomicPtr<T> {
1555        AtomicPtr { p: UnsafeCell::new(p) }
1556    }
1557
1558    /// Creates a new `AtomicPtr` from a pointer.
1559    ///
1560    /// # Examples
1561    ///
1562    /// ```
1563    /// use std::sync::atomic::{self, AtomicPtr};
1564    ///
1565    /// // Get a pointer to an allocated value
1566    /// let ptr: *mut *mut u8 = Box::into_raw(Box::new(std::ptr::null_mut()));
1567    ///
1568    /// assert!(ptr.cast::<AtomicPtr<u8>>().is_aligned());
1569    ///
1570    /// {
1571    ///     // Create an atomic view of the allocated value
1572    ///     let atomic = unsafe { AtomicPtr::from_ptr(ptr) };
1573    ///
1574    ///     // Use `atomic` for atomic operations, possibly share it with other threads
1575    ///     atomic.store(std::ptr::NonNull::dangling().as_ptr(), atomic::Ordering::Relaxed);
1576    /// }
1577    ///
1578    /// // It's ok to non-atomically access the value behind `ptr`,
1579    /// // since the reference to the atomic ended its lifetime in the block above
1580    /// assert!(!unsafe { *ptr }.is_null());
1581    ///
1582    /// // Deallocate the value
1583    /// unsafe { drop(Box::from_raw(ptr)) }
1584    /// ```
1585    ///
1586    /// # Safety
1587    ///
1588    /// * `ptr` must be aligned to `align_of::<AtomicPtr<T>>()` (note that on some platforms this
1589    ///   can be bigger than `align_of::<*mut T>()`).
1590    /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
1591    /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
1592    ///   allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
1593    ///   sizes, without synchronization.
1594    ///
1595    /// [valid]: crate::ptr#safety
1596    /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
1597    #[inline]
1598    #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
1599    #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
1600    pub const unsafe fn from_ptr<'a>(ptr: *mut *mut T) -> &'a AtomicPtr<T> {
1601        // SAFETY: guaranteed by the caller
1602        unsafe { &*ptr.cast() }
1603    }
1604
1605    /// Returns a mutable reference to the underlying pointer.
1606    ///
1607    /// This is safe because the mutable reference guarantees that no other threads are
1608    /// concurrently accessing the atomic data.
1609    ///
1610    /// # Examples
1611    ///
1612    /// ```
1613    /// use std::sync::atomic::{AtomicPtr, Ordering};
1614    ///
1615    /// let mut data = 10;
1616    /// let mut atomic_ptr = AtomicPtr::new(&mut data);
1617    /// let mut other_data = 5;
1618    /// *atomic_ptr.get_mut() = &mut other_data;
1619    /// assert_eq!(unsafe { *atomic_ptr.load(Ordering::SeqCst) }, 5);
1620    /// ```
1621    #[inline]
1622    #[stable(feature = "atomic_access", since = "1.15.0")]
1623    pub fn get_mut(&mut self) -> &mut *mut T {
1624        self.p.get_mut()
1625    }
1626
1627    /// Gets atomic access to a pointer.
1628    ///
1629    /// **Note:** This function is only available on targets where `AtomicPtr<T>` has the same alignment as `*const T`
1630    ///
1631    /// # Examples
1632    ///
1633    /// ```
1634    /// #![feature(atomic_from_mut)]
1635    /// use std::sync::atomic::{AtomicPtr, Ordering};
1636    ///
1637    /// let mut data = 123;
1638    /// let mut some_ptr = &mut data as *mut i32;
1639    /// let a = AtomicPtr::from_mut(&mut some_ptr);
1640    /// let mut other_data = 456;
1641    /// a.store(&mut other_data, Ordering::Relaxed);
1642    /// assert_eq!(unsafe { *some_ptr }, 456);
1643    /// ```
1644    #[inline]
1645    #[cfg(target_has_atomic_equal_alignment = "ptr")]
1646    #[unstable(feature = "atomic_from_mut", issue = "76314")]
1647    pub fn from_mut(v: &mut *mut T) -> &mut Self {
1648        let [] = [(); align_of::<AtomicPtr<()>>() - align_of::<*mut ()>()];
1649        // SAFETY:
1650        //  - the mutable reference guarantees unique ownership.
1651        //  - the alignment of `*mut T` and `Self` is the same on all platforms
1652        //    supported by rust, as verified above.
1653        unsafe { &mut *(v as *mut *mut T as *mut Self) }
1654    }
1655
1656    /// Gets non-atomic access to a `&mut [AtomicPtr]` slice.
1657    ///
1658    /// This is safe because the mutable reference guarantees that no other threads are
1659    /// concurrently accessing the atomic data.
1660    ///
1661    /// # Examples
1662    ///
1663    /// ```ignore-wasm
1664    /// #![feature(atomic_from_mut)]
1665    /// use std::ptr::null_mut;
1666    /// use std::sync::atomic::{AtomicPtr, Ordering};
1667    ///
1668    /// let mut some_ptrs = [const { AtomicPtr::new(null_mut::<String>()) }; 10];
1669    ///
1670    /// let view: &mut [*mut String] = AtomicPtr::get_mut_slice(&mut some_ptrs);
1671    /// assert_eq!(view, [null_mut::<String>(); 10]);
1672    /// view
1673    ///     .iter_mut()
1674    ///     .enumerate()
1675    ///     .for_each(|(i, ptr)| *ptr = Box::into_raw(Box::new(format!("iteration#{i}"))));
1676    ///
1677    /// std::thread::scope(|s| {
1678    ///     for ptr in &some_ptrs {
1679    ///         s.spawn(move || {
1680    ///             let ptr = ptr.load(Ordering::Relaxed);
1681    ///             assert!(!ptr.is_null());
1682    ///
1683    ///             let name = unsafe { Box::from_raw(ptr) };
1684    ///             println!("Hello, {name}!");
1685    ///         });
1686    ///     }
1687    /// });
1688    /// ```
1689    #[inline]
1690    #[unstable(feature = "atomic_from_mut", issue = "76314")]
1691    pub fn get_mut_slice(this: &mut [Self]) -> &mut [*mut T] {
1692        // SAFETY: the mutable reference guarantees unique ownership.
1693        unsafe { &mut *(this as *mut [Self] as *mut [*mut T]) }
1694    }
1695
1696    /// Gets atomic access to a slice of pointers.
1697    ///
1698    /// **Note:** This function is only available on targets where `AtomicPtr<T>` has the same alignment as `*const T`
1699    ///
1700    /// # Examples
1701    ///
1702    /// ```ignore-wasm
1703    /// #![feature(atomic_from_mut)]
1704    /// use std::ptr::null_mut;
1705    /// use std::sync::atomic::{AtomicPtr, Ordering};
1706    ///
1707    /// let mut some_ptrs = [null_mut::<String>(); 10];
1708    /// let a = &*AtomicPtr::from_mut_slice(&mut some_ptrs);
1709    /// std::thread::scope(|s| {
1710    ///     for i in 0..a.len() {
1711    ///         s.spawn(move || {
1712    ///             let name = Box::new(format!("thread{i}"));
1713    ///             a[i].store(Box::into_raw(name), Ordering::Relaxed);
1714    ///         });
1715    ///     }
1716    /// });
1717    /// for p in some_ptrs {
1718    ///     assert!(!p.is_null());
1719    ///     let name = unsafe { Box::from_raw(p) };
1720    ///     println!("Hello, {name}!");
1721    /// }
1722    /// ```
1723    #[inline]
1724    #[cfg(target_has_atomic_equal_alignment = "ptr")]
1725    #[unstable(feature = "atomic_from_mut", issue = "76314")]
1726    pub fn from_mut_slice(v: &mut [*mut T]) -> &mut [Self] {
1727        // SAFETY:
1728        //  - the mutable reference guarantees unique ownership.
1729        //  - the alignment of `*mut T` and `Self` is the same on all platforms
1730        //    supported by rust, as verified above.
1731        unsafe { &mut *(v as *mut [*mut T] as *mut [Self]) }
1732    }
1733
1734    /// Consumes the atomic and returns the contained value.
1735    ///
1736    /// This is safe because passing `self` by value guarantees that no other threads are
1737    /// concurrently accessing the atomic data.
1738    ///
1739    /// # Examples
1740    ///
1741    /// ```
1742    /// use std::sync::atomic::AtomicPtr;
1743    ///
1744    /// let mut data = 5;
1745    /// let atomic_ptr = AtomicPtr::new(&mut data);
1746    /// assert_eq!(unsafe { *atomic_ptr.into_inner() }, 5);
1747    /// ```
1748    #[inline]
1749    #[stable(feature = "atomic_access", since = "1.15.0")]
1750    #[rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0")]
1751    pub const fn into_inner(self) -> *mut T {
1752        self.p.into_inner()
1753    }
1754
1755    /// Loads a value from the pointer.
1756    ///
1757    /// `load` takes an [`Ordering`] argument which describes the memory ordering
1758    /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
1759    ///
1760    /// # Panics
1761    ///
1762    /// Panics if `order` is [`Release`] or [`AcqRel`].
1763    ///
1764    /// # Examples
1765    ///
1766    /// ```
1767    /// use std::sync::atomic::{AtomicPtr, Ordering};
1768    ///
1769    /// let ptr = &mut 5;
1770    /// let some_ptr = AtomicPtr::new(ptr);
1771    ///
1772    /// let value = some_ptr.load(Ordering::Relaxed);
1773    /// ```
1774    #[inline]
1775    #[stable(feature = "rust1", since = "1.0.0")]
1776    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1777    pub fn load(&self, order: Ordering) -> *mut T {
1778        // SAFETY: data races are prevented by atomic intrinsics.
1779        unsafe { atomic_load(self.p.get(), order) }
1780    }
1781
1782    /// Stores a value into the pointer.
1783    ///
1784    /// `store` takes an [`Ordering`] argument which describes the memory ordering
1785    /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
1786    ///
1787    /// # Panics
1788    ///
1789    /// Panics if `order` is [`Acquire`] or [`AcqRel`].
1790    ///
1791    /// # Examples
1792    ///
1793    /// ```
1794    /// use std::sync::atomic::{AtomicPtr, Ordering};
1795    ///
1796    /// let ptr = &mut 5;
1797    /// let some_ptr = AtomicPtr::new(ptr);
1798    ///
1799    /// let other_ptr = &mut 10;
1800    ///
1801    /// some_ptr.store(other_ptr, Ordering::Relaxed);
1802    /// ```
1803    #[inline]
1804    #[stable(feature = "rust1", since = "1.0.0")]
1805    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1806    #[rustc_should_not_be_called_on_const_items]
1807    pub fn store(&self, ptr: *mut T, order: Ordering) {
1808        // SAFETY: data races are prevented by atomic intrinsics.
1809        unsafe {
1810            atomic_store(self.p.get(), ptr, order);
1811        }
1812    }
1813
1814    /// Stores a value into the pointer, returning the previous value.
1815    ///
1816    /// `swap` takes an [`Ordering`] argument which describes the memory ordering
1817    /// of this operation. All ordering modes are possible. Note that using
1818    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1819    /// using [`Release`] makes the load part [`Relaxed`].
1820    ///
1821    /// **Note:** This method is only available on platforms that support atomic
1822    /// operations on pointers.
1823    ///
1824    /// # Examples
1825    ///
1826    /// ```
1827    /// use std::sync::atomic::{AtomicPtr, Ordering};
1828    ///
1829    /// let ptr = &mut 5;
1830    /// let some_ptr = AtomicPtr::new(ptr);
1831    ///
1832    /// let other_ptr = &mut 10;
1833    ///
1834    /// let value = some_ptr.swap(other_ptr, Ordering::Relaxed);
1835    /// ```
1836    #[inline]
1837    #[stable(feature = "rust1", since = "1.0.0")]
1838    #[cfg(target_has_atomic = "ptr")]
1839    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1840    #[rustc_should_not_be_called_on_const_items]
1841    pub fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T {
1842        // SAFETY: data races are prevented by atomic intrinsics.
1843        unsafe { atomic_swap(self.p.get(), ptr, order) }
1844    }
1845
1846    /// Stores a value into the pointer if the current value is the same as the `current` value.
1847    ///
1848    /// The return value is always the previous value. If it is equal to `current`, then the value
1849    /// was updated.
1850    ///
1851    /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
1852    /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
1853    /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
1854    /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
1855    /// happens, and using [`Release`] makes the load part [`Relaxed`].
1856    ///
1857    /// **Note:** This method is only available on platforms that support atomic
1858    /// operations on pointers.
1859    ///
1860    /// # Migrating to `compare_exchange` and `compare_exchange_weak`
1861    ///
1862    /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
1863    /// memory orderings:
1864    ///
1865    /// Original | Success | Failure
1866    /// -------- | ------- | -------
1867    /// Relaxed  | Relaxed | Relaxed
1868    /// Acquire  | Acquire | Acquire
1869    /// Release  | Release | Relaxed
1870    /// AcqRel   | AcqRel  | Acquire
1871    /// SeqCst   | SeqCst  | SeqCst
1872    ///
1873    /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
1874    /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
1875    /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
1876    /// rather than to infer success vs failure based on the value that was read.
1877    ///
1878    /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
1879    /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
1880    /// which allows the compiler to generate better assembly code when the compare and swap
1881    /// is used in a loop.
1882    ///
1883    /// # Examples
1884    ///
1885    /// ```
1886    /// use std::sync::atomic::{AtomicPtr, Ordering};
1887    ///
1888    /// let ptr = &mut 5;
1889    /// let some_ptr = AtomicPtr::new(ptr);
1890    ///
1891    /// let other_ptr = &mut 10;
1892    ///
1893    /// let value = some_ptr.compare_and_swap(ptr, other_ptr, Ordering::Relaxed);
1894    /// ```
1895    #[inline]
1896    #[stable(feature = "rust1", since = "1.0.0")]
1897    #[deprecated(
1898        since = "1.50.0",
1899        note = "Use `compare_exchange` or `compare_exchange_weak` instead"
1900    )]
1901    #[cfg(target_has_atomic = "ptr")]
1902    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1903    #[rustc_should_not_be_called_on_const_items]
1904    pub fn compare_and_swap(&self, current: *mut T, new: *mut T, order: Ordering) -> *mut T {
1905        match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
1906            Ok(x) => x,
1907            Err(x) => x,
1908        }
1909    }
1910
1911    /// Stores a value into the pointer if the current value is the same as the `current` value.
1912    ///
1913    /// The return value is a result indicating whether the new value was written and containing
1914    /// the previous value. On success this value is guaranteed to be equal to `current`.
1915    ///
1916    /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
1917    /// ordering of this operation. `success` describes the required ordering for the
1918    /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1919    /// `failure` describes the required ordering for the load operation that takes place when
1920    /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1921    /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1922    /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
1923    ///
1924    /// **Note:** This method is only available on platforms that support atomic
1925    /// operations on pointers.
1926    ///
1927    /// # Examples
1928    ///
1929    /// ```
1930    /// use std::sync::atomic::{AtomicPtr, Ordering};
1931    ///
1932    /// let ptr = &mut 5;
1933    /// let some_ptr = AtomicPtr::new(ptr);
1934    ///
1935    /// let other_ptr = &mut 10;
1936    ///
1937    /// let value = some_ptr.compare_exchange(ptr, other_ptr,
1938    ///                                       Ordering::SeqCst, Ordering::Relaxed);
1939    /// ```
1940    ///
1941    /// # Considerations
1942    ///
1943    /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
1944    /// of CAS operations. In particular, a load of the value followed by a successful
1945    /// `compare_exchange` with the previous load *does not ensure* that other threads have not
1946    /// changed the value in the interim. This is usually important when the *equality* check in
1947    /// the `compare_exchange` is being used to check the *identity* of a value, but equality
1948    /// does not necessarily imply identity. This is a particularly common case for pointers, as
1949    /// a pointer holding the same address does not imply that the same object exists at that
1950    /// address! In this case, `compare_exchange` can lead to the [ABA problem].
1951    ///
1952    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1953    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1954    #[inline]
1955    #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1956    #[cfg(target_has_atomic = "ptr")]
1957    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1958    #[rustc_should_not_be_called_on_const_items]
1959    pub fn compare_exchange(
1960        &self,
1961        current: *mut T,
1962        new: *mut T,
1963        success: Ordering,
1964        failure: Ordering,
1965    ) -> Result<*mut T, *mut T> {
1966        // SAFETY: data races are prevented by atomic intrinsics.
1967        unsafe { atomic_compare_exchange(self.p.get(), current, new, success, failure) }
1968    }
1969
1970    /// Stores a value into the pointer if the current value is the same as the `current` value.
1971    ///
1972    /// Unlike [`AtomicPtr::compare_exchange`], this function is allowed to spuriously fail even when the
1973    /// comparison succeeds, which can result in more efficient code on some platforms. The
1974    /// return value is a result indicating whether the new value was written and containing the
1975    /// previous value.
1976    ///
1977    /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
1978    /// ordering of this operation. `success` describes the required ordering for the
1979    /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1980    /// `failure` describes the required ordering for the load operation that takes place when
1981    /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1982    /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1983    /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
1984    ///
1985    /// **Note:** This method is only available on platforms that support atomic
1986    /// operations on pointers.
1987    ///
1988    /// # Examples
1989    ///
1990    /// ```
1991    /// use std::sync::atomic::{AtomicPtr, Ordering};
1992    ///
1993    /// let some_ptr = AtomicPtr::new(&mut 5);
1994    ///
1995    /// let new = &mut 10;
1996    /// let mut old = some_ptr.load(Ordering::Relaxed);
1997    /// loop {
1998    ///     match some_ptr.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
1999    ///         Ok(_) => break,
2000    ///         Err(x) => old = x,
2001    ///     }
2002    /// }
2003    /// ```
2004    ///
2005    /// # Considerations
2006    ///
2007    /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
2008    /// of CAS operations. In particular, a load of the value followed by a successful
2009    /// `compare_exchange` with the previous load *does not ensure* that other threads have not
2010    /// changed the value in the interim. This is usually important when the *equality* check in
2011    /// the `compare_exchange` is being used to check the *identity* of a value, but equality
2012    /// does not necessarily imply identity. This is a particularly common case for pointers, as
2013    /// a pointer holding the same address does not imply that the same object exists at that
2014    /// address! In this case, `compare_exchange` can lead to the [ABA problem].
2015    ///
2016    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
2017    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
2018    #[inline]
2019    #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
2020    #[cfg(target_has_atomic = "ptr")]
2021    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2022    #[rustc_should_not_be_called_on_const_items]
2023    pub fn compare_exchange_weak(
2024        &self,
2025        current: *mut T,
2026        new: *mut T,
2027        success: Ordering,
2028        failure: Ordering,
2029    ) -> Result<*mut T, *mut T> {
2030        // SAFETY: This intrinsic is unsafe because it operates on a raw pointer
2031        // but we know for sure that the pointer is valid (we just got it from
2032        // an `UnsafeCell` that we have by reference) and the atomic operation
2033        // itself allows us to safely mutate the `UnsafeCell` contents.
2034        unsafe { atomic_compare_exchange_weak(self.p.get(), current, new, success, failure) }
2035    }
2036
2037    /// Fetches the value, and applies a function to it that returns an optional
2038    /// new value. Returns a `Result` of `Ok(previous_value)` if the function
2039    /// returned `Some(_)`, else `Err(previous_value)`.
2040    ///
2041    /// Note: This may call the function multiple times if the value has been
2042    /// changed from other threads in the meantime, as long as the function
2043    /// returns `Some(_)`, but the function will have been applied only once to
2044    /// the stored value.
2045    ///
2046    /// `fetch_update` takes two [`Ordering`] arguments to describe the memory
2047    /// ordering of this operation. The first describes the required ordering for
2048    /// when the operation finally succeeds while the second describes the
2049    /// required ordering for loads. These correspond to the success and failure
2050    /// orderings of [`AtomicPtr::compare_exchange`] respectively.
2051    ///
2052    /// Using [`Acquire`] as success ordering makes the store part of this
2053    /// operation [`Relaxed`], and using [`Release`] makes the final successful
2054    /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
2055    /// [`Acquire`] or [`Relaxed`].
2056    ///
2057    /// **Note:** This method is only available on platforms that support atomic
2058    /// operations on pointers.
2059    ///
2060    /// # Considerations
2061    ///
2062    /// This method is not magic; it is not provided by the hardware, and does not act like a
2063    /// critical section or mutex.
2064    ///
2065    /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
2066    /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
2067    /// which is a particularly common pitfall for pointers!
2068    ///
2069    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
2070    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
2071    ///
2072    /// # Examples
2073    ///
2074    /// ```rust
2075    /// use std::sync::atomic::{AtomicPtr, Ordering};
2076    ///
2077    /// let ptr: *mut _ = &mut 5;
2078    /// let some_ptr = AtomicPtr::new(ptr);
2079    ///
2080    /// let new: *mut _ = &mut 10;
2081    /// assert_eq!(some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr));
2082    /// let result = some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
2083    ///     if x == ptr {
2084    ///         Some(new)
2085    ///     } else {
2086    ///         None
2087    ///     }
2088    /// });
2089    /// assert_eq!(result, Ok(ptr));
2090    /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
2091    /// ```
2092    #[inline]
2093    #[stable(feature = "atomic_fetch_update", since = "1.53.0")]
2094    #[cfg(target_has_atomic = "ptr")]
2095    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2096    #[rustc_should_not_be_called_on_const_items]
2097    pub fn fetch_update<F>(
2098        &self,
2099        set_order: Ordering,
2100        fetch_order: Ordering,
2101        mut f: F,
2102    ) -> Result<*mut T, *mut T>
2103    where
2104        F: FnMut(*mut T) -> Option<*mut T>,
2105    {
2106        let mut prev = self.load(fetch_order);
2107        while let Some(next) = f(prev) {
2108            match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
2109                x @ Ok(_) => return x,
2110                Err(next_prev) => prev = next_prev,
2111            }
2112        }
2113        Err(prev)
2114    }
2115    /// Fetches the value, and applies a function to it that returns an optional
2116    /// new value. Returns a `Result` of `Ok(previous_value)` if the function
2117    /// returned `Some(_)`, else `Err(previous_value)`.
2118    ///
2119    /// See also: [`update`](`AtomicPtr::update`).
2120    ///
2121    /// Note: This may call the function multiple times if the value has been
2122    /// changed from other threads in the meantime, as long as the function
2123    /// returns `Some(_)`, but the function will have been applied only once to
2124    /// the stored value.
2125    ///
2126    /// `try_update` takes two [`Ordering`] arguments to describe the memory
2127    /// ordering of this operation. The first describes the required ordering for
2128    /// when the operation finally succeeds while the second describes the
2129    /// required ordering for loads. These correspond to the success and failure
2130    /// orderings of [`AtomicPtr::compare_exchange`] respectively.
2131    ///
2132    /// Using [`Acquire`] as success ordering makes the store part of this
2133    /// operation [`Relaxed`], and using [`Release`] makes the final successful
2134    /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
2135    /// [`Acquire`] or [`Relaxed`].
2136    ///
2137    /// **Note:** This method is only available on platforms that support atomic
2138    /// operations on pointers.
2139    ///
2140    /// # Considerations
2141    ///
2142    /// This method is not magic; it is not provided by the hardware, and does not act like a
2143    /// critical section or mutex.
2144    ///
2145    /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
2146    /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
2147    /// which is a particularly common pitfall for pointers!
2148    ///
2149    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
2150    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
2151    ///
2152    /// # Examples
2153    ///
2154    /// ```rust
2155    /// #![feature(atomic_try_update)]
2156    /// use std::sync::atomic::{AtomicPtr, Ordering};
2157    ///
2158    /// let ptr: *mut _ = &mut 5;
2159    /// let some_ptr = AtomicPtr::new(ptr);
2160    ///
2161    /// let new: *mut _ = &mut 10;
2162    /// assert_eq!(some_ptr.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr));
2163    /// let result = some_ptr.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
2164    ///     if x == ptr {
2165    ///         Some(new)
2166    ///     } else {
2167    ///         None
2168    ///     }
2169    /// });
2170    /// assert_eq!(result, Ok(ptr));
2171    /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
2172    /// ```
2173    #[inline]
2174    #[unstable(feature = "atomic_try_update", issue = "135894")]
2175    #[cfg(target_has_atomic = "ptr")]
2176    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2177    #[rustc_should_not_be_called_on_const_items]
2178    pub fn try_update(
2179        &self,
2180        set_order: Ordering,
2181        fetch_order: Ordering,
2182        f: impl FnMut(*mut T) -> Option<*mut T>,
2183    ) -> Result<*mut T, *mut T> {
2184        // FIXME(atomic_try_update): this is currently an unstable alias to `fetch_update`;
2185        //      when stabilizing, turn `fetch_update` into a deprecated alias to `try_update`.
2186        self.fetch_update(set_order, fetch_order, f)
2187    }
2188
2189    /// Fetches the value, applies a function to it that it return a new value.
2190    /// The new value is stored and the old value is returned.
2191    ///
2192    /// See also: [`try_update`](`AtomicPtr::try_update`).
2193    ///
2194    /// Note: This may call the function multiple times if the value has been changed from other threads in
2195    /// the meantime, but the function will have been applied only once to the stored value.
2196    ///
2197    /// `update` takes two [`Ordering`] arguments to describe the memory
2198    /// ordering of this operation. The first describes the required ordering for
2199    /// when the operation finally succeeds while the second describes the
2200    /// required ordering for loads. These correspond to the success and failure
2201    /// orderings of [`AtomicPtr::compare_exchange`] respectively.
2202    ///
2203    /// Using [`Acquire`] as success ordering makes the store part
2204    /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
2205    /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
2206    ///
2207    /// **Note:** This method is only available on platforms that support atomic
2208    /// operations on pointers.
2209    ///
2210    /// # Considerations
2211    ///
2212    /// This method is not magic; it is not provided by the hardware, and does not act like a
2213    /// critical section or mutex.
2214    ///
2215    /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
2216    /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
2217    /// which is a particularly common pitfall for pointers!
2218    ///
2219    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
2220    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
2221    ///
2222    /// # Examples
2223    ///
2224    /// ```rust
2225    /// #![feature(atomic_try_update)]
2226    ///
2227    /// use std::sync::atomic::{AtomicPtr, Ordering};
2228    ///
2229    /// let ptr: *mut _ = &mut 5;
2230    /// let some_ptr = AtomicPtr::new(ptr);
2231    ///
2232    /// let new: *mut _ = &mut 10;
2233    /// let result = some_ptr.update(Ordering::SeqCst, Ordering::SeqCst, |_| new);
2234    /// assert_eq!(result, ptr);
2235    /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
2236    /// ```
2237    #[inline]
2238    #[unstable(feature = "atomic_try_update", issue = "135894")]
2239    #[cfg(target_has_atomic = "8")]
2240    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2241    #[rustc_should_not_be_called_on_const_items]
2242    pub fn update(
2243        &self,
2244        set_order: Ordering,
2245        fetch_order: Ordering,
2246        mut f: impl FnMut(*mut T) -> *mut T,
2247    ) -> *mut T {
2248        let mut prev = self.load(fetch_order);
2249        loop {
2250            match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
2251                Ok(x) => break x,
2252                Err(next_prev) => prev = next_prev,
2253            }
2254        }
2255    }
2256
2257    /// Offsets the pointer's address by adding `val` (in units of `T`),
2258    /// returning the previous pointer.
2259    ///
2260    /// This is equivalent to using [`wrapping_add`] to atomically perform the
2261    /// equivalent of `ptr = ptr.wrapping_add(val);`.
2262    ///
2263    /// This method operates in units of `T`, which means that it cannot be used
2264    /// to offset the pointer by an amount which is not a multiple of
2265    /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
2266    /// work with a deliberately misaligned pointer. In such cases, you may use
2267    /// the [`fetch_byte_add`](Self::fetch_byte_add) method instead.
2268    ///
2269    /// `fetch_ptr_add` takes an [`Ordering`] argument which describes the
2270    /// memory ordering of this operation. All ordering modes are possible. Note
2271    /// that using [`Acquire`] makes the store part of this operation
2272    /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2273    ///
2274    /// **Note**: This method is only available on platforms that support atomic
2275    /// operations on [`AtomicPtr`].
2276    ///
2277    /// [`wrapping_add`]: pointer::wrapping_add
2278    ///
2279    /// # Examples
2280    ///
2281    /// ```
2282    /// use core::sync::atomic::{AtomicPtr, Ordering};
2283    ///
2284    /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
2285    /// assert_eq!(atom.fetch_ptr_add(1, Ordering::Relaxed).addr(), 0);
2286    /// // Note: units of `size_of::<i64>()`.
2287    /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 8);
2288    /// ```
2289    #[inline]
2290    #[cfg(target_has_atomic = "ptr")]
2291    #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2292    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2293    #[rustc_should_not_be_called_on_const_items]
2294    pub fn fetch_ptr_add(&self, val: usize, order: Ordering) -> *mut T {
2295        self.fetch_byte_add(val.wrapping_mul(size_of::<T>()), order)
2296    }
2297
2298    /// Offsets the pointer's address by subtracting `val` (in units of `T`),
2299    /// returning the previous pointer.
2300    ///
2301    /// This is equivalent to using [`wrapping_sub`] to atomically perform the
2302    /// equivalent of `ptr = ptr.wrapping_sub(val);`.
2303    ///
2304    /// This method operates in units of `T`, which means that it cannot be used
2305    /// to offset the pointer by an amount which is not a multiple of
2306    /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
2307    /// work with a deliberately misaligned pointer. In such cases, you may use
2308    /// the [`fetch_byte_sub`](Self::fetch_byte_sub) method instead.
2309    ///
2310    /// `fetch_ptr_sub` takes an [`Ordering`] argument which describes the memory
2311    /// ordering of this operation. All ordering modes are possible. Note that
2312    /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2313    /// and using [`Release`] makes the load part [`Relaxed`].
2314    ///
2315    /// **Note**: This method is only available on platforms that support atomic
2316    /// operations on [`AtomicPtr`].
2317    ///
2318    /// [`wrapping_sub`]: pointer::wrapping_sub
2319    ///
2320    /// # Examples
2321    ///
2322    /// ```
2323    /// use core::sync::atomic::{AtomicPtr, Ordering};
2324    ///
2325    /// let array = [1i32, 2i32];
2326    /// let atom = AtomicPtr::new(array.as_ptr().wrapping_add(1) as *mut _);
2327    ///
2328    /// assert!(core::ptr::eq(
2329    ///     atom.fetch_ptr_sub(1, Ordering::Relaxed),
2330    ///     &array[1],
2331    /// ));
2332    /// assert!(core::ptr::eq(atom.load(Ordering::Relaxed), &array[0]));
2333    /// ```
2334    #[inline]
2335    #[cfg(target_has_atomic = "ptr")]
2336    #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2337    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2338    #[rustc_should_not_be_called_on_const_items]
2339    pub fn fetch_ptr_sub(&self, val: usize, order: Ordering) -> *mut T {
2340        self.fetch_byte_sub(val.wrapping_mul(size_of::<T>()), order)
2341    }
2342
2343    /// Offsets the pointer's address by adding `val` *bytes*, returning the
2344    /// previous pointer.
2345    ///
2346    /// This is equivalent to using [`wrapping_byte_add`] to atomically
2347    /// perform `ptr = ptr.wrapping_byte_add(val)`.
2348    ///
2349    /// `fetch_byte_add` takes an [`Ordering`] argument which describes the
2350    /// memory ordering of this operation. All ordering modes are possible. Note
2351    /// that using [`Acquire`] makes the store part of this operation
2352    /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2353    ///
2354    /// **Note**: This method is only available on platforms that support atomic
2355    /// operations on [`AtomicPtr`].
2356    ///
2357    /// [`wrapping_byte_add`]: pointer::wrapping_byte_add
2358    ///
2359    /// # Examples
2360    ///
2361    /// ```
2362    /// use core::sync::atomic::{AtomicPtr, Ordering};
2363    ///
2364    /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
2365    /// assert_eq!(atom.fetch_byte_add(1, Ordering::Relaxed).addr(), 0);
2366    /// // Note: in units of bytes, not `size_of::<i64>()`.
2367    /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 1);
2368    /// ```
2369    #[inline]
2370    #[cfg(target_has_atomic = "ptr")]
2371    #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2372    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2373    #[rustc_should_not_be_called_on_const_items]
2374    pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T {
2375        // SAFETY: data races are prevented by atomic intrinsics.
2376        unsafe { atomic_add(self.p.get(), val, order).cast() }
2377    }
2378
2379    /// Offsets the pointer's address by subtracting `val` *bytes*, returning the
2380    /// previous pointer.
2381    ///
2382    /// This is equivalent to using [`wrapping_byte_sub`] to atomically
2383    /// perform `ptr = ptr.wrapping_byte_sub(val)`.
2384    ///
2385    /// `fetch_byte_sub` takes an [`Ordering`] argument which describes the
2386    /// memory ordering of this operation. All ordering modes are possible. Note
2387    /// that using [`Acquire`] makes the store part of this operation
2388    /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2389    ///
2390    /// **Note**: This method is only available on platforms that support atomic
2391    /// operations on [`AtomicPtr`].
2392    ///
2393    /// [`wrapping_byte_sub`]: pointer::wrapping_byte_sub
2394    ///
2395    /// # Examples
2396    ///
2397    /// ```
2398    /// use core::sync::atomic::{AtomicPtr, Ordering};
2399    ///
2400    /// let mut arr = [0i64, 1];
2401    /// let atom = AtomicPtr::<i64>::new(&raw mut arr[1]);
2402    /// assert_eq!(atom.fetch_byte_sub(8, Ordering::Relaxed).addr(), (&raw const arr[1]).addr());
2403    /// assert_eq!(atom.load(Ordering::Relaxed).addr(), (&raw const arr[0]).addr());
2404    /// ```
2405    #[inline]
2406    #[cfg(target_has_atomic = "ptr")]
2407    #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2408    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2409    #[rustc_should_not_be_called_on_const_items]
2410    pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T {
2411        // SAFETY: data races are prevented by atomic intrinsics.
2412        unsafe { atomic_sub(self.p.get(), val, order).cast() }
2413    }
2414
2415    /// Performs a bitwise "or" operation on the address of the current pointer,
2416    /// and the argument `val`, and stores a pointer with provenance of the
2417    /// current pointer and the resulting address.
2418    ///
2419    /// This is equivalent to using [`map_addr`] to atomically perform
2420    /// `ptr = ptr.map_addr(|a| a | val)`. This can be used in tagged
2421    /// pointer schemes to atomically set tag bits.
2422    ///
2423    /// **Caveat**: This operation returns the previous value. To compute the
2424    /// stored value without losing provenance, you may use [`map_addr`]. For
2425    /// example: `a.fetch_or(val).map_addr(|a| a | val)`.
2426    ///
2427    /// `fetch_or` takes an [`Ordering`] argument which describes the memory
2428    /// ordering of this operation. All ordering modes are possible. Note that
2429    /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2430    /// and using [`Release`] makes the load part [`Relaxed`].
2431    ///
2432    /// **Note**: This method is only available on platforms that support atomic
2433    /// operations on [`AtomicPtr`].
2434    ///
2435    /// This API and its claimed semantics are part of the Strict Provenance
2436    /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2437    /// details.
2438    ///
2439    /// [`map_addr`]: pointer::map_addr
2440    ///
2441    /// # Examples
2442    ///
2443    /// ```
2444    /// use core::sync::atomic::{AtomicPtr, Ordering};
2445    ///
2446    /// let pointer = &mut 3i64 as *mut i64;
2447    ///
2448    /// let atom = AtomicPtr::<i64>::new(pointer);
2449    /// // Tag the bottom bit of the pointer.
2450    /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 0);
2451    /// // Extract and untag.
2452    /// let tagged = atom.load(Ordering::Relaxed);
2453    /// assert_eq!(tagged.addr() & 1, 1);
2454    /// assert_eq!(tagged.map_addr(|p| p & !1), pointer);
2455    /// ```
2456    #[inline]
2457    #[cfg(target_has_atomic = "ptr")]
2458    #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2459    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2460    #[rustc_should_not_be_called_on_const_items]
2461    pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T {
2462        // SAFETY: data races are prevented by atomic intrinsics.
2463        unsafe { atomic_or(self.p.get(), val, order).cast() }
2464    }
2465
2466    /// Performs a bitwise "and" operation on the address of the current
2467    /// pointer, and the argument `val`, and stores a pointer with provenance of
2468    /// the current pointer and the resulting address.
2469    ///
2470    /// This is equivalent to using [`map_addr`] to atomically perform
2471    /// `ptr = ptr.map_addr(|a| a & val)`. This can be used in tagged
2472    /// pointer schemes to atomically unset tag bits.
2473    ///
2474    /// **Caveat**: This operation returns the previous value. To compute the
2475    /// stored value without losing provenance, you may use [`map_addr`]. For
2476    /// example: `a.fetch_and(val).map_addr(|a| a & val)`.
2477    ///
2478    /// `fetch_and` takes an [`Ordering`] argument which describes the memory
2479    /// ordering of this operation. All ordering modes are possible. Note that
2480    /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2481    /// and using [`Release`] makes the load part [`Relaxed`].
2482    ///
2483    /// **Note**: This method is only available on platforms that support atomic
2484    /// operations on [`AtomicPtr`].
2485    ///
2486    /// This API and its claimed semantics are part of the Strict Provenance
2487    /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2488    /// details.
2489    ///
2490    /// [`map_addr`]: pointer::map_addr
2491    ///
2492    /// # Examples
2493    ///
2494    /// ```
2495    /// use core::sync::atomic::{AtomicPtr, Ordering};
2496    ///
2497    /// let pointer = &mut 3i64 as *mut i64;
2498    /// // A tagged pointer
2499    /// let atom = AtomicPtr::<i64>::new(pointer.map_addr(|a| a | 1));
2500    /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 1);
2501    /// // Untag, and extract the previously tagged pointer.
2502    /// let untagged = atom.fetch_and(!1, Ordering::Relaxed)
2503    ///     .map_addr(|a| a & !1);
2504    /// assert_eq!(untagged, pointer);
2505    /// ```
2506    #[inline]
2507    #[cfg(target_has_atomic = "ptr")]
2508    #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2509    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2510    #[rustc_should_not_be_called_on_const_items]
2511    pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T {
2512        // SAFETY: data races are prevented by atomic intrinsics.
2513        unsafe { atomic_and(self.p.get(), val, order).cast() }
2514    }
2515
2516    /// Performs a bitwise "xor" operation on the address of the current
2517    /// pointer, and the argument `val`, and stores a pointer with provenance of
2518    /// the current pointer and the resulting address.
2519    ///
2520    /// This is equivalent to using [`map_addr`] to atomically perform
2521    /// `ptr = ptr.map_addr(|a| a ^ val)`. This can be used in tagged
2522    /// pointer schemes to atomically toggle tag bits.
2523    ///
2524    /// **Caveat**: This operation returns the previous value. To compute the
2525    /// stored value without losing provenance, you may use [`map_addr`]. For
2526    /// example: `a.fetch_xor(val).map_addr(|a| a ^ val)`.
2527    ///
2528    /// `fetch_xor` takes an [`Ordering`] argument which describes the memory
2529    /// ordering of this operation. All ordering modes are possible. Note that
2530    /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2531    /// and using [`Release`] makes the load part [`Relaxed`].
2532    ///
2533    /// **Note**: This method is only available on platforms that support atomic
2534    /// operations on [`AtomicPtr`].
2535    ///
2536    /// This API and its claimed semantics are part of the Strict Provenance
2537    /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2538    /// details.
2539    ///
2540    /// [`map_addr`]: pointer::map_addr
2541    ///
2542    /// # Examples
2543    ///
2544    /// ```
2545    /// use core::sync::atomic::{AtomicPtr, Ordering};
2546    ///
2547    /// let pointer = &mut 3i64 as *mut i64;
2548    /// let atom = AtomicPtr::<i64>::new(pointer);
2549    ///
2550    /// // Toggle a tag bit on the pointer.
2551    /// atom.fetch_xor(1, Ordering::Relaxed);
2552    /// assert_eq!(atom.load(Ordering::Relaxed).addr() & 1, 1);
2553    /// ```
2554    #[inline]
2555    #[cfg(target_has_atomic = "ptr")]
2556    #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2557    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2558    #[rustc_should_not_be_called_on_const_items]
2559    pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T {
2560        // SAFETY: data races are prevented by atomic intrinsics.
2561        unsafe { atomic_xor(self.p.get(), val, order).cast() }
2562    }
2563
2564    /// Returns a mutable pointer to the underlying pointer.
2565    ///
2566    /// Doing non-atomic reads and writes on the resulting pointer can be a data race.
2567    /// This method is mostly useful for FFI, where the function signature may use
2568    /// `*mut *mut T` instead of `&AtomicPtr<T>`.
2569    ///
2570    /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
2571    /// atomic types work with interior mutability. All modifications of an atomic change the value
2572    /// through a shared reference, and can do so safely as long as they use atomic operations. Any
2573    /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
2574    /// requirements of the [memory model].
2575    ///
2576    /// # Examples
2577    ///
2578    /// ```ignore (extern-declaration)
2579    /// use std::sync::atomic::AtomicPtr;
2580    ///
2581    /// extern "C" {
2582    ///     fn my_atomic_op(arg: *mut *mut u32);
2583    /// }
2584    ///
2585    /// let mut value = 17;
2586    /// let atomic = AtomicPtr::new(&mut value);
2587    ///
2588    /// // SAFETY: Safe as long as `my_atomic_op` is atomic.
2589    /// unsafe {
2590    ///     my_atomic_op(atomic.as_ptr());
2591    /// }
2592    /// ```
2593    ///
2594    /// [memory model]: self#memory-model-for-atomic-accesses
2595    #[inline]
2596    #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
2597    #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
2598    #[rustc_never_returns_null_ptr]
2599    pub const fn as_ptr(&self) -> *mut *mut T {
2600        self.p.get()
2601    }
2602}
2603
2604#[cfg(target_has_atomic_load_store = "8")]
2605#[stable(feature = "atomic_bool_from", since = "1.24.0")]
2606#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2607#[cfg(not(feature = "ferrocene_subset"))]
2608impl const From<bool> for AtomicBool {
2609    /// Converts a `bool` into an `AtomicBool`.
2610    ///
2611    /// # Examples
2612    ///
2613    /// ```
2614    /// use std::sync::atomic::AtomicBool;
2615    /// let atomic_bool = AtomicBool::from(true);
2616    /// assert_eq!(format!("{atomic_bool:?}"), "true")
2617    /// ```
2618    #[inline]
2619    fn from(b: bool) -> Self {
2620        Self::new(b)
2621    }
2622}
2623
2624#[cfg(target_has_atomic_load_store = "ptr")]
2625#[stable(feature = "atomic_from", since = "1.23.0")]
2626#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2627#[cfg(not(feature = "ferrocene_subset"))]
2628impl<T> const From<*mut T> for AtomicPtr<T> {
2629    /// Converts a `*mut T` into an `AtomicPtr<T>`.
2630    #[inline]
2631    fn from(p: *mut T) -> Self {
2632        Self::new(p)
2633    }
2634}
2635
2636#[allow(unused_macros)] // This macro ends up being unused on some architectures.
2637macro_rules! if_8_bit {
2638    (u8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) };
2639    (i8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) };
2640    ($_:ident, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($no)*)?) };
2641}
2642
2643#[cfg(target_has_atomic_load_store)]
2644macro_rules! atomic_int {
2645    ($cfg_cas:meta,
2646     $cfg_align:meta,
2647     $stable:meta,
2648     $stable_cxchg:meta,
2649     $stable_debug:meta,
2650     $stable_access:meta,
2651     $stable_from:meta,
2652     $stable_nand:meta,
2653     $const_stable_new:meta,
2654     $const_stable_into_inner:meta,
2655     $diagnostic_item:meta,
2656     $s_int_type:literal,
2657     $extra_feature:expr,
2658     $min_fn:ident, $max_fn:ident,
2659     $align:expr,
2660     $int_type:ident $atomic_type:ident) => {
2661        /// An integer type which can be safely shared between threads.
2662        ///
2663        /// This type has the same
2664        #[doc = if_8_bit!(
2665            $int_type,
2666            yes = ["size, alignment, and bit validity"],
2667            no = ["size and bit validity"],
2668        )]
2669        /// as the underlying integer type, [`
2670        #[doc = $s_int_type]
2671        /// `].
2672        #[doc = if_8_bit! {
2673            $int_type,
2674            no = [
2675                "However, the alignment of this type is always equal to its ",
2676                "size, even on targets where [`", $s_int_type, "`] has a ",
2677                "lesser alignment."
2678            ],
2679        }]
2680        ///
2681        /// For more about the differences between atomic types and
2682        /// non-atomic types as well as information about the portability of
2683        /// this type, please see the [module-level documentation].
2684        ///
2685        /// **Note:** This type is only available on platforms that support
2686        /// atomic loads and stores of [`
2687        #[doc = $s_int_type]
2688        /// `].
2689        ///
2690        /// [module-level documentation]: crate::sync::atomic
2691        #[$stable]
2692        #[$diagnostic_item]
2693        #[repr(C, align($align))]
2694        pub struct $atomic_type {
2695            v: UnsafeCell<$int_type>,
2696        }
2697
2698        #[$stable]
2699        impl Default for $atomic_type {
2700            #[inline]
2701            fn default() -> Self {
2702                Self::new(Default::default())
2703            }
2704        }
2705
2706        #[$stable_from]
2707        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2708        impl const From<$int_type> for $atomic_type {
2709            #[doc = concat!("Converts an `", stringify!($int_type), "` into an `", stringify!($atomic_type), "`.")]
2710            #[inline]
2711            fn from(v: $int_type) -> Self { Self::new(v) }
2712        }
2713
2714        #[$stable_debug]
2715        #[cfg(not(feature = "ferrocene_subset"))]
2716        impl fmt::Debug for $atomic_type {
2717            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2718                fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
2719            }
2720        }
2721
2722        // Send is implicitly implemented.
2723        #[$stable]
2724        unsafe impl Sync for $atomic_type {}
2725
2726        impl $atomic_type {
2727            /// Creates a new atomic integer.
2728            ///
2729            /// # Examples
2730            ///
2731            /// ```
2732            #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2733            ///
2734            #[doc = concat!("let atomic_forty_two = ", stringify!($atomic_type), "::new(42);")]
2735            /// ```
2736            #[inline]
2737            #[$stable]
2738            #[$const_stable_new]
2739            #[must_use]
2740            pub const fn new(v: $int_type) -> Self {
2741                Self {v: UnsafeCell::new(v)}
2742            }
2743
2744            /// Creates a new reference to an atomic integer from a pointer.
2745            ///
2746            /// # Examples
2747            ///
2748            /// ```
2749            #[doc = concat!($extra_feature, "use std::sync::atomic::{self, ", stringify!($atomic_type), "};")]
2750            ///
2751            /// // Get a pointer to an allocated value
2752            #[doc = concat!("let ptr: *mut ", stringify!($int_type), " = Box::into_raw(Box::new(0));")]
2753            ///
2754            #[doc = concat!("assert!(ptr.cast::<", stringify!($atomic_type), ">().is_aligned());")]
2755            ///
2756            /// {
2757            ///     // Create an atomic view of the allocated value
2758            // SAFETY: this is a doc comment, tidy, it can't hurt you (also guaranteed by the construction of `ptr` and the assert above)
2759            #[doc = concat!("    let atomic = unsafe {", stringify!($atomic_type), "::from_ptr(ptr) };")]
2760            ///
2761            ///     // Use `atomic` for atomic operations, possibly share it with other threads
2762            ///     atomic.store(1, atomic::Ordering::Relaxed);
2763            /// }
2764            ///
2765            /// // It's ok to non-atomically access the value behind `ptr`,
2766            /// // since the reference to the atomic ended its lifetime in the block above
2767            /// assert_eq!(unsafe { *ptr }, 1);
2768            ///
2769            /// // Deallocate the value
2770            /// unsafe { drop(Box::from_raw(ptr)) }
2771            /// ```
2772            ///
2773            /// # Safety
2774            ///
2775            /// * `ptr` must be aligned to
2776            #[doc = concat!("  `align_of::<", stringify!($atomic_type), ">()`")]
2777            #[doc = if_8_bit!{
2778                $int_type,
2779                yes = [
2780                    "  (note that this is always true, since `align_of::<",
2781                    stringify!($atomic_type), ">() == 1`)."
2782                ],
2783                no = [
2784                    "  (note that on some platforms this can be bigger than `align_of::<",
2785                    stringify!($int_type), ">()`)."
2786                ],
2787            }]
2788            /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
2789            /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
2790            ///   allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
2791            ///   sizes, without synchronization.
2792            ///
2793            /// [valid]: crate::ptr#safety
2794            /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
2795            #[inline]
2796            #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
2797            #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
2798            pub const unsafe fn from_ptr<'a>(ptr: *mut $int_type) -> &'a $atomic_type {
2799                // SAFETY: guaranteed by the caller
2800                unsafe { &*ptr.cast() }
2801            }
2802
2803
2804            /// Returns a mutable reference to the underlying integer.
2805            ///
2806            /// This is safe because the mutable reference guarantees that no other threads are
2807            /// concurrently accessing the atomic data.
2808            ///
2809            /// # Examples
2810            ///
2811            /// ```
2812            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2813            ///
2814            #[doc = concat!("let mut some_var = ", stringify!($atomic_type), "::new(10);")]
2815            /// assert_eq!(*some_var.get_mut(), 10);
2816            /// *some_var.get_mut() = 5;
2817            /// assert_eq!(some_var.load(Ordering::SeqCst), 5);
2818            /// ```
2819            #[inline]
2820            #[$stable_access]
2821            pub fn get_mut(&mut self) -> &mut $int_type {
2822                self.v.get_mut()
2823            }
2824
2825            #[doc = concat!("Get atomic access to a `&mut ", stringify!($int_type), "`.")]
2826            ///
2827            #[doc = if_8_bit! {
2828                $int_type,
2829                no = [
2830                    "**Note:** This function is only available on targets where `",
2831                    stringify!($atomic_type), "` has the same alignment as `", stringify!($int_type), "`."
2832                ],
2833            }]
2834            ///
2835            /// # Examples
2836            ///
2837            /// ```
2838            /// #![feature(atomic_from_mut)]
2839            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2840            ///
2841            /// let mut some_int = 123;
2842            #[doc = concat!("let a = ", stringify!($atomic_type), "::from_mut(&mut some_int);")]
2843            /// a.store(100, Ordering::Relaxed);
2844            /// assert_eq!(some_int, 100);
2845            /// ```
2846            ///
2847            #[inline]
2848            #[$cfg_align]
2849            #[unstable(feature = "atomic_from_mut", issue = "76314")]
2850            pub fn from_mut(v: &mut $int_type) -> &mut Self {
2851                let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
2852                // SAFETY:
2853                //  - the mutable reference guarantees unique ownership.
2854                //  - the alignment of `$int_type` and `Self` is the
2855                //    same, as promised by $cfg_align and verified above.
2856                unsafe { &mut *(v as *mut $int_type as *mut Self) }
2857            }
2858
2859            #[doc = concat!("Get non-atomic access to a `&mut [", stringify!($atomic_type), "]` slice")]
2860            ///
2861            /// This is safe because the mutable reference guarantees that no other threads are
2862            /// concurrently accessing the atomic data.
2863            ///
2864            /// # Examples
2865            ///
2866            /// ```ignore-wasm
2867            /// #![feature(atomic_from_mut)]
2868            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2869            ///
2870            #[doc = concat!("let mut some_ints = [const { ", stringify!($atomic_type), "::new(0) }; 10];")]
2871            ///
2872            #[doc = concat!("let view: &mut [", stringify!($int_type), "] = ", stringify!($atomic_type), "::get_mut_slice(&mut some_ints);")]
2873            /// assert_eq!(view, [0; 10]);
2874            /// view
2875            ///     .iter_mut()
2876            ///     .enumerate()
2877            ///     .for_each(|(idx, int)| *int = idx as _);
2878            ///
2879            /// std::thread::scope(|s| {
2880            ///     some_ints
2881            ///         .iter()
2882            ///         .enumerate()
2883            ///         .for_each(|(idx, int)| {
2884            ///             s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
2885            ///         })
2886            /// });
2887            /// ```
2888            #[inline]
2889            #[unstable(feature = "atomic_from_mut", issue = "76314")]
2890            pub fn get_mut_slice(this: &mut [Self]) -> &mut [$int_type] {
2891                // SAFETY: the mutable reference guarantees unique ownership.
2892                unsafe { &mut *(this as *mut [Self] as *mut [$int_type]) }
2893            }
2894
2895            #[doc = concat!("Get atomic access to a `&mut [", stringify!($int_type), "]` slice.")]
2896            ///
2897            #[doc = if_8_bit! {
2898                $int_type,
2899                no = [
2900                    "**Note:** This function is only available on targets where `",
2901                    stringify!($atomic_type), "` has the same alignment as `", stringify!($int_type), "`."
2902                ],
2903            }]
2904            ///
2905            /// # Examples
2906            ///
2907            /// ```ignore-wasm
2908            /// #![feature(atomic_from_mut)]
2909            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2910            ///
2911            /// let mut some_ints = [0; 10];
2912            #[doc = concat!("let a = &*", stringify!($atomic_type), "::from_mut_slice(&mut some_ints);")]
2913            /// std::thread::scope(|s| {
2914            ///     for i in 0..a.len() {
2915            ///         s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
2916            ///     }
2917            /// });
2918            /// for (i, n) in some_ints.into_iter().enumerate() {
2919            ///     assert_eq!(i, n as usize);
2920            /// }
2921            /// ```
2922            #[inline]
2923            #[$cfg_align]
2924            #[unstable(feature = "atomic_from_mut", issue = "76314")]
2925            pub fn from_mut_slice(v: &mut [$int_type]) -> &mut [Self] {
2926                let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
2927                // SAFETY:
2928                //  - the mutable reference guarantees unique ownership.
2929                //  - the alignment of `$int_type` and `Self` is the
2930                //    same, as promised by $cfg_align and verified above.
2931                unsafe { &mut *(v as *mut [$int_type] as *mut [Self]) }
2932            }
2933
2934            /// Consumes the atomic and returns the contained value.
2935            ///
2936            /// This is safe because passing `self` by value guarantees that no other threads are
2937            /// concurrently accessing the atomic data.
2938            ///
2939            /// # Examples
2940            ///
2941            /// ```
2942            #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2943            ///
2944            #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2945            /// assert_eq!(some_var.into_inner(), 5);
2946            /// ```
2947            #[inline]
2948            #[$stable_access]
2949            #[$const_stable_into_inner]
2950            pub const fn into_inner(self) -> $int_type {
2951                self.v.into_inner()
2952            }
2953
2954            /// Loads a value from the atomic integer.
2955            ///
2956            /// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2957            /// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
2958            ///
2959            /// # Panics
2960            ///
2961            /// Panics if `order` is [`Release`] or [`AcqRel`].
2962            ///
2963            /// # Examples
2964            ///
2965            /// ```
2966            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2967            ///
2968            #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2969            ///
2970            /// assert_eq!(some_var.load(Ordering::Relaxed), 5);
2971            /// ```
2972            #[inline]
2973            #[$stable]
2974            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2975            pub fn load(&self, order: Ordering) -> $int_type {
2976                // SAFETY: data races are prevented by atomic intrinsics.
2977                unsafe { atomic_load(self.v.get(), order) }
2978            }
2979
2980            /// Stores a value into the atomic integer.
2981            ///
2982            /// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2983            ///  Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
2984            ///
2985            /// # Panics
2986            ///
2987            /// Panics if `order` is [`Acquire`] or [`AcqRel`].
2988            ///
2989            /// # Examples
2990            ///
2991            /// ```
2992            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2993            ///
2994            #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2995            ///
2996            /// some_var.store(10, Ordering::Relaxed);
2997            /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2998            /// ```
2999            #[inline]
3000            #[$stable]
3001            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3002            #[rustc_should_not_be_called_on_const_items]
3003            pub fn store(&self, val: $int_type, order: Ordering) {
3004                // SAFETY: data races are prevented by atomic intrinsics.
3005                unsafe { atomic_store(self.v.get(), val, order); }
3006            }
3007
3008            /// Stores a value into the atomic integer, returning the previous value.
3009            ///
3010            /// `swap` takes an [`Ordering`] argument which describes the memory ordering
3011            /// of this operation. All ordering modes are possible. Note that using
3012            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3013            /// using [`Release`] makes the load part [`Relaxed`].
3014            ///
3015            /// **Note**: This method is only available on platforms that support atomic operations on
3016            #[doc = concat!("[`", $s_int_type, "`].")]
3017            ///
3018            /// # Examples
3019            ///
3020            /// ```
3021            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3022            ///
3023            #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
3024            ///
3025            /// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
3026            /// ```
3027            #[inline]
3028            #[$stable]
3029            #[$cfg_cas]
3030            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3031            #[rustc_should_not_be_called_on_const_items]
3032            pub fn swap(&self, val: $int_type, order: Ordering) -> $int_type {
3033                // SAFETY: data races are prevented by atomic intrinsics.
3034                unsafe { atomic_swap(self.v.get(), val, order) }
3035            }
3036
3037            /// Stores a value into the atomic integer if the current value is the same as
3038            /// the `current` value.
3039            ///
3040            /// The return value is always the previous value. If it is equal to `current`, then the
3041            /// value was updated.
3042            ///
3043            /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
3044            /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
3045            /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
3046            /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
3047            /// happens, and using [`Release`] makes the load part [`Relaxed`].
3048            ///
3049            /// **Note**: This method is only available on platforms that support atomic operations on
3050            #[doc = concat!("[`", $s_int_type, "`].")]
3051            ///
3052            /// # Migrating to `compare_exchange` and `compare_exchange_weak`
3053            ///
3054            /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
3055            /// memory orderings:
3056            ///
3057            /// Original | Success | Failure
3058            /// -------- | ------- | -------
3059            /// Relaxed  | Relaxed | Relaxed
3060            /// Acquire  | Acquire | Acquire
3061            /// Release  | Release | Relaxed
3062            /// AcqRel   | AcqRel  | Acquire
3063            /// SeqCst   | SeqCst  | SeqCst
3064            ///
3065            /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
3066            /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
3067            /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
3068            /// rather than to infer success vs failure based on the value that was read.
3069            ///
3070            /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
3071            /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
3072            /// which allows the compiler to generate better assembly code when the compare and swap
3073            /// is used in a loop.
3074            ///
3075            /// # Examples
3076            ///
3077            /// ```
3078            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3079            ///
3080            #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
3081            ///
3082            /// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
3083            /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3084            ///
3085            /// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
3086            /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3087            /// ```
3088            #[inline]
3089            #[$stable]
3090            #[deprecated(
3091                since = "1.50.0",
3092                note = "Use `compare_exchange` or `compare_exchange_weak` instead")
3093            ]
3094            #[$cfg_cas]
3095            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3096            #[rustc_should_not_be_called_on_const_items]
3097            pub fn compare_and_swap(&self,
3098                                    current: $int_type,
3099                                    new: $int_type,
3100                                    order: Ordering) -> $int_type {
3101                match self.compare_exchange(current,
3102                                            new,
3103                                            order,
3104                                            strongest_failure_ordering(order)) {
3105                    Ok(x) => x,
3106                    Err(x) => x,
3107                }
3108            }
3109
3110            /// Stores a value into the atomic integer if the current value is the same as
3111            /// the `current` value.
3112            ///
3113            /// The return value is a result indicating whether the new value was written and
3114            /// containing the previous value. On success this value is guaranteed to be equal to
3115            /// `current`.
3116            ///
3117            /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
3118            /// ordering of this operation. `success` describes the required ordering for the
3119            /// read-modify-write operation that takes place if the comparison with `current` succeeds.
3120            /// `failure` describes the required ordering for the load operation that takes place when
3121            /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
3122            /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
3123            /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3124            ///
3125            /// **Note**: This method is only available on platforms that support atomic operations on
3126            #[doc = concat!("[`", $s_int_type, "`].")]
3127            ///
3128            /// # Examples
3129            ///
3130            /// ```
3131            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3132            ///
3133            #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
3134            ///
3135            /// assert_eq!(some_var.compare_exchange(5, 10,
3136            ///                                      Ordering::Acquire,
3137            ///                                      Ordering::Relaxed),
3138            ///            Ok(5));
3139            /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3140            ///
3141            /// assert_eq!(some_var.compare_exchange(6, 12,
3142            ///                                      Ordering::SeqCst,
3143            ///                                      Ordering::Acquire),
3144            ///            Err(10));
3145            /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3146            /// ```
3147            ///
3148            /// # Considerations
3149            ///
3150            /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
3151            /// of CAS operations. In particular, a load of the value followed by a successful
3152            /// `compare_exchange` with the previous load *does not ensure* that other threads have not
3153            /// changed the value in the interim! This is usually important when the *equality* check in
3154            /// the `compare_exchange` is being used to check the *identity* of a value, but equality
3155            /// does not necessarily imply identity. This is a particularly common case for pointers, as
3156            /// a pointer holding the same address does not imply that the same object exists at that
3157            /// address! In this case, `compare_exchange` can lead to the [ABA problem].
3158            ///
3159            /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3160            /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3161            #[inline]
3162            #[$stable_cxchg]
3163            #[$cfg_cas]
3164            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3165            #[rustc_should_not_be_called_on_const_items]
3166            pub fn compare_exchange(&self,
3167                                    current: $int_type,
3168                                    new: $int_type,
3169                                    success: Ordering,
3170                                    failure: Ordering) -> Result<$int_type, $int_type> {
3171                // SAFETY: data races are prevented by atomic intrinsics.
3172                unsafe { atomic_compare_exchange(self.v.get(), current, new, success, failure) }
3173            }
3174
3175            /// Stores a value into the atomic integer if the current value is the same as
3176            /// the `current` value.
3177            ///
3178            #[doc = concat!("Unlike [`", stringify!($atomic_type), "::compare_exchange`],")]
3179            /// this function is allowed to spuriously fail even
3180            /// when the comparison succeeds, which can result in more efficient code on some
3181            /// platforms. The return value is a result indicating whether the new value was
3182            /// written and containing the previous value.
3183            ///
3184            /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
3185            /// ordering of this operation. `success` describes the required ordering for the
3186            /// read-modify-write operation that takes place if the comparison with `current` succeeds.
3187            /// `failure` describes the required ordering for the load operation that takes place when
3188            /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
3189            /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
3190            /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3191            ///
3192            /// **Note**: This method is only available on platforms that support atomic operations on
3193            #[doc = concat!("[`", $s_int_type, "`].")]
3194            ///
3195            /// # Examples
3196            ///
3197            /// ```
3198            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3199            ///
3200            #[doc = concat!("let val = ", stringify!($atomic_type), "::new(4);")]
3201            ///
3202            /// let mut old = val.load(Ordering::Relaxed);
3203            /// loop {
3204            ///     let new = old * 2;
3205            ///     match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
3206            ///         Ok(_) => break,
3207            ///         Err(x) => old = x,
3208            ///     }
3209            /// }
3210            /// ```
3211            ///
3212            /// # Considerations
3213            ///
3214            /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
3215            /// of CAS operations. In particular, a load of the value followed by a successful
3216            /// `compare_exchange` with the previous load *does not ensure* that other threads have not
3217            /// changed the value in the interim. This is usually important when the *equality* check in
3218            /// the `compare_exchange` is being used to check the *identity* of a value, but equality
3219            /// does not necessarily imply identity. This is a particularly common case for pointers, as
3220            /// a pointer holding the same address does not imply that the same object exists at that
3221            /// address! In this case, `compare_exchange` can lead to the [ABA problem].
3222            ///
3223            /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3224            /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3225            #[inline]
3226            #[$stable_cxchg]
3227            #[$cfg_cas]
3228            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3229            #[rustc_should_not_be_called_on_const_items]
3230            pub fn compare_exchange_weak(&self,
3231                                         current: $int_type,
3232                                         new: $int_type,
3233                                         success: Ordering,
3234                                         failure: Ordering) -> Result<$int_type, $int_type> {
3235                // SAFETY: data races are prevented by atomic intrinsics.
3236                unsafe {
3237                    atomic_compare_exchange_weak(self.v.get(), current, new, success, failure)
3238                }
3239            }
3240
3241            /// Adds to the current value, returning the previous value.
3242            ///
3243            /// This operation wraps around on overflow.
3244            ///
3245            /// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
3246            /// of this operation. All ordering modes are possible. Note that using
3247            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3248            /// using [`Release`] makes the load part [`Relaxed`].
3249            ///
3250            /// **Note**: This method is only available on platforms that support atomic operations on
3251            #[doc = concat!("[`", $s_int_type, "`].")]
3252            ///
3253            /// # Examples
3254            ///
3255            /// ```
3256            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3257            ///
3258            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0);")]
3259            /// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
3260            /// assert_eq!(foo.load(Ordering::SeqCst), 10);
3261            /// ```
3262            #[inline]
3263            #[$stable]
3264            #[$cfg_cas]
3265            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3266            #[rustc_should_not_be_called_on_const_items]
3267            pub fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type {
3268                // SAFETY: data races are prevented by atomic intrinsics.
3269                unsafe { atomic_add(self.v.get(), val, order) }
3270            }
3271
3272            /// Subtracts from the current value, returning the previous value.
3273            ///
3274            /// This operation wraps around on overflow.
3275            ///
3276            /// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
3277            /// of this operation. All ordering modes are possible. Note that using
3278            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3279            /// using [`Release`] makes the load part [`Relaxed`].
3280            ///
3281            /// **Note**: This method is only available on platforms that support atomic operations on
3282            #[doc = concat!("[`", $s_int_type, "`].")]
3283            ///
3284            /// # Examples
3285            ///
3286            /// ```
3287            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3288            ///
3289            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(20);")]
3290            /// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
3291            /// assert_eq!(foo.load(Ordering::SeqCst), 10);
3292            /// ```
3293            #[inline]
3294            #[$stable]
3295            #[$cfg_cas]
3296            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3297            #[rustc_should_not_be_called_on_const_items]
3298            pub fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type {
3299                // SAFETY: data races are prevented by atomic intrinsics.
3300                unsafe { atomic_sub(self.v.get(), val, order) }
3301            }
3302
3303            /// Bitwise "and" with the current value.
3304            ///
3305            /// Performs a bitwise "and" operation on the current value and the argument `val`, and
3306            /// sets the new value to the result.
3307            ///
3308            /// Returns the previous value.
3309            ///
3310            /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
3311            /// of this operation. All ordering modes are possible. Note that using
3312            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3313            /// using [`Release`] makes the load part [`Relaxed`].
3314            ///
3315            /// **Note**: This method is only available on platforms that support atomic operations on
3316            #[doc = concat!("[`", $s_int_type, "`].")]
3317            ///
3318            /// # Examples
3319            ///
3320            /// ```
3321            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3322            ///
3323            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3324            /// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
3325            /// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
3326            /// ```
3327            #[inline]
3328            #[$stable]
3329            #[$cfg_cas]
3330            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3331            #[rustc_should_not_be_called_on_const_items]
3332            pub fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type {
3333                // SAFETY: data races are prevented by atomic intrinsics.
3334                unsafe { atomic_and(self.v.get(), val, order) }
3335            }
3336
3337            /// Bitwise "nand" with the current value.
3338            ///
3339            /// Performs a bitwise "nand" operation on the current value and the argument `val`, and
3340            /// sets the new value to the result.
3341            ///
3342            /// Returns the previous value.
3343            ///
3344            /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
3345            /// of this operation. All ordering modes are possible. Note that using
3346            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3347            /// using [`Release`] makes the load part [`Relaxed`].
3348            ///
3349            /// **Note**: This method is only available on platforms that support atomic operations on
3350            #[doc = concat!("[`", $s_int_type, "`].")]
3351            ///
3352            /// # Examples
3353            ///
3354            /// ```
3355            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3356            ///
3357            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0x13);")]
3358            /// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
3359            /// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
3360            /// ```
3361            #[inline]
3362            #[$stable_nand]
3363            #[$cfg_cas]
3364            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3365            #[rustc_should_not_be_called_on_const_items]
3366            pub fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type {
3367                // SAFETY: data races are prevented by atomic intrinsics.
3368                unsafe { atomic_nand(self.v.get(), val, order) }
3369            }
3370
3371            /// Bitwise "or" with the current value.
3372            ///
3373            /// Performs a bitwise "or" operation on the current value and the argument `val`, and
3374            /// sets the new value to the result.
3375            ///
3376            /// Returns the previous value.
3377            ///
3378            /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
3379            /// of this operation. All ordering modes are possible. Note that using
3380            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3381            /// using [`Release`] makes the load part [`Relaxed`].
3382            ///
3383            /// **Note**: This method is only available on platforms that support atomic operations on
3384            #[doc = concat!("[`", $s_int_type, "`].")]
3385            ///
3386            /// # Examples
3387            ///
3388            /// ```
3389            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3390            ///
3391            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3392            /// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
3393            /// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
3394            /// ```
3395            #[inline]
3396            #[$stable]
3397            #[$cfg_cas]
3398            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3399            #[rustc_should_not_be_called_on_const_items]
3400            pub fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type {
3401                // SAFETY: data races are prevented by atomic intrinsics.
3402                unsafe { atomic_or(self.v.get(), val, order) }
3403            }
3404
3405            /// Bitwise "xor" with the current value.
3406            ///
3407            /// Performs a bitwise "xor" operation on the current value and the argument `val`, and
3408            /// sets the new value to the result.
3409            ///
3410            /// Returns the previous value.
3411            ///
3412            /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
3413            /// of this operation. All ordering modes are possible. Note that using
3414            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3415            /// using [`Release`] makes the load part [`Relaxed`].
3416            ///
3417            /// **Note**: This method is only available on platforms that support atomic operations on
3418            #[doc = concat!("[`", $s_int_type, "`].")]
3419            ///
3420            /// # Examples
3421            ///
3422            /// ```
3423            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3424            ///
3425            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3426            /// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
3427            /// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
3428            /// ```
3429            #[inline]
3430            #[$stable]
3431            #[$cfg_cas]
3432            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3433            #[rustc_should_not_be_called_on_const_items]
3434            pub fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type {
3435                // SAFETY: data races are prevented by atomic intrinsics.
3436                unsafe { atomic_xor(self.v.get(), val, order) }
3437            }
3438
3439            /// Fetches the value, and applies a function to it that returns an optional
3440            /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
3441            /// `Err(previous_value)`.
3442            ///
3443            /// Note: This may call the function multiple times if the value has been changed from other threads in
3444            /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
3445            /// only once to the stored value.
3446            ///
3447            /// `fetch_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3448            /// The first describes the required ordering for when the operation finally succeeds while the second
3449            /// describes the required ordering for loads. These correspond to the success and failure orderings of
3450            #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3451            /// respectively.
3452            ///
3453            /// Using [`Acquire`] as success ordering makes the store part
3454            /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3455            /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3456            ///
3457            /// **Note**: This method is only available on platforms that support atomic operations on
3458            #[doc = concat!("[`", $s_int_type, "`].")]
3459            ///
3460            /// # Considerations
3461            ///
3462            /// This method is not magic; it is not provided by the hardware, and does not act like a
3463            /// critical section or mutex.
3464            ///
3465            /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3466            /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3467            /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3468            /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3469            ///
3470            /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3471            /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3472            ///
3473            /// # Examples
3474            ///
3475            /// ```rust
3476            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3477            ///
3478            #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3479            /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
3480            /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
3481            /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
3482            /// assert_eq!(x.load(Ordering::SeqCst), 9);
3483            /// ```
3484            #[inline]
3485            #[stable(feature = "no_more_cas", since = "1.45.0")]
3486            #[$cfg_cas]
3487            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3488            #[rustc_should_not_be_called_on_const_items]
3489            pub fn fetch_update<F>(&self,
3490                                   set_order: Ordering,
3491                                   fetch_order: Ordering,
3492                                   mut f: F) -> Result<$int_type, $int_type>
3493            where F: FnMut($int_type) -> Option<$int_type> {
3494                let mut prev = self.load(fetch_order);
3495                while let Some(next) = f(prev) {
3496                    match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
3497                        x @ Ok(_) => return x,
3498                        Err(next_prev) => prev = next_prev
3499                    }
3500                }
3501                Err(prev)
3502            }
3503
3504            /// Fetches the value, and applies a function to it that returns an optional
3505            /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
3506            /// `Err(previous_value)`.
3507            ///
3508            #[doc = concat!("See also: [`update`](`", stringify!($atomic_type), "::update`).")]
3509            ///
3510            /// Note: This may call the function multiple times if the value has been changed from other threads in
3511            /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
3512            /// only once to the stored value.
3513            ///
3514            /// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3515            /// The first describes the required ordering for when the operation finally succeeds while the second
3516            /// describes the required ordering for loads. These correspond to the success and failure orderings of
3517            #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3518            /// respectively.
3519            ///
3520            /// Using [`Acquire`] as success ordering makes the store part
3521            /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3522            /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3523            ///
3524            /// **Note**: This method is only available on platforms that support atomic operations on
3525            #[doc = concat!("[`", $s_int_type, "`].")]
3526            ///
3527            /// # Considerations
3528            ///
3529            /// This method is not magic; it is not provided by the hardware, and does not act like a
3530            /// critical section or mutex.
3531            ///
3532            /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3533            /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3534            /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3535            /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3536            ///
3537            /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3538            /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3539            ///
3540            /// # Examples
3541            ///
3542            /// ```rust
3543            /// #![feature(atomic_try_update)]
3544            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3545            ///
3546            #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3547            /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
3548            /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
3549            /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
3550            /// assert_eq!(x.load(Ordering::SeqCst), 9);
3551            /// ```
3552            #[inline]
3553            #[unstable(feature = "atomic_try_update", issue = "135894")]
3554            #[$cfg_cas]
3555            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3556            #[rustc_should_not_be_called_on_const_items]
3557            pub fn try_update(
3558                &self,
3559                set_order: Ordering,
3560                fetch_order: Ordering,
3561                f: impl FnMut($int_type) -> Option<$int_type>,
3562            ) -> Result<$int_type, $int_type> {
3563                // FIXME(atomic_try_update): this is currently an unstable alias to `fetch_update`;
3564                //      when stabilizing, turn `fetch_update` into a deprecated alias to `try_update`.
3565                self.fetch_update(set_order, fetch_order, f)
3566            }
3567
3568            /// Fetches the value, applies a function to it that it return a new value.
3569            /// The new value is stored and the old value is returned.
3570            ///
3571            #[doc = concat!("See also: [`try_update`](`", stringify!($atomic_type), "::try_update`).")]
3572            ///
3573            /// Note: This may call the function multiple times if the value has been changed from other threads in
3574            /// the meantime, but the function will have been applied only once to the stored value.
3575            ///
3576            /// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3577            /// The first describes the required ordering for when the operation finally succeeds while the second
3578            /// describes the required ordering for loads. These correspond to the success and failure orderings of
3579            #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3580            /// respectively.
3581            ///
3582            /// Using [`Acquire`] as success ordering makes the store part
3583            /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3584            /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3585            ///
3586            /// **Note**: This method is only available on platforms that support atomic operations on
3587            #[doc = concat!("[`", $s_int_type, "`].")]
3588            ///
3589            /// # Considerations
3590            ///
3591            /// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3592            /// This method is not magic; it is not provided by the hardware, and does not act like a
3593            /// critical section or mutex.
3594            ///
3595            /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3596            /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3597            /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3598            /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3599            ///
3600            /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3601            /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3602            ///
3603            /// # Examples
3604            ///
3605            /// ```rust
3606            /// #![feature(atomic_try_update)]
3607            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3608            ///
3609            #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3610            /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
3611            /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
3612            /// assert_eq!(x.load(Ordering::SeqCst), 9);
3613            /// ```
3614            #[inline]
3615            #[unstable(feature = "atomic_try_update", issue = "135894")]
3616            #[$cfg_cas]
3617            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3618            #[rustc_should_not_be_called_on_const_items]
3619            pub fn update(
3620                &self,
3621                set_order: Ordering,
3622                fetch_order: Ordering,
3623                mut f: impl FnMut($int_type) -> $int_type,
3624            ) -> $int_type {
3625                let mut prev = self.load(fetch_order);
3626                loop {
3627                    match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
3628                        Ok(x) => break x,
3629                        Err(next_prev) => prev = next_prev,
3630                    }
3631                }
3632            }
3633
3634            /// Maximum with the current value.
3635            ///
3636            /// Finds the maximum of the current value and the argument `val`, and
3637            /// sets the new value to the result.
3638            ///
3639            /// Returns the previous value.
3640            ///
3641            /// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
3642            /// of this operation. All ordering modes are possible. Note that using
3643            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3644            /// using [`Release`] makes the load part [`Relaxed`].
3645            ///
3646            /// **Note**: This method is only available on platforms that support atomic operations on
3647            #[doc = concat!("[`", $s_int_type, "`].")]
3648            ///
3649            /// # Examples
3650            ///
3651            /// ```
3652            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3653            ///
3654            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3655            /// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
3656            /// assert_eq!(foo.load(Ordering::SeqCst), 42);
3657            /// ```
3658            ///
3659            /// If you want to obtain the maximum value in one step, you can use the following:
3660            ///
3661            /// ```
3662            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3663            ///
3664            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3665            /// let bar = 42;
3666            /// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
3667            /// assert!(max_foo == 42);
3668            /// ```
3669            #[inline]
3670            #[stable(feature = "atomic_min_max", since = "1.45.0")]
3671            #[$cfg_cas]
3672            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3673            #[rustc_should_not_be_called_on_const_items]
3674            pub fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type {
3675                // SAFETY: data races are prevented by atomic intrinsics.
3676                unsafe { $max_fn(self.v.get(), val, order) }
3677            }
3678
3679            /// Minimum with the current value.
3680            ///
3681            /// Finds the minimum of the current value and the argument `val`, and
3682            /// sets the new value to the result.
3683            ///
3684            /// Returns the previous value.
3685            ///
3686            /// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
3687            /// of this operation. All ordering modes are possible. Note that using
3688            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3689            /// using [`Release`] makes the load part [`Relaxed`].
3690            ///
3691            /// **Note**: This method is only available on platforms that support atomic operations on
3692            #[doc = concat!("[`", $s_int_type, "`].")]
3693            ///
3694            /// # Examples
3695            ///
3696            /// ```
3697            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3698            ///
3699            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3700            /// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
3701            /// assert_eq!(foo.load(Ordering::Relaxed), 23);
3702            /// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
3703            /// assert_eq!(foo.load(Ordering::Relaxed), 22);
3704            /// ```
3705            ///
3706            /// If you want to obtain the minimum value in one step, you can use the following:
3707            ///
3708            /// ```
3709            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3710            ///
3711            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3712            /// let bar = 12;
3713            /// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
3714            /// assert_eq!(min_foo, 12);
3715            /// ```
3716            #[inline]
3717            #[stable(feature = "atomic_min_max", since = "1.45.0")]
3718            #[$cfg_cas]
3719            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3720            #[rustc_should_not_be_called_on_const_items]
3721            pub fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type {
3722                // SAFETY: data races are prevented by atomic intrinsics.
3723                unsafe { $min_fn(self.v.get(), val, order) }
3724            }
3725
3726            /// Returns a mutable pointer to the underlying integer.
3727            ///
3728            /// Doing non-atomic reads and writes on the resulting integer can be a data race.
3729            /// This method is mostly useful for FFI, where the function signature may use
3730            #[doc = concat!("`*mut ", stringify!($int_type), "` instead of `&", stringify!($atomic_type), "`.")]
3731            ///
3732            /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
3733            /// atomic types work with interior mutability. All modifications of an atomic change the value
3734            /// through a shared reference, and can do so safely as long as they use atomic operations. Any
3735            /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
3736            /// requirements of the [memory model].
3737            ///
3738            /// # Examples
3739            ///
3740            /// ```ignore (extern-declaration)
3741            /// # fn main() {
3742            #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
3743            ///
3744            /// extern "C" {
3745            #[doc = concat!("    fn my_atomic_op(arg: *mut ", stringify!($int_type), ");")]
3746            /// }
3747            ///
3748            #[doc = concat!("let atomic = ", stringify!($atomic_type), "::new(1);")]
3749            ///
3750            /// // SAFETY: Safe as long as `my_atomic_op` is atomic.
3751            /// unsafe {
3752            ///     my_atomic_op(atomic.as_ptr());
3753            /// }
3754            /// # }
3755            /// ```
3756            ///
3757            /// [memory model]: self#memory-model-for-atomic-accesses
3758            #[inline]
3759            #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
3760            #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
3761            #[rustc_never_returns_null_ptr]
3762            pub const fn as_ptr(&self) -> *mut $int_type {
3763                self.v.get()
3764            }
3765        }
3766    }
3767}
3768
3769#[cfg(target_has_atomic_load_store = "8")]
3770#[cfg(not(feature = "ferrocene_subset"))]
3771atomic_int! {
3772    cfg(target_has_atomic = "8"),
3773    cfg(target_has_atomic_equal_alignment = "8"),
3774    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3775    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3776    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3777    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3778    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3779    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3780    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3781    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3782    rustc_diagnostic_item = "AtomicI8",
3783    "i8",
3784    "",
3785    atomic_min, atomic_max,
3786    1,
3787    i8 AtomicI8
3788}
3789#[cfg(target_has_atomic_load_store = "8")]
3790atomic_int! {
3791    cfg(target_has_atomic = "8"),
3792    cfg(target_has_atomic_equal_alignment = "8"),
3793    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3794    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3795    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3796    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3797    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3798    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3799    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3800    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3801    rustc_diagnostic_item = "AtomicU8",
3802    "u8",
3803    "",
3804    atomic_umin, atomic_umax,
3805    1,
3806    u8 AtomicU8
3807}
3808#[cfg(target_has_atomic_load_store = "16")]
3809#[cfg(not(feature = "ferrocene_subset"))]
3810atomic_int! {
3811    cfg(target_has_atomic = "16"),
3812    cfg(target_has_atomic_equal_alignment = "16"),
3813    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3814    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3815    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3816    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3817    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3818    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3819    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3820    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3821    rustc_diagnostic_item = "AtomicI16",
3822    "i16",
3823    "",
3824    atomic_min, atomic_max,
3825    2,
3826    i16 AtomicI16
3827}
3828#[cfg(target_has_atomic_load_store = "16")]
3829atomic_int! {
3830    cfg(target_has_atomic = "16"),
3831    cfg(target_has_atomic_equal_alignment = "16"),
3832    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3833    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3834    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3835    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3836    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3837    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3838    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3839    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3840    rustc_diagnostic_item = "AtomicU16",
3841    "u16",
3842    "",
3843    atomic_umin, atomic_umax,
3844    2,
3845    u16 AtomicU16
3846}
3847#[cfg(target_has_atomic_load_store = "32")]
3848#[cfg(not(feature = "ferrocene_subset"))]
3849atomic_int! {
3850    cfg(target_has_atomic = "32"),
3851    cfg(target_has_atomic_equal_alignment = "32"),
3852    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3853    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3854    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3855    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3856    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3857    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3858    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3859    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3860    rustc_diagnostic_item = "AtomicI32",
3861    "i32",
3862    "",
3863    atomic_min, atomic_max,
3864    4,
3865    i32 AtomicI32
3866}
3867#[cfg(target_has_atomic_load_store = "32")]
3868atomic_int! {
3869    cfg(target_has_atomic = "32"),
3870    cfg(target_has_atomic_equal_alignment = "32"),
3871    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3872    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3873    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3874    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3875    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3876    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3877    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3878    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3879    rustc_diagnostic_item = "AtomicU32",
3880    "u32",
3881    "",
3882    atomic_umin, atomic_umax,
3883    4,
3884    u32 AtomicU32
3885}
3886#[cfg(target_has_atomic_load_store = "64")]
3887#[cfg(not(feature = "ferrocene_subset"))]
3888atomic_int! {
3889    cfg(target_has_atomic = "64"),
3890    cfg(target_has_atomic_equal_alignment = "64"),
3891    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3892    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3893    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3894    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3895    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3896    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3897    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3898    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3899    rustc_diagnostic_item = "AtomicI64",
3900    "i64",
3901    "",
3902    atomic_min, atomic_max,
3903    8,
3904    i64 AtomicI64
3905}
3906#[cfg(target_has_atomic_load_store = "64")]
3907atomic_int! {
3908    cfg(target_has_atomic = "64"),
3909    cfg(target_has_atomic_equal_alignment = "64"),
3910    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3911    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3912    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3913    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3914    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3915    stable(feature = "integer_atomics_stable", since = "1.34.0"),
3916    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3917    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3918    rustc_diagnostic_item = "AtomicU64",
3919    "u64",
3920    "",
3921    atomic_umin, atomic_umax,
3922    8,
3923    u64 AtomicU64
3924}
3925#[cfg(target_has_atomic_load_store = "128")]
3926#[cfg(not(feature = "ferrocene_subset"))]
3927atomic_int! {
3928    cfg(target_has_atomic = "128"),
3929    cfg(target_has_atomic_equal_alignment = "128"),
3930    unstable(feature = "integer_atomics", issue = "99069"),
3931    unstable(feature = "integer_atomics", issue = "99069"),
3932    unstable(feature = "integer_atomics", issue = "99069"),
3933    unstable(feature = "integer_atomics", issue = "99069"),
3934    unstable(feature = "integer_atomics", issue = "99069"),
3935    unstable(feature = "integer_atomics", issue = "99069"),
3936    rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3937    rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3938    rustc_diagnostic_item = "AtomicI128",
3939    "i128",
3940    "#![feature(integer_atomics)]\n\n",
3941    atomic_min, atomic_max,
3942    16,
3943    i128 AtomicI128
3944}
3945#[cfg(target_has_atomic_load_store = "128")]
3946#[cfg(not(feature = "ferrocene_subset"))]
3947atomic_int! {
3948    cfg(target_has_atomic = "128"),
3949    cfg(target_has_atomic_equal_alignment = "128"),
3950    unstable(feature = "integer_atomics", issue = "99069"),
3951    unstable(feature = "integer_atomics", issue = "99069"),
3952    unstable(feature = "integer_atomics", issue = "99069"),
3953    unstable(feature = "integer_atomics", issue = "99069"),
3954    unstable(feature = "integer_atomics", issue = "99069"),
3955    unstable(feature = "integer_atomics", issue = "99069"),
3956    rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3957    rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3958    rustc_diagnostic_item = "AtomicU128",
3959    "u128",
3960    "#![feature(integer_atomics)]\n\n",
3961    atomic_umin, atomic_umax,
3962    16,
3963    u128 AtomicU128
3964}
3965
3966#[cfg(target_has_atomic_load_store = "ptr")]
3967macro_rules! atomic_int_ptr_sized {
3968    ( $($target_pointer_width:literal $align:literal)* ) => { $(
3969        #[cfg(target_pointer_width = $target_pointer_width)]
3970        #[cfg(not(feature = "ferrocene_subset"))]
3971        atomic_int! {
3972            cfg(target_has_atomic = "ptr"),
3973            cfg(target_has_atomic_equal_alignment = "ptr"),
3974            stable(feature = "rust1", since = "1.0.0"),
3975            stable(feature = "extended_compare_and_swap", since = "1.10.0"),
3976            stable(feature = "atomic_debug", since = "1.3.0"),
3977            stable(feature = "atomic_access", since = "1.15.0"),
3978            stable(feature = "atomic_from", since = "1.23.0"),
3979            stable(feature = "atomic_nand", since = "1.27.0"),
3980            rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
3981            rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3982            rustc_diagnostic_item = "AtomicIsize",
3983            "isize",
3984            "",
3985            atomic_min, atomic_max,
3986            $align,
3987            isize AtomicIsize
3988        }
3989        #[cfg(target_pointer_width = $target_pointer_width)]
3990        atomic_int! {
3991            cfg(target_has_atomic = "ptr"),
3992            cfg(target_has_atomic_equal_alignment = "ptr"),
3993            stable(feature = "rust1", since = "1.0.0"),
3994            stable(feature = "extended_compare_and_swap", since = "1.10.0"),
3995            stable(feature = "atomic_debug", since = "1.3.0"),
3996            stable(feature = "atomic_access", since = "1.15.0"),
3997            stable(feature = "atomic_from", since = "1.23.0"),
3998            stable(feature = "atomic_nand", since = "1.27.0"),
3999            rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
4000            rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
4001            rustc_diagnostic_item = "AtomicUsize",
4002            "usize",
4003            "",
4004            atomic_umin, atomic_umax,
4005            $align,
4006            usize AtomicUsize
4007        }
4008
4009        /// An [`AtomicIsize`] initialized to `0`.
4010        #[cfg(target_pointer_width = $target_pointer_width)]
4011        #[stable(feature = "rust1", since = "1.0.0")]
4012        #[deprecated(
4013            since = "1.34.0",
4014            note = "the `new` function is now preferred",
4015            suggestion = "AtomicIsize::new(0)",
4016        )]
4017        #[cfg(not(feature = "ferrocene_subset"))]
4018        pub const ATOMIC_ISIZE_INIT: AtomicIsize = AtomicIsize::new(0);
4019
4020        /// An [`AtomicUsize`] initialized to `0`.
4021        #[cfg(target_pointer_width = $target_pointer_width)]
4022        #[stable(feature = "rust1", since = "1.0.0")]
4023        #[deprecated(
4024            since = "1.34.0",
4025            note = "the `new` function is now preferred",
4026            suggestion = "AtomicUsize::new(0)",
4027        )]
4028        pub const ATOMIC_USIZE_INIT: AtomicUsize = AtomicUsize::new(0);
4029    )* };
4030}
4031
4032#[cfg(target_has_atomic_load_store = "ptr")]
4033atomic_int_ptr_sized! {
4034    "16" 2
4035    "32" 4
4036    "64" 8
4037}
4038
4039#[inline]
4040#[cfg(target_has_atomic)]
4041fn strongest_failure_ordering(order: Ordering) -> Ordering {
4042    match order {
4043        Release => Relaxed,
4044        Relaxed => Relaxed,
4045        SeqCst => SeqCst,
4046        Acquire => Acquire,
4047        AcqRel => Acquire,
4048    }
4049}
4050
4051#[inline]
4052#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4053unsafe fn atomic_store<T: Copy>(dst: *mut T, val: T, order: Ordering) {
4054    // SAFETY: the caller must uphold the safety contract for `atomic_store`.
4055    unsafe {
4056        match order {
4057            Relaxed => intrinsics::atomic_store::<T, { AO::Relaxed }>(dst, val),
4058            Release => intrinsics::atomic_store::<T, { AO::Release }>(dst, val),
4059            SeqCst => intrinsics::atomic_store::<T, { AO::SeqCst }>(dst, val),
4060            Acquire => panic!("there is no such thing as an acquire store"),
4061            AcqRel => panic!("there is no such thing as an acquire-release store"),
4062        }
4063    }
4064}
4065
4066#[inline]
4067#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4068unsafe fn atomic_load<T: Copy>(dst: *const T, order: Ordering) -> T {
4069    // SAFETY: the caller must uphold the safety contract for `atomic_load`.
4070    unsafe {
4071        match order {
4072            Relaxed => intrinsics::atomic_load::<T, { AO::Relaxed }>(dst),
4073            Acquire => intrinsics::atomic_load::<T, { AO::Acquire }>(dst),
4074            SeqCst => intrinsics::atomic_load::<T, { AO::SeqCst }>(dst),
4075            Release => panic!("there is no such thing as a release load"),
4076            AcqRel => panic!("there is no such thing as an acquire-release load"),
4077        }
4078    }
4079}
4080
4081#[inline]
4082#[cfg(target_has_atomic)]
4083#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4084unsafe fn atomic_swap<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4085    // SAFETY: the caller must uphold the safety contract for `atomic_swap`.
4086    unsafe {
4087        match order {
4088            Relaxed => intrinsics::atomic_xchg::<T, { AO::Relaxed }>(dst, val),
4089            Acquire => intrinsics::atomic_xchg::<T, { AO::Acquire }>(dst, val),
4090            Release => intrinsics::atomic_xchg::<T, { AO::Release }>(dst, val),
4091            AcqRel => intrinsics::atomic_xchg::<T, { AO::AcqRel }>(dst, val),
4092            SeqCst => intrinsics::atomic_xchg::<T, { AO::SeqCst }>(dst, val),
4093        }
4094    }
4095}
4096
4097/// Returns the previous value (like __sync_fetch_and_add).
4098#[inline]
4099#[cfg(target_has_atomic)]
4100#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4101unsafe fn atomic_add<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4102    // SAFETY: the caller must uphold the safety contract for `atomic_add`.
4103    unsafe {
4104        match order {
4105            Relaxed => intrinsics::atomic_xadd::<T, U, { AO::Relaxed }>(dst, val),
4106            Acquire => intrinsics::atomic_xadd::<T, U, { AO::Acquire }>(dst, val),
4107            Release => intrinsics::atomic_xadd::<T, U, { AO::Release }>(dst, val),
4108            AcqRel => intrinsics::atomic_xadd::<T, U, { AO::AcqRel }>(dst, val),
4109            SeqCst => intrinsics::atomic_xadd::<T, U, { AO::SeqCst }>(dst, val),
4110        }
4111    }
4112}
4113
4114/// Returns the previous value (like __sync_fetch_and_sub).
4115#[inline]
4116#[cfg(target_has_atomic)]
4117#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4118unsafe fn atomic_sub<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4119    // SAFETY: the caller must uphold the safety contract for `atomic_sub`.
4120    unsafe {
4121        match order {
4122            Relaxed => intrinsics::atomic_xsub::<T, U, { AO::Relaxed }>(dst, val),
4123            Acquire => intrinsics::atomic_xsub::<T, U, { AO::Acquire }>(dst, val),
4124            Release => intrinsics::atomic_xsub::<T, U, { AO::Release }>(dst, val),
4125            AcqRel => intrinsics::atomic_xsub::<T, U, { AO::AcqRel }>(dst, val),
4126            SeqCst => intrinsics::atomic_xsub::<T, U, { AO::SeqCst }>(dst, val),
4127        }
4128    }
4129}
4130
4131/// Publicly exposed for stdarch; nobody else should use this.
4132#[inline]
4133#[cfg(target_has_atomic)]
4134#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4135#[unstable(feature = "core_intrinsics", issue = "none")]
4136#[doc(hidden)]
4137pub unsafe fn atomic_compare_exchange<T: Copy>(
4138    dst: *mut T,
4139    old: T,
4140    new: T,
4141    success: Ordering,
4142    failure: Ordering,
4143) -> Result<T, T> {
4144    // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`.
4145    let (val, ok) = unsafe {
4146        match (success, failure) {
4147            (Relaxed, Relaxed) => {
4148                intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::Relaxed }>(dst, old, new)
4149            }
4150            (Relaxed, Acquire) => {
4151                intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::Acquire }>(dst, old, new)
4152            }
4153            (Relaxed, SeqCst) => {
4154                intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::SeqCst }>(dst, old, new)
4155            }
4156            (Acquire, Relaxed) => {
4157                intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::Relaxed }>(dst, old, new)
4158            }
4159            (Acquire, Acquire) => {
4160                intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::Acquire }>(dst, old, new)
4161            }
4162            (Acquire, SeqCst) => {
4163                intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::SeqCst }>(dst, old, new)
4164            }
4165            (Release, Relaxed) => {
4166                intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::Relaxed }>(dst, old, new)
4167            }
4168            (Release, Acquire) => {
4169                intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::Acquire }>(dst, old, new)
4170            }
4171            (Release, SeqCst) => {
4172                intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::SeqCst }>(dst, old, new)
4173            }
4174            (AcqRel, Relaxed) => {
4175                intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::Relaxed }>(dst, old, new)
4176            }
4177            (AcqRel, Acquire) => {
4178                intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::Acquire }>(dst, old, new)
4179            }
4180            (AcqRel, SeqCst) => {
4181                intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::SeqCst }>(dst, old, new)
4182            }
4183            (SeqCst, Relaxed) => {
4184                intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::Relaxed }>(dst, old, new)
4185            }
4186            (SeqCst, Acquire) => {
4187                intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::Acquire }>(dst, old, new)
4188            }
4189            (SeqCst, SeqCst) => {
4190                intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::SeqCst }>(dst, old, new)
4191            }
4192            (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
4193            (_, Release) => panic!("there is no such thing as a release failure ordering"),
4194        }
4195    };
4196    if ok { Ok(val) } else { Err(val) }
4197}
4198
4199#[inline]
4200#[cfg(target_has_atomic)]
4201#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4202unsafe fn atomic_compare_exchange_weak<T: Copy>(
4203    dst: *mut T,
4204    old: T,
4205    new: T,
4206    success: Ordering,
4207    failure: Ordering,
4208) -> Result<T, T> {
4209    // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`.
4210    let (val, ok) = unsafe {
4211        match (success, failure) {
4212            (Relaxed, Relaxed) => {
4213                intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::Relaxed }>(dst, old, new)
4214            }
4215            (Relaxed, Acquire) => {
4216                intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::Acquire }>(dst, old, new)
4217            }
4218            (Relaxed, SeqCst) => {
4219                intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::SeqCst }>(dst, old, new)
4220            }
4221            (Acquire, Relaxed) => {
4222                intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::Relaxed }>(dst, old, new)
4223            }
4224            (Acquire, Acquire) => {
4225                intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::Acquire }>(dst, old, new)
4226            }
4227            (Acquire, SeqCst) => {
4228                intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::SeqCst }>(dst, old, new)
4229            }
4230            (Release, Relaxed) => {
4231                intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::Relaxed }>(dst, old, new)
4232            }
4233            (Release, Acquire) => {
4234                intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::Acquire }>(dst, old, new)
4235            }
4236            (Release, SeqCst) => {
4237                intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::SeqCst }>(dst, old, new)
4238            }
4239            (AcqRel, Relaxed) => {
4240                intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::Relaxed }>(dst, old, new)
4241            }
4242            (AcqRel, Acquire) => {
4243                intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::Acquire }>(dst, old, new)
4244            }
4245            (AcqRel, SeqCst) => {
4246                intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::SeqCst }>(dst, old, new)
4247            }
4248            (SeqCst, Relaxed) => {
4249                intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::Relaxed }>(dst, old, new)
4250            }
4251            (SeqCst, Acquire) => {
4252                intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::Acquire }>(dst, old, new)
4253            }
4254            (SeqCst, SeqCst) => {
4255                intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::SeqCst }>(dst, old, new)
4256            }
4257            (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
4258            (_, Release) => panic!("there is no such thing as a release failure ordering"),
4259        }
4260    };
4261    if ok { Ok(val) } else { Err(val) }
4262}
4263
4264#[inline]
4265#[cfg(target_has_atomic)]
4266#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4267unsafe fn atomic_and<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4268    // SAFETY: the caller must uphold the safety contract for `atomic_and`
4269    unsafe {
4270        match order {
4271            Relaxed => intrinsics::atomic_and::<T, U, { AO::Relaxed }>(dst, val),
4272            Acquire => intrinsics::atomic_and::<T, U, { AO::Acquire }>(dst, val),
4273            Release => intrinsics::atomic_and::<T, U, { AO::Release }>(dst, val),
4274            AcqRel => intrinsics::atomic_and::<T, U, { AO::AcqRel }>(dst, val),
4275            SeqCst => intrinsics::atomic_and::<T, U, { AO::SeqCst }>(dst, val),
4276        }
4277    }
4278}
4279
4280#[inline]
4281#[cfg(target_has_atomic)]
4282#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4283unsafe fn atomic_nand<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4284    // SAFETY: the caller must uphold the safety contract for `atomic_nand`
4285    unsafe {
4286        match order {
4287            Relaxed => intrinsics::atomic_nand::<T, U, { AO::Relaxed }>(dst, val),
4288            Acquire => intrinsics::atomic_nand::<T, U, { AO::Acquire }>(dst, val),
4289            Release => intrinsics::atomic_nand::<T, U, { AO::Release }>(dst, val),
4290            AcqRel => intrinsics::atomic_nand::<T, U, { AO::AcqRel }>(dst, val),
4291            SeqCst => intrinsics::atomic_nand::<T, U, { AO::SeqCst }>(dst, val),
4292        }
4293    }
4294}
4295
4296#[inline]
4297#[cfg(target_has_atomic)]
4298#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4299unsafe fn atomic_or<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4300    // SAFETY: the caller must uphold the safety contract for `atomic_or`
4301    unsafe {
4302        match order {
4303            SeqCst => intrinsics::atomic_or::<T, U, { AO::SeqCst }>(dst, val),
4304            Acquire => intrinsics::atomic_or::<T, U, { AO::Acquire }>(dst, val),
4305            Release => intrinsics::atomic_or::<T, U, { AO::Release }>(dst, val),
4306            AcqRel => intrinsics::atomic_or::<T, U, { AO::AcqRel }>(dst, val),
4307            Relaxed => intrinsics::atomic_or::<T, U, { AO::Relaxed }>(dst, val),
4308        }
4309    }
4310}
4311
4312#[inline]
4313#[cfg(target_has_atomic)]
4314#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4315unsafe fn atomic_xor<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4316    // SAFETY: the caller must uphold the safety contract for `atomic_xor`
4317    unsafe {
4318        match order {
4319            SeqCst => intrinsics::atomic_xor::<T, U, { AO::SeqCst }>(dst, val),
4320            Acquire => intrinsics::atomic_xor::<T, U, { AO::Acquire }>(dst, val),
4321            Release => intrinsics::atomic_xor::<T, U, { AO::Release }>(dst, val),
4322            AcqRel => intrinsics::atomic_xor::<T, U, { AO::AcqRel }>(dst, val),
4323            Relaxed => intrinsics::atomic_xor::<T, U, { AO::Relaxed }>(dst, val),
4324        }
4325    }
4326}
4327
4328/// Updates `*dst` to the max value of `val` and the old value (signed comparison)
4329#[inline]
4330#[cfg(target_has_atomic)]
4331#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4332#[cfg(not(feature = "ferrocene_subset"))]
4333unsafe fn atomic_max<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4334    // SAFETY: the caller must uphold the safety contract for `atomic_max`
4335    unsafe {
4336        match order {
4337            Relaxed => intrinsics::atomic_max::<T, { AO::Relaxed }>(dst, val),
4338            Acquire => intrinsics::atomic_max::<T, { AO::Acquire }>(dst, val),
4339            Release => intrinsics::atomic_max::<T, { AO::Release }>(dst, val),
4340            AcqRel => intrinsics::atomic_max::<T, { AO::AcqRel }>(dst, val),
4341            SeqCst => intrinsics::atomic_max::<T, { AO::SeqCst }>(dst, val),
4342        }
4343    }
4344}
4345
4346/// Updates `*dst` to the min value of `val` and the old value (signed comparison)
4347#[inline]
4348#[cfg(target_has_atomic)]
4349#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4350#[cfg(not(feature = "ferrocene_subset"))]
4351unsafe fn atomic_min<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4352    // SAFETY: the caller must uphold the safety contract for `atomic_min`
4353    unsafe {
4354        match order {
4355            Relaxed => intrinsics::atomic_min::<T, { AO::Relaxed }>(dst, val),
4356            Acquire => intrinsics::atomic_min::<T, { AO::Acquire }>(dst, val),
4357            Release => intrinsics::atomic_min::<T, { AO::Release }>(dst, val),
4358            AcqRel => intrinsics::atomic_min::<T, { AO::AcqRel }>(dst, val),
4359            SeqCst => intrinsics::atomic_min::<T, { AO::SeqCst }>(dst, val),
4360        }
4361    }
4362}
4363
4364/// Updates `*dst` to the max value of `val` and the old value (unsigned comparison)
4365#[inline]
4366#[cfg(target_has_atomic)]
4367#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4368unsafe fn atomic_umax<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4369    // SAFETY: the caller must uphold the safety contract for `atomic_umax`
4370    unsafe {
4371        match order {
4372            Relaxed => intrinsics::atomic_umax::<T, { AO::Relaxed }>(dst, val),
4373            Acquire => intrinsics::atomic_umax::<T, { AO::Acquire }>(dst, val),
4374            Release => intrinsics::atomic_umax::<T, { AO::Release }>(dst, val),
4375            AcqRel => intrinsics::atomic_umax::<T, { AO::AcqRel }>(dst, val),
4376            SeqCst => intrinsics::atomic_umax::<T, { AO::SeqCst }>(dst, val),
4377        }
4378    }
4379}
4380
4381/// Updates `*dst` to the min value of `val` and the old value (unsigned comparison)
4382#[inline]
4383#[cfg(target_has_atomic)]
4384#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4385unsafe fn atomic_umin<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4386    // SAFETY: the caller must uphold the safety contract for `atomic_umin`
4387    unsafe {
4388        match order {
4389            Relaxed => intrinsics::atomic_umin::<T, { AO::Relaxed }>(dst, val),
4390            Acquire => intrinsics::atomic_umin::<T, { AO::Acquire }>(dst, val),
4391            Release => intrinsics::atomic_umin::<T, { AO::Release }>(dst, val),
4392            AcqRel => intrinsics::atomic_umin::<T, { AO::AcqRel }>(dst, val),
4393            SeqCst => intrinsics::atomic_umin::<T, { AO::SeqCst }>(dst, val),
4394        }
4395    }
4396}
4397
4398/// An atomic fence.
4399///
4400/// Fences create synchronization between themselves and atomic operations or fences in other
4401/// threads. To achieve this, a fence prevents the compiler and CPU from reordering certain types of
4402/// memory operations around it.
4403///
4404/// There are 3 different ways to use an atomic fence:
4405///
4406/// - atomic - fence synchronization: an atomic operation with (at least) [`Release`] ordering
4407///   semantics synchronizes with a fence with (at least) [`Acquire`] ordering semantics.
4408/// - fence - atomic synchronization: a fence with (at least) [`Release`] ordering semantics
4409///   synchronizes with an atomic operation with (at least) [`Acquire`] ordering semantics.
4410/// - fence - fence synchronization: a fence with (at least) [`Release`] ordering semantics
4411///   synchronizes with a fence with (at least) [`Acquire`] ordering semantics.
4412///
4413/// These 3 ways complement the regular, fence-less, atomic - atomic synchronization.
4414///
4415/// ## Atomic - Fence
4416///
4417/// An atomic operation on one thread will synchronize with a fence on another thread when:
4418///
4419/// -   on thread 1:
4420///     -   an atomic operation 'X' with (at least) [`Release`] ordering semantics on some atomic
4421///         object 'm',
4422///
4423/// -   is paired on thread 2 with:
4424///     -   an atomic read 'Y' with any order on 'm',
4425///     -   followed by a fence 'B' with (at least) [`Acquire`] ordering semantics.
4426///
4427/// This provides a happens-before dependence between X and B.
4428///
4429/// ```text
4430///     Thread 1                                          Thread 2
4431///
4432/// m.store(3, Release); X ---------
4433///                                |
4434///                                |
4435///                                -------------> Y  if m.load(Relaxed) == 3 {
4436///                                               B      fence(Acquire);
4437///                                                      ...
4438///                                                  }
4439/// ```
4440///
4441/// ## Fence - Atomic
4442///
4443/// A fence on one thread will synchronize with an atomic operation on another thread when:
4444///
4445/// -   on thread:
4446///     -   a fence 'A' with (at least) [`Release`] ordering semantics,
4447///     -   followed by an atomic write 'X' with any ordering on some atomic object 'm',
4448///
4449/// -   is paired on thread 2 with:
4450///     -   an atomic operation 'Y' with (at least) [`Acquire`] ordering semantics.
4451///
4452/// This provides a happens-before dependence between A and Y.
4453///
4454/// ```text
4455///     Thread 1                                          Thread 2
4456///
4457/// fence(Release);      A
4458/// m.store(3, Relaxed); X ---------
4459///                                |
4460///                                |
4461///                                -------------> Y  if m.load(Acquire) == 3 {
4462///                                                      ...
4463///                                                  }
4464/// ```
4465///
4466/// ## Fence - Fence
4467///
4468/// A fence on one thread will synchronize with a fence on another thread when:
4469///
4470/// -   on thread 1:
4471///     -   a fence 'A' which has (at least) [`Release`] ordering semantics,
4472///     -   followed by an atomic write 'X' with any ordering on some atomic object 'm',
4473///
4474/// -   is paired on thread 2 with:
4475///     -   an atomic read 'Y' with any ordering on 'm',
4476///     -   followed by a fence 'B' with (at least) [`Acquire`] ordering semantics.
4477///
4478/// This provides a happens-before dependence between A and B.
4479///
4480/// ```text
4481///     Thread 1                                          Thread 2
4482///
4483/// fence(Release);      A --------------
4484/// m.store(3, Relaxed); X ---------    |
4485///                                |    |
4486///                                |    |
4487///                                -------------> Y  if m.load(Relaxed) == 3 {
4488///                                     |-------> B      fence(Acquire);
4489///                                                      ...
4490///                                                  }
4491/// ```
4492///
4493/// ## Mandatory Atomic
4494///
4495/// Note that in the examples above, it is crucial that the access to `m` are atomic. Fences cannot
4496/// be used to establish synchronization between non-atomic accesses in different threads. However,
4497/// thanks to the happens-before relationship, any non-atomic access that happen-before the atomic
4498/// operation or fence with (at least) [`Release`] ordering semantics are now also properly
4499/// synchronized with any non-atomic accesses that happen-after the atomic operation or fence with
4500/// (at least) [`Acquire`] ordering semantics.
4501///
4502/// ## Memory Ordering
4503///
4504/// A fence which has [`SeqCst`] ordering, in addition to having both [`Acquire`] and [`Release`]
4505/// semantics, participates in the global program order of the other [`SeqCst`] operations and/or
4506/// fences.
4507///
4508/// Accepts [`Acquire`], [`Release`], [`AcqRel`] and [`SeqCst`] orderings.
4509///
4510/// # Panics
4511///
4512/// Panics if `order` is [`Relaxed`].
4513///
4514/// # Examples
4515///
4516/// ```
4517/// use std::sync::atomic::AtomicBool;
4518/// use std::sync::atomic::fence;
4519/// use std::sync::atomic::Ordering;
4520///
4521/// // A mutual exclusion primitive based on spinlock.
4522/// pub struct Mutex {
4523///     flag: AtomicBool,
4524/// }
4525///
4526/// impl Mutex {
4527///     pub fn new() -> Mutex {
4528///         Mutex {
4529///             flag: AtomicBool::new(false),
4530///         }
4531///     }
4532///
4533///     pub fn lock(&self) {
4534///         // Wait until the old value is `false`.
4535///         while self
4536///             .flag
4537///             .compare_exchange_weak(false, true, Ordering::Relaxed, Ordering::Relaxed)
4538///             .is_err()
4539///         {}
4540///         // This fence synchronizes-with store in `unlock`.
4541///         fence(Ordering::Acquire);
4542///     }
4543///
4544///     pub fn unlock(&self) {
4545///         self.flag.store(false, Ordering::Release);
4546///     }
4547/// }
4548/// ```
4549#[inline]
4550#[stable(feature = "rust1", since = "1.0.0")]
4551#[rustc_diagnostic_item = "fence"]
4552#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4553pub fn fence(order: Ordering) {
4554    // SAFETY: using an atomic fence is safe.
4555    unsafe {
4556        match order {
4557            Acquire => intrinsics::atomic_fence::<{ AO::Acquire }>(),
4558            Release => intrinsics::atomic_fence::<{ AO::Release }>(),
4559            AcqRel => intrinsics::atomic_fence::<{ AO::AcqRel }>(),
4560            SeqCst => intrinsics::atomic_fence::<{ AO::SeqCst }>(),
4561            Relaxed => panic!("there is no such thing as a relaxed fence"),
4562        }
4563    }
4564}
4565
4566/// A "compiler-only" atomic fence.
4567///
4568/// Like [`fence`], this function establishes synchronization with other atomic operations and
4569/// fences. However, unlike [`fence`], `compiler_fence` only establishes synchronization with
4570/// operations *in the same thread*. This may at first sound rather useless, since code within a
4571/// thread is typically already totally ordered and does not need any further synchronization.
4572/// However, there are cases where code can run on the same thread without being ordered:
4573/// - The most common case is that of a *signal handler*: a signal handler runs in the same thread
4574///   as the code it interrupted, but it is not ordered with respect to that code. `compiler_fence`
4575///   can be used to establish synchronization between a thread and its signal handler, the same way
4576///   that `fence` can be used to establish synchronization across threads.
4577/// - Similar situations can arise in embedded programming with interrupt handlers, or in custom
4578///   implementations of preemptive green threads. In general, `compiler_fence` can establish
4579///   synchronization with code that is guaranteed to run on the same hardware CPU.
4580///
4581/// See [`fence`] for how a fence can be used to achieve synchronization. Note that just like
4582/// [`fence`], synchronization still requires atomic operations to be used in both threads -- it is
4583/// not possible to perform synchronization entirely with fences and non-atomic operations.
4584///
4585/// `compiler_fence` does not emit any machine code, but restricts the kinds of memory re-ordering
4586/// the compiler is allowed to do. `compiler_fence` corresponds to [`atomic_signal_fence`] in C and
4587/// C++.
4588///
4589/// [`atomic_signal_fence`]: https://en.cppreference.com/w/cpp/atomic/atomic_signal_fence
4590///
4591/// # Panics
4592///
4593/// Panics if `order` is [`Relaxed`].
4594///
4595/// # Examples
4596///
4597/// Without the two `compiler_fence` calls, the read of `IMPORTANT_VARIABLE` in `signal_handler`
4598/// is *undefined behavior* due to a data race, despite everything happening in a single thread.
4599/// This is because the signal handler is considered to run concurrently with its associated
4600/// thread, and explicit synchronization is required to pass data between a thread and its
4601/// signal handler. The code below uses two `compiler_fence` calls to establish the usual
4602/// release-acquire synchronization pattern (see [`fence`] for an image).
4603///
4604/// ```
4605/// use std::sync::atomic::AtomicBool;
4606/// use std::sync::atomic::Ordering;
4607/// use std::sync::atomic::compiler_fence;
4608///
4609/// static mut IMPORTANT_VARIABLE: usize = 0;
4610/// static IS_READY: AtomicBool = AtomicBool::new(false);
4611///
4612/// fn main() {
4613///     unsafe { IMPORTANT_VARIABLE = 42 };
4614///     // Marks earlier writes as being released with future relaxed stores.
4615///     compiler_fence(Ordering::Release);
4616///     IS_READY.store(true, Ordering::Relaxed);
4617/// }
4618///
4619/// fn signal_handler() {
4620///     if IS_READY.load(Ordering::Relaxed) {
4621///         // Acquires writes that were released with relaxed stores that we read from.
4622///         compiler_fence(Ordering::Acquire);
4623///         assert_eq!(unsafe { IMPORTANT_VARIABLE }, 42);
4624///     }
4625/// }
4626/// ```
4627#[inline]
4628#[stable(feature = "compiler_fences", since = "1.21.0")]
4629#[rustc_diagnostic_item = "compiler_fence"]
4630#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4631pub fn compiler_fence(order: Ordering) {
4632    // SAFETY: using an atomic fence is safe.
4633    unsafe {
4634        match order {
4635            Acquire => intrinsics::atomic_singlethreadfence::<{ AO::Acquire }>(),
4636            Release => intrinsics::atomic_singlethreadfence::<{ AO::Release }>(),
4637            AcqRel => intrinsics::atomic_singlethreadfence::<{ AO::AcqRel }>(),
4638            SeqCst => intrinsics::atomic_singlethreadfence::<{ AO::SeqCst }>(),
4639            Relaxed => panic!("there is no such thing as a relaxed fence"),
4640        }
4641    }
4642}
4643
4644#[cfg(target_has_atomic_load_store = "8")]
4645#[stable(feature = "atomic_debug", since = "1.3.0")]
4646#[cfg(not(feature = "ferrocene_subset"))]
4647impl fmt::Debug for AtomicBool {
4648    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4649        fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
4650    }
4651}
4652
4653#[cfg(target_has_atomic_load_store = "ptr")]
4654#[stable(feature = "atomic_debug", since = "1.3.0")]
4655#[cfg(not(feature = "ferrocene_subset"))]
4656impl<T> fmt::Debug for AtomicPtr<T> {
4657    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4658        fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
4659    }
4660}
4661
4662#[cfg(target_has_atomic_load_store = "ptr")]
4663#[stable(feature = "atomic_pointer", since = "1.24.0")]
4664#[cfg(not(feature = "ferrocene_subset"))]
4665impl<T> fmt::Pointer for AtomicPtr<T> {
4666    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4667        fmt::Pointer::fmt(&self.load(Ordering::Relaxed), f)
4668    }
4669}
4670
4671/// Signals the processor that it is inside a busy-wait spin-loop ("spin lock").
4672///
4673/// This function is deprecated in favor of [`hint::spin_loop`].
4674///
4675/// [`hint::spin_loop`]: crate::hint::spin_loop
4676#[inline]
4677#[stable(feature = "spin_loop_hint", since = "1.24.0")]
4678#[deprecated(since = "1.51.0", note = "use hint::spin_loop instead")]
4679#[cfg(not(feature = "ferrocene_subset"))]
4680pub fn spin_loop_hint() {
4681    spin_loop()
4682}