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