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