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