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