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