Skip to main content

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