Skip to main content

core/sync/
atomic.rs

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