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
//! * ARM platforms like `armv5te` that aren't for Linux only provide `load`
134
//!   and `store` operations, and do not support Compare and Swap (CAS)
135
//!   operations, such as `swap`, `fetch_add`, etc. Additionally on Linux,
136
//!   these CAS operations are implemented via [operating system support], which
137
//!   may come with a performance penalty.
138
//! * ARM targets with `thumbv6m` only provide `load` and `store` operations,
139
//!   and do not support Compare and Swap (CAS) operations, such as `swap`,
140
//!   `fetch_add`, etc.
141
//!
142
//! [operating system support]: https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt
143
//!
144
//! Note that future platforms may be added that also do not have support for
145
//! some atomic operations. Maximally portable code will want to be careful
146
//! about which atomic types are used. `AtomicUsize` and `AtomicIsize` are
147
//! generally the most portable, but even then they're not available everywhere.
148
//! For reference, the `std` library requires `AtomicBool`s and pointer-sized atomics, although
149
//! `core` does not.
150
//!
151
//! The `#[cfg(target_has_atomic)]` attribute can be used to conditionally
152
//! compile based on the target's supported bit widths. It is a key-value
153
//! option set for each supported size, with values "8", "16", "32", "64",
154
//! "128", and "ptr" for pointer-sized atomics.
155
//!
156
//! [lock-free]: https://en.wikipedia.org/wiki/Non-blocking_algorithm
157
//!
158
//! # Atomic accesses to read-only memory
159
//!
160
//! In general, *all* atomic accesses on read-only memory are undefined behavior. For instance, attempting
161
//! to do a `compare_exchange` that will definitely fail (making it conceptually a read-only
162
//! operation) can still cause a segmentation fault if the underlying memory page is mapped read-only. Since
163
//! atomic `load`s might be implemented using compare-exchange operations, even a `load` can fault
164
//! on read-only memory.
165
//!
166
//! For the purpose of this section, "read-only memory" is defined as memory that is read-only in
167
//! the underlying target, i.e., the pages are mapped with a read-only flag and any attempt to write
168
//! will cause a page fault. In particular, an `&u128` reference that points to memory that is
169
//! read-write mapped is *not* considered to point to "read-only memory". In Rust, almost all memory
170
//! is read-write; the only exceptions are memory created by `const` items or `static` items without
171
//! interior mutability, and memory that was specifically marked as read-only by the operating
172
//! system via platform-specific APIs.
173
//!
174
//! As an exception from the general rule stated above, "sufficiently small" atomic loads with
175
//! `Ordering::Relaxed` are implemented in a way that works on read-only memory, and are hence not
176
//! undefined behavior. The exact size limit for what makes a load "sufficiently small" varies
177
//! depending on the target:
178
//!
179
//! | `target_arch` | Size limit |
180
//! |---------------|---------|
181
//! | `x86`, `arm`, `loongarch32`, `mips`, `mips32r6`, `powerpc`, `riscv32`, `sparc`, `hexagon` | 4 bytes |
182
//! | `x86_64`, `aarch64`, `loongarch64`, `mips64`, `mips64r6`, `powerpc64`, `riscv64`, `sparc64`, `s390x` | 8 bytes |
183
//!
184
//! Atomics loads that are larger than this limit as well as atomic loads with ordering other
185
//! than `Relaxed`, as well as *all* atomic loads on targets not listed in the table, might still be
186
//! read-only under certain conditions, but that is not a stable guarantee and should not be relied
187
//! upon.
188
//!
189
//! If you need to do an acquire load on read-only memory, you can do a relaxed load followed by an
190
//! acquire fence instead.
191
//!
192
//! # Examples
193
//!
194
//! A simple spinlock:
195
//!
196
//! ```ignore-wasm
197
//! use std::sync::Arc;
198
//! use std::sync::atomic::{AtomicUsize, Ordering};
199
//! use std::{hint, thread};
200
//!
201
//! fn main() {
202
//!     let spinlock = Arc::new(AtomicUsize::new(1));
203
//!
204
//!     let spinlock_clone = Arc::clone(&spinlock);
205
//!
206
//!     let thread = thread::spawn(move || {
207
//!         spinlock_clone.store(0, Ordering::Release);
208
//!     });
209
//!
210
//!     // Wait for the other thread to release the lock
211
//!     while spinlock.load(Ordering::Acquire) != 0 {
212
//!         hint::spin_loop();
213
//!     }
214
//!
215
//!     if let Err(panic) = thread.join() {
216
//!         println!("Thread had an error: {panic:?}");
217
//!     }
218
//! }
219
//! ```
220
//!
221
//! Keep a global count of live threads:
222
//!
223
//! ```
224
//! use std::sync::atomic::{AtomicUsize, Ordering};
225
//!
226
//! static GLOBAL_THREAD_COUNT: AtomicUsize = AtomicUsize::new(0);
227
//!
228
//! // Note that Relaxed ordering doesn't synchronize anything
229
//! // except the global thread counter itself.
230
//! let old_thread_count = GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::Relaxed);
231
//! // Note that this number may not be true at the moment of printing
232
//! // because some other thread may have changed static value already.
233
//! println!("live threads: {}", old_thread_count + 1);
234
//! ```
235

            
236
#![stable(feature = "rust1", since = "1.0.0")]
237
#![cfg_attr(not(target_has_atomic_load_store = "8"), allow(dead_code))]
238
#![cfg_attr(not(target_has_atomic_load_store = "8"), allow(unused_imports))]
239
#![rustc_diagnostic_item = "atomic_mod"]
240
// Clippy complains about the pattern of "safe function calling unsafe function taking pointers".
241
// This happens with AtomicPtr intrinsics but is fine, as the pointers clippy is concerned about
242
// are just normal values that get loaded/stored, but not dereferenced.
243
#![allow(clippy::not_unsafe_ptr_arg_deref)]
244

            
245
use self::Ordering::*;
246
use crate::cell::UnsafeCell;
247
#[cfg(not(feature = "ferrocene_certified"))]
248
use crate::hint::spin_loop;
249
#[cfg(feature = "ferrocene_certified")]
250
use crate::intrinsics;
251
use crate::intrinsics::AtomicOrdering as AO;
252
#[cfg(not(feature = "ferrocene_certified"))]
253
use crate::{fmt, intrinsics};
254

            
255
trait Sealed {}
256

            
257
/// A marker trait for primitive types which can be modified atomically.
258
///
259
/// This is an implementation detail for <code>[Atomic]\<T></code> which may disappear or be replaced at any time.
260
///
261
/// # Safety
262
///
263
/// Types implementing this trait must be primitives that can be modified atomically.
264
///
265
/// The associated `Self::AtomicInner` type must have the same size and bit validity as `Self`,
266
/// but may have a higher alignment requirement, so the following `transmute`s are sound:
267
///
268
/// - `&mut Self::AtomicInner` as `&mut Self`
269
/// - `Self` as `Self::AtomicInner` or the reverse
270
#[unstable(
271
    feature = "atomic_internals",
272
    reason = "implementation detail which may disappear or be replaced at any time",
273
    issue = "none"
274
)]
275
#[expect(private_bounds)]
276
pub unsafe trait AtomicPrimitive: Sized + Copy + Sealed {
277
    /// Temporary implementation detail.
278
    type AtomicInner: Sized;
279
}
280

            
281
macro impl_atomic_primitive(
282
    $Atom:ident $(<$T:ident>)? ($Primitive:ty),
283
    size($size:literal),
284
    align($align:literal) $(,)?
285
) {
286
    impl $(<$T>)? Sealed for $Primitive {}
287

            
288
    #[unstable(
289
        feature = "atomic_internals",
290
        reason = "implementation detail which may disappear or be replaced at any time",
291
        issue = "none"
292
    )]
293
    #[cfg(target_has_atomic_load_store = $size)]
294
    unsafe impl $(<$T>)? AtomicPrimitive for $Primitive {
295
        type AtomicInner = $Atom $(<$T>)?;
296
    }
297
}
298

            
299
#[cfg(not(feature = "ferrocene_certified"))]
300
impl_atomic_primitive!(AtomicBool(bool), size("8"), align(1));
301
#[cfg(not(feature = "ferrocene_certified"))]
302
impl_atomic_primitive!(AtomicI8(i8), size("8"), align(1));
303
#[cfg(not(feature = "ferrocene_certified"))]
304
impl_atomic_primitive!(AtomicU8(u8), size("8"), align(1));
305
#[cfg(not(feature = "ferrocene_certified"))]
306
impl_atomic_primitive!(AtomicI16(i16), size("16"), align(2));
307
#[cfg(not(feature = "ferrocene_certified"))]
308
impl_atomic_primitive!(AtomicU16(u16), size("16"), align(2));
309
#[cfg(not(feature = "ferrocene_certified"))]
310
impl_atomic_primitive!(AtomicI32(i32), size("32"), align(4));
311
impl_atomic_primitive!(AtomicU32(u32), size("32"), align(4));
312
#[cfg(not(feature = "ferrocene_certified"))]
313
impl_atomic_primitive!(AtomicI64(i64), size("64"), align(8));
314
#[cfg(not(feature = "ferrocene_certified"))]
315
impl_atomic_primitive!(AtomicU64(u64), size("64"), align(8));
316
#[cfg(not(feature = "ferrocene_certified"))]
317
impl_atomic_primitive!(AtomicI128(i128), size("128"), align(16));
318
#[cfg(not(feature = "ferrocene_certified"))]
319
impl_atomic_primitive!(AtomicU128(u128), size("128"), align(16));
320

            
321
#[cfg(target_pointer_width = "16")]
322
#[cfg(not(feature = "ferrocene_certified"))]
323
impl_atomic_primitive!(AtomicIsize(isize), size("ptr"), align(2));
324
#[cfg(target_pointer_width = "32")]
325
#[cfg(not(feature = "ferrocene_certified"))]
326
impl_atomic_primitive!(AtomicIsize(isize), size("ptr"), align(4));
327
#[cfg(target_pointer_width = "64")]
328
#[cfg(not(feature = "ferrocene_certified"))]
329
impl_atomic_primitive!(AtomicIsize(isize), size("ptr"), align(8));
330

            
331
#[cfg(target_pointer_width = "16")]
332
#[cfg(not(feature = "ferrocene_certified"))]
333
impl_atomic_primitive!(AtomicUsize(usize), size("ptr"), align(2));
334
#[cfg(target_pointer_width = "32")]
335
#[cfg(not(feature = "ferrocene_certified"))]
336
impl_atomic_primitive!(AtomicUsize(usize), size("ptr"), align(4));
337
#[cfg(target_pointer_width = "64")]
338
#[cfg(not(feature = "ferrocene_certified"))]
339
impl_atomic_primitive!(AtomicUsize(usize), size("ptr"), align(8));
340

            
341
#[cfg(target_pointer_width = "16")]
342
#[cfg(not(feature = "ferrocene_certified"))]
343
impl_atomic_primitive!(AtomicPtr<T>(*mut T), size("ptr"), align(2));
344
#[cfg(target_pointer_width = "32")]
345
#[cfg(not(feature = "ferrocene_certified"))]
346
impl_atomic_primitive!(AtomicPtr<T>(*mut T), size("ptr"), align(4));
347
#[cfg(target_pointer_width = "64")]
348
#[cfg(not(feature = "ferrocene_certified"))]
349
impl_atomic_primitive!(AtomicPtr<T>(*mut T), size("ptr"), align(8));
350

            
351
/// A memory location which can be safely modified from multiple threads.
352
///
353
/// This has the same size and bit validity as the underlying type `T`. However,
354
/// the alignment of this type is always equal to its size, even on targets where
355
/// `T` has alignment less than its size.
356
///
357
/// For more about the differences between atomic types and non-atomic types as
358
/// well as information about the portability of this type, please see the
359
/// [module-level documentation].
360
///
361
/// **Note:** This type is only available on platforms that support atomic loads
362
/// and stores of `T`.
363
///
364
/// [module-level documentation]: crate::sync::atomic
365
#[unstable(feature = "generic_atomic", issue = "130539")]
366
#[cfg(not(feature = "ferrocene_certified"))]
367
pub type Atomic<T> = <T as AtomicPrimitive>::AtomicInner;
368

            
369
// Some architectures don't have byte-sized atomics, which results in LLVM
370
// emulating them using a LL/SC loop. However for AtomicBool we can take
371
// advantage of the fact that it only ever contains 0 or 1 and use atomic OR/AND
372
// instead, which LLVM can emulate using a larger atomic OR/AND operation.
373
//
374
// This list should only contain architectures which have word-sized atomic-or/
375
// atomic-and instructions but don't natively support byte-sized atomics.
376
#[cfg(target_has_atomic = "8")]
377
#[cfg(not(feature = "ferrocene_certified"))]
378
const EMULATE_ATOMIC_BOOL: bool = cfg!(any(
379
    target_arch = "riscv32",
380
    target_arch = "riscv64",
381
    target_arch = "loongarch32",
382
    target_arch = "loongarch64"
383
));
384

            
385
/// A boolean type which can be safely shared between threads.
386
///
387
/// This type has the same size, alignment, and bit validity as a [`bool`].
388
///
389
/// **Note**: This type is only available on platforms that support atomic
390
/// loads and stores of `u8`.
391
#[cfg(target_has_atomic_load_store = "8")]
392
#[stable(feature = "rust1", since = "1.0.0")]
393
#[rustc_diagnostic_item = "AtomicBool"]
394
#[repr(C, align(1))]
395
#[cfg(not(feature = "ferrocene_certified"))]
396
pub struct AtomicBool {
397
    v: UnsafeCell<u8>,
398
}
399

            
400
#[cfg(target_has_atomic_load_store = "8")]
401
#[stable(feature = "rust1", since = "1.0.0")]
402
#[cfg(not(feature = "ferrocene_certified"))]
403
impl Default for AtomicBool {
404
    /// Creates an `AtomicBool` initialized to `false`.
405
    #[inline]
406
    fn default() -> Self {
407
        Self::new(false)
408
    }
409
}
410

            
411
// Send is implicitly implemented for AtomicBool.
412
#[cfg(target_has_atomic_load_store = "8")]
413
#[stable(feature = "rust1", since = "1.0.0")]
414
#[cfg(not(feature = "ferrocene_certified"))]
415
unsafe impl Sync for AtomicBool {}
416

            
417
/// A raw pointer type which can be safely shared between threads.
418
///
419
/// This type has the same size and bit validity as a `*mut T`.
420
///
421
/// **Note**: This type is only available on platforms that support atomic
422
/// loads and stores of pointers. Its size depends on the target pointer's size.
423
#[cfg(target_has_atomic_load_store = "ptr")]
424
#[stable(feature = "rust1", since = "1.0.0")]
425
#[rustc_diagnostic_item = "AtomicPtr"]
426
#[cfg_attr(target_pointer_width = "16", repr(C, align(2)))]
427
#[cfg_attr(target_pointer_width = "32", repr(C, align(4)))]
428
#[cfg_attr(target_pointer_width = "64", repr(C, align(8)))]
429
#[cfg(not(feature = "ferrocene_certified"))]
430
pub struct AtomicPtr<T> {
431
    p: UnsafeCell<*mut T>,
432
}
433

            
434
#[cfg(target_has_atomic_load_store = "ptr")]
435
#[stable(feature = "rust1", since = "1.0.0")]
436
#[cfg(not(feature = "ferrocene_certified"))]
437
impl<T> Default for AtomicPtr<T> {
438
    /// Creates a null `AtomicPtr<T>`.
439
    fn default() -> AtomicPtr<T> {
440
        AtomicPtr::new(crate::ptr::null_mut())
441
    }
442
}
443

            
444
#[cfg(target_has_atomic_load_store = "ptr")]
445
#[stable(feature = "rust1", since = "1.0.0")]
446
#[cfg(not(feature = "ferrocene_certified"))]
447
unsafe impl<T> Send for AtomicPtr<T> {}
448
#[cfg(target_has_atomic_load_store = "ptr")]
449
#[stable(feature = "rust1", since = "1.0.0")]
450
#[cfg(not(feature = "ferrocene_certified"))]
451
unsafe impl<T> Sync for AtomicPtr<T> {}
452

            
453
/// Atomic memory orderings
454
///
455
/// Memory orderings specify the way atomic operations synchronize memory.
456
/// In its weakest [`Ordering::Relaxed`], only the memory directly touched by the
457
/// operation is synchronized. On the other hand, a store-load pair of [`Ordering::SeqCst`]
458
/// operations synchronize other memory while additionally preserving a total order of such
459
/// operations across all threads.
460
///
461
/// Rust's memory orderings are [the same as those of
462
/// C++20](https://en.cppreference.com/w/cpp/atomic/memory_order).
463
///
464
/// For more information see the [nomicon].
465
///
466
/// [nomicon]: ../../../nomicon/atomics.html
467
#[stable(feature = "rust1", since = "1.0.0")]
468
#[cfg_attr(not(feature = "ferrocene_certified"), derive(Copy, Clone, Debug, Eq, PartialEq, Hash))]
469
#[cfg_attr(feature = "ferrocene_certified", derive(Copy, Clone))]
470
#[non_exhaustive]
471
#[rustc_diagnostic_item = "Ordering"]
472
pub enum Ordering {
473
    /// No ordering constraints, only atomic operations.
474
    ///
475
    /// Corresponds to [`memory_order_relaxed`] in C++20.
476
    ///
477
    /// [`memory_order_relaxed`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Relaxed_ordering
478
    #[stable(feature = "rust1", since = "1.0.0")]
479
    Relaxed,
480
    /// When coupled with a store, all previous operations become ordered
481
    /// before any load of this value with [`Acquire`] (or stronger) ordering.
482
    /// In particular, all previous writes become visible to all threads
483
    /// that perform an [`Acquire`] (or stronger) load of this value.
484
    ///
485
    /// Notice that using this ordering for an operation that combines loads
486
    /// and stores leads to a [`Relaxed`] load operation!
487
    ///
488
    /// This ordering is only applicable for operations that can perform a store.
489
    ///
490
    /// Corresponds to [`memory_order_release`] in C++20.
491
    ///
492
    /// [`memory_order_release`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
493
    #[stable(feature = "rust1", since = "1.0.0")]
494
    Release,
495
    /// When coupled with a load, if the loaded value was written by a store operation with
496
    /// [`Release`] (or stronger) ordering, then all subsequent operations
497
    /// become ordered after that store. In particular, all subsequent loads will see data
498
    /// written before the store.
499
    ///
500
    /// Notice that using this ordering for an operation that combines loads
501
    /// and stores leads to a [`Relaxed`] store operation!
502
    ///
503
    /// This ordering is only applicable for operations that can perform a load.
504
    ///
505
    /// Corresponds to [`memory_order_acquire`] in C++20.
506
    ///
507
    /// [`memory_order_acquire`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
508
    #[stable(feature = "rust1", since = "1.0.0")]
509
    Acquire,
510
    /// Has the effects of both [`Acquire`] and [`Release`] together:
511
    /// For loads it uses [`Acquire`] ordering. For stores it uses the [`Release`] ordering.
512
    ///
513
    /// Notice that in the case of `compare_and_swap`, it is possible that the operation ends up
514
    /// not performing any store and hence it has just [`Acquire`] ordering. However,
515
    /// `AcqRel` will never perform [`Relaxed`] accesses.
516
    ///
517
    /// This ordering is only applicable for operations that combine both loads and stores.
518
    ///
519
    /// Corresponds to [`memory_order_acq_rel`] in C++20.
520
    ///
521
    /// [`memory_order_acq_rel`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
522
    #[stable(feature = "rust1", since = "1.0.0")]
523
    AcqRel,
524
    /// Like [`Acquire`]/[`Release`]/[`AcqRel`] (for load, store, and load-with-store
525
    /// operations, respectively) with the additional guarantee that all threads see all
526
    /// sequentially consistent operations in the same order.
527
    ///
528
    /// Corresponds to [`memory_order_seq_cst`] in C++20.
529
    ///
530
    /// [`memory_order_seq_cst`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Sequentially-consistent_ordering
531
    #[stable(feature = "rust1", since = "1.0.0")]
532
    SeqCst,
533
}
534

            
535
/// An [`AtomicBool`] initialized to `false`.
536
#[cfg(target_has_atomic_load_store = "8")]
537
#[stable(feature = "rust1", since = "1.0.0")]
538
#[deprecated(
539
    since = "1.34.0",
540
    note = "the `new` function is now preferred",
541
    suggestion = "AtomicBool::new(false)"
542
)]
543
#[cfg(not(feature = "ferrocene_certified"))]
544
pub const ATOMIC_BOOL_INIT: AtomicBool = AtomicBool::new(false);
545

            
546
#[cfg(target_has_atomic_load_store = "8")]
547
#[cfg(not(feature = "ferrocene_certified"))]
548
impl AtomicBool {
549
    /// Creates a new `AtomicBool`.
550
    ///
551
    /// # Examples
552
    ///
553
    /// ```
554
    /// use std::sync::atomic::AtomicBool;
555
    ///
556
    /// let atomic_true = AtomicBool::new(true);
557
    /// let atomic_false = AtomicBool::new(false);
558
    /// ```
559
    #[inline]
560
    #[stable(feature = "rust1", since = "1.0.0")]
561
    #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")]
562
    #[must_use]
563
    pub const fn new(v: bool) -> AtomicBool {
564
        AtomicBool { v: UnsafeCell::new(v as u8) }
565
    }
566

            
567
    /// Creates a new `AtomicBool` from a pointer.
568
    ///
569
    /// # Examples
570
    ///
571
    /// ```
572
    /// use std::sync::atomic::{self, AtomicBool};
573
    ///
574
    /// // Get a pointer to an allocated value
575
    /// let ptr: *mut bool = Box::into_raw(Box::new(false));
576
    ///
577
    /// assert!(ptr.cast::<AtomicBool>().is_aligned());
578
    ///
579
    /// {
580
    ///     // Create an atomic view of the allocated value
581
    ///     let atomic = unsafe { AtomicBool::from_ptr(ptr) };
582
    ///
583
    ///     // Use `atomic` for atomic operations, possibly share it with other threads
584
    ///     atomic.store(true, atomic::Ordering::Relaxed);
585
    /// }
586
    ///
587
    /// // It's ok to non-atomically access the value behind `ptr`,
588
    /// // since the reference to the atomic ended its lifetime in the block above
589
    /// assert_eq!(unsafe { *ptr }, true);
590
    ///
591
    /// // Deallocate the value
592
    /// unsafe { drop(Box::from_raw(ptr)) }
593
    /// ```
594
    ///
595
    /// # Safety
596
    ///
597
    /// * `ptr` must be aligned to `align_of::<AtomicBool>()` (note that this is always true, since
598
    ///   `align_of::<AtomicBool>() == 1`).
599
    /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
600
    /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
601
    ///   allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
602
    ///   sizes, without synchronization.
603
    ///
604
    /// [valid]: crate::ptr#safety
605
    /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
606
    #[inline]
607
    #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
608
    #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
609
    pub const unsafe fn from_ptr<'a>(ptr: *mut bool) -> &'a AtomicBool {
610
        // SAFETY: guaranteed by the caller
611
        unsafe { &*ptr.cast() }
612
    }
613

            
614
    /// Returns a mutable reference to the underlying [`bool`].
615
    ///
616
    /// This is safe because the mutable reference guarantees that no other threads are
617
    /// concurrently accessing the atomic data.
618
    ///
619
    /// # Examples
620
    ///
621
    /// ```
622
    /// use std::sync::atomic::{AtomicBool, Ordering};
623
    ///
624
    /// let mut some_bool = AtomicBool::new(true);
625
    /// assert_eq!(*some_bool.get_mut(), true);
626
    /// *some_bool.get_mut() = false;
627
    /// assert_eq!(some_bool.load(Ordering::SeqCst), false);
628
    /// ```
629
    #[inline]
630
    #[stable(feature = "atomic_access", since = "1.15.0")]
631
    pub fn get_mut(&mut self) -> &mut bool {
632
        // SAFETY: the mutable reference guarantees unique ownership.
633
        unsafe { &mut *(self.v.get() as *mut bool) }
634
    }
635

            
636
    /// Gets atomic access to a `&mut bool`.
637
    ///
638
    /// # Examples
639
    ///
640
    /// ```
641
    /// #![feature(atomic_from_mut)]
642
    /// use std::sync::atomic::{AtomicBool, Ordering};
643
    ///
644
    /// let mut some_bool = true;
645
    /// let a = AtomicBool::from_mut(&mut some_bool);
646
    /// a.store(false, Ordering::Relaxed);
647
    /// assert_eq!(some_bool, false);
648
    /// ```
649
    #[inline]
650
    #[cfg(target_has_atomic_equal_alignment = "8")]
651
    #[unstable(feature = "atomic_from_mut", issue = "76314")]
652
    pub fn from_mut(v: &mut bool) -> &mut Self {
653
        // SAFETY: the mutable reference guarantees unique ownership, and
654
        // alignment of both `bool` and `Self` is 1.
655
        unsafe { &mut *(v as *mut bool as *mut Self) }
656
    }
657

            
658
    /// Gets non-atomic access to a `&mut [AtomicBool]` slice.
659
    ///
660
    /// This is safe because the mutable reference guarantees that no other threads are
661
    /// concurrently accessing the atomic data.
662
    ///
663
    /// # Examples
664
    ///
665
    /// ```ignore-wasm
666
    /// #![feature(atomic_from_mut)]
667
    /// use std::sync::atomic::{AtomicBool, Ordering};
668
    ///
669
    /// let mut some_bools = [const { AtomicBool::new(false) }; 10];
670
    ///
671
    /// let view: &mut [bool] = AtomicBool::get_mut_slice(&mut some_bools);
672
    /// assert_eq!(view, [false; 10]);
673
    /// view[..5].copy_from_slice(&[true; 5]);
674
    ///
675
    /// std::thread::scope(|s| {
676
    ///     for t in &some_bools[..5] {
677
    ///         s.spawn(move || assert_eq!(t.load(Ordering::Relaxed), true));
678
    ///     }
679
    ///
680
    ///     for f in &some_bools[5..] {
681
    ///         s.spawn(move || assert_eq!(f.load(Ordering::Relaxed), false));
682
    ///     }
683
    /// });
684
    /// ```
685
    #[inline]
686
    #[unstable(feature = "atomic_from_mut", issue = "76314")]
687
    pub fn get_mut_slice(this: &mut [Self]) -> &mut [bool] {
688
        // SAFETY: the mutable reference guarantees unique ownership.
689
        unsafe { &mut *(this as *mut [Self] as *mut [bool]) }
690
    }
691

            
692
    /// Gets atomic access to a `&mut [bool]` slice.
693
    ///
694
    /// # Examples
695
    ///
696
    /// ```rust,ignore-wasm
697
    /// #![feature(atomic_from_mut)]
698
    /// use std::sync::atomic::{AtomicBool, Ordering};
699
    ///
700
    /// let mut some_bools = [false; 10];
701
    /// let a = &*AtomicBool::from_mut_slice(&mut some_bools);
702
    /// std::thread::scope(|s| {
703
    ///     for i in 0..a.len() {
704
    ///         s.spawn(move || a[i].store(true, Ordering::Relaxed));
705
    ///     }
706
    /// });
707
    /// assert_eq!(some_bools, [true; 10]);
708
    /// ```
709
    #[inline]
710
    #[cfg(target_has_atomic_equal_alignment = "8")]
711
    #[unstable(feature = "atomic_from_mut", issue = "76314")]
712
    pub fn from_mut_slice(v: &mut [bool]) -> &mut [Self] {
713
        // SAFETY: the mutable reference guarantees unique ownership, and
714
        // alignment of both `bool` and `Self` is 1.
715
        unsafe { &mut *(v as *mut [bool] as *mut [Self]) }
716
    }
717

            
718
    /// Consumes the atomic and returns the contained value.
719
    ///
720
    /// This is safe because passing `self` by value guarantees that no other threads are
721
    /// concurrently accessing the atomic data.
722
    ///
723
    /// # Examples
724
    ///
725
    /// ```
726
    /// use std::sync::atomic::AtomicBool;
727
    ///
728
    /// let some_bool = AtomicBool::new(true);
729
    /// assert_eq!(some_bool.into_inner(), true);
730
    /// ```
731
    #[inline]
732
    #[stable(feature = "atomic_access", since = "1.15.0")]
733
    #[rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0")]
734
    pub const fn into_inner(self) -> bool {
735
        self.v.into_inner() != 0
736
    }
737

            
738
    /// Loads a value from the bool.
739
    ///
740
    /// `load` takes an [`Ordering`] argument which describes the memory ordering
741
    /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
742
    ///
743
    /// # Panics
744
    ///
745
    /// Panics if `order` is [`Release`] or [`AcqRel`].
746
    ///
747
    /// # Examples
748
    ///
749
    /// ```
750
    /// use std::sync::atomic::{AtomicBool, Ordering};
751
    ///
752
    /// let some_bool = AtomicBool::new(true);
753
    ///
754
    /// assert_eq!(some_bool.load(Ordering::Relaxed), true);
755
    /// ```
756
    #[inline]
757
    #[stable(feature = "rust1", since = "1.0.0")]
758
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
759
    pub fn load(&self, order: Ordering) -> bool {
760
        // SAFETY: any data races are prevented by atomic intrinsics and the raw
761
        // pointer passed in is valid because we got it from a reference.
762
        unsafe { atomic_load(self.v.get(), order) != 0 }
763
    }
764

            
765
    /// Stores a value into the bool.
766
    ///
767
    /// `store` takes an [`Ordering`] argument which describes the memory ordering
768
    /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
769
    ///
770
    /// # Panics
771
    ///
772
    /// Panics if `order` is [`Acquire`] or [`AcqRel`].
773
    ///
774
    /// # Examples
775
    ///
776
    /// ```
777
    /// use std::sync::atomic::{AtomicBool, Ordering};
778
    ///
779
    /// let some_bool = AtomicBool::new(true);
780
    ///
781
    /// some_bool.store(false, Ordering::Relaxed);
782
    /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
783
    /// ```
784
    #[inline]
785
    #[stable(feature = "rust1", since = "1.0.0")]
786
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
787
    pub fn store(&self, val: bool, order: Ordering) {
788
        // SAFETY: any data races are prevented by atomic intrinsics and the raw
789
        // pointer passed in is valid because we got it from a reference.
790
        unsafe {
791
            atomic_store(self.v.get(), val as u8, order);
792
        }
793
    }
794

            
795
    /// Stores a value into the bool, returning the previous value.
796
    ///
797
    /// `swap` takes an [`Ordering`] argument which describes the memory ordering
798
    /// of this operation. All ordering modes are possible. Note that using
799
    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
800
    /// using [`Release`] makes the load part [`Relaxed`].
801
    ///
802
    /// **Note:** This method is only available on platforms that support atomic
803
    /// operations on `u8`.
804
    ///
805
    /// # Examples
806
    ///
807
    /// ```
808
    /// use std::sync::atomic::{AtomicBool, Ordering};
809
    ///
810
    /// let some_bool = AtomicBool::new(true);
811
    ///
812
    /// assert_eq!(some_bool.swap(false, Ordering::Relaxed), true);
813
    /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
814
    /// ```
815
    #[inline]
816
    #[stable(feature = "rust1", since = "1.0.0")]
817
    #[cfg(target_has_atomic = "8")]
818
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
819
    pub fn swap(&self, val: bool, order: Ordering) -> bool {
820
        if EMULATE_ATOMIC_BOOL {
821
            if val { self.fetch_or(true, order) } else { self.fetch_and(false, order) }
822
        } else {
823
            // SAFETY: data races are prevented by atomic intrinsics.
824
            unsafe { atomic_swap(self.v.get(), val as u8, order) != 0 }
825
        }
826
    }
827

            
828
    /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
829
    ///
830
    /// The return value is always the previous value. If it is equal to `current`, then the value
831
    /// was updated.
832
    ///
833
    /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
834
    /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
835
    /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
836
    /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
837
    /// happens, and using [`Release`] makes the load part [`Relaxed`].
838
    ///
839
    /// **Note:** This method is only available on platforms that support atomic
840
    /// operations on `u8`.
841
    ///
842
    /// # Migrating to `compare_exchange` and `compare_exchange_weak`
843
    ///
844
    /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
845
    /// memory orderings:
846
    ///
847
    /// Original | Success | Failure
848
    /// -------- | ------- | -------
849
    /// Relaxed  | Relaxed | Relaxed
850
    /// Acquire  | Acquire | Acquire
851
    /// Release  | Release | Relaxed
852
    /// AcqRel   | AcqRel  | Acquire
853
    /// SeqCst   | SeqCst  | SeqCst
854
    ///
855
    /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
856
    /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
857
    /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
858
    /// rather than to infer success vs failure based on the value that was read.
859
    ///
860
    /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
861
    /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
862
    /// which allows the compiler to generate better assembly code when the compare and swap
863
    /// is used in a loop.
864
    ///
865
    /// # Examples
866
    ///
867
    /// ```
868
    /// use std::sync::atomic::{AtomicBool, Ordering};
869
    ///
870
    /// let some_bool = AtomicBool::new(true);
871
    ///
872
    /// assert_eq!(some_bool.compare_and_swap(true, false, Ordering::Relaxed), true);
873
    /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
874
    ///
875
    /// assert_eq!(some_bool.compare_and_swap(true, true, Ordering::Relaxed), false);
876
    /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
877
    /// ```
878
    #[inline]
879
    #[stable(feature = "rust1", since = "1.0.0")]
880
    #[deprecated(
881
        since = "1.50.0",
882
        note = "Use `compare_exchange` or `compare_exchange_weak` instead"
883
    )]
884
    #[cfg(target_has_atomic = "8")]
885
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
886
    pub fn compare_and_swap(&self, current: bool, new: bool, order: Ordering) -> bool {
887
        match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
888
            Ok(x) => x,
889
            Err(x) => x,
890
        }
891
    }
892

            
893
    /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
894
    ///
895
    /// The return value is a result indicating whether the new value was written and containing
896
    /// the previous value. On success this value is guaranteed to be equal to `current`.
897
    ///
898
    /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
899
    /// ordering of this operation. `success` describes the required ordering for the
900
    /// read-modify-write operation that takes place if the comparison with `current` succeeds.
901
    /// `failure` describes the required ordering for the load operation that takes place when
902
    /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
903
    /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
904
    /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
905
    ///
906
    /// **Note:** This method is only available on platforms that support atomic
907
    /// operations on `u8`.
908
    ///
909
    /// # Examples
910
    ///
911
    /// ```
912
    /// use std::sync::atomic::{AtomicBool, Ordering};
913
    ///
914
    /// let some_bool = AtomicBool::new(true);
915
    ///
916
    /// assert_eq!(some_bool.compare_exchange(true,
917
    ///                                       false,
918
    ///                                       Ordering::Acquire,
919
    ///                                       Ordering::Relaxed),
920
    ///            Ok(true));
921
    /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
922
    ///
923
    /// assert_eq!(some_bool.compare_exchange(true, true,
924
    ///                                       Ordering::SeqCst,
925
    ///                                       Ordering::Acquire),
926
    ///            Err(false));
927
    /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
928
    /// ```
929
    ///
930
    /// # Considerations
931
    ///
932
    /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
933
    /// of CAS operations. In particular, a load of the value followed by a successful
934
    /// `compare_exchange` with the previous load *does not ensure* that other threads have not
935
    /// changed the value in the interim. This is usually important when the *equality* check in
936
    /// the `compare_exchange` is being used to check the *identity* of a value, but equality
937
    /// does not necessarily imply identity. In this case, `compare_exchange` can lead to the
938
    /// [ABA problem].
939
    ///
940
    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
941
    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
942
    #[inline]
943
    #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
944
    #[doc(alias = "compare_and_swap")]
945
    #[cfg(target_has_atomic = "8")]
946
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
947
    pub fn compare_exchange(
948
        &self,
949
        current: bool,
950
        new: bool,
951
        success: Ordering,
952
        failure: Ordering,
953
    ) -> Result<bool, bool> {
954
        if EMULATE_ATOMIC_BOOL {
955
            // Pick the strongest ordering from success and failure.
956
            let order = match (success, failure) {
957
                (SeqCst, _) => SeqCst,
958
                (_, SeqCst) => SeqCst,
959
                (AcqRel, _) => AcqRel,
960
                (_, AcqRel) => {
961
                    panic!("there is no such thing as an acquire-release failure ordering")
962
                }
963
                (Release, Acquire) => AcqRel,
964
                (Acquire, _) => Acquire,
965
                (_, Acquire) => Acquire,
966
                (Release, Relaxed) => Release,
967
                (_, Release) => panic!("there is no such thing as a release failure ordering"),
968
                (Relaxed, Relaxed) => Relaxed,
969
            };
970
            let old = if current == new {
971
                // This is a no-op, but we still need to perform the operation
972
                // for memory ordering reasons.
973
                self.fetch_or(false, order)
974
            } else {
975
                // This sets the value to the new one and returns the old one.
976
                self.swap(new, order)
977
            };
978
            if old == current { Ok(old) } else { Err(old) }
979
        } else {
980
            // SAFETY: data races are prevented by atomic intrinsics.
981
            match unsafe {
982
                atomic_compare_exchange(self.v.get(), current as u8, new as u8, success, failure)
983
            } {
984
                Ok(x) => Ok(x != 0),
985
                Err(x) => Err(x != 0),
986
            }
987
        }
988
    }
989

            
990
    /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
991
    ///
992
    /// Unlike [`AtomicBool::compare_exchange`], this function is allowed to spuriously fail even when the
993
    /// comparison succeeds, which can result in more efficient code on some platforms. The
994
    /// return value is a result indicating whether the new value was written and containing the
995
    /// previous value.
996
    ///
997
    /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
998
    /// ordering of this operation. `success` describes the required ordering for the
999
    /// read-modify-write operation that takes place if the comparison with `current` succeeds.
    /// `failure` describes the required ordering for the load operation that takes place when
    /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
    /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
    /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on `u8`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicBool, Ordering};
    ///
    /// let val = AtomicBool::new(false);
    ///
    /// let new = true;
    /// let mut old = val.load(Ordering::Relaxed);
    /// loop {
    ///     match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
    ///         Ok(_) => break,
    ///         Err(x) => old = x,
    ///     }
    /// }
    /// ```
    ///
    /// # Considerations
    ///
    /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
    /// of CAS operations. In particular, a load of the value followed by a successful
    /// `compare_exchange` with the previous load *does not ensure* that other threads have not
    /// changed the value in the interim. This is usually important when the *equality* check in
    /// the `compare_exchange` is being used to check the *identity* of a value, but equality
    /// does not necessarily imply identity. In this case, `compare_exchange` can lead to the
    /// [ABA problem].
    ///
    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
    #[inline]
    #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
    #[doc(alias = "compare_and_swap")]
    #[cfg(target_has_atomic = "8")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn compare_exchange_weak(
        &self,
        current: bool,
        new: bool,
        success: Ordering,
        failure: Ordering,
    ) -> Result<bool, bool> {
        if EMULATE_ATOMIC_BOOL {
            return self.compare_exchange(current, new, success, failure);
        }
        // SAFETY: data races are prevented by atomic intrinsics.
        match unsafe {
            atomic_compare_exchange_weak(self.v.get(), current as u8, new as u8, success, failure)
        } {
            Ok(x) => Ok(x != 0),
            Err(x) => Err(x != 0),
        }
    }
    /// Logical "and" with a boolean value.
    ///
    /// Performs a logical "and" operation on the current value and the argument `val`, and sets
    /// the new value to the result.
    ///
    /// Returns the previous value.
    ///
    /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. All ordering modes are possible. Note that using
    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
    /// using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on `u8`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicBool, Ordering};
    ///
    /// let foo = AtomicBool::new(true);
    /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), true);
    /// assert_eq!(foo.load(Ordering::SeqCst), false);
    ///
    /// let foo = AtomicBool::new(true);
    /// assert_eq!(foo.fetch_and(true, Ordering::SeqCst), true);
    /// assert_eq!(foo.load(Ordering::SeqCst), true);
    ///
    /// let foo = AtomicBool::new(false);
    /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), false);
    /// assert_eq!(foo.load(Ordering::SeqCst), false);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[cfg(target_has_atomic = "8")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_and(&self, val: bool, order: Ordering) -> bool {
        // SAFETY: data races are prevented by atomic intrinsics.
        unsafe { atomic_and(self.v.get(), val as u8, order) != 0 }
    }
    /// Logical "nand" with a boolean value.
    ///
    /// Performs a logical "nand" operation on the current value and the argument `val`, and sets
    /// the new value to the result.
    ///
    /// Returns the previous value.
    ///
    /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. All ordering modes are possible. Note that using
    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
    /// using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on `u8`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicBool, Ordering};
    ///
    /// let foo = AtomicBool::new(true);
    /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), true);
    /// assert_eq!(foo.load(Ordering::SeqCst), true);
    ///
    /// let foo = AtomicBool::new(true);
    /// assert_eq!(foo.fetch_nand(true, Ordering::SeqCst), true);
    /// assert_eq!(foo.load(Ordering::SeqCst) as usize, 0);
    /// assert_eq!(foo.load(Ordering::SeqCst), false);
    ///
    /// let foo = AtomicBool::new(false);
    /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), false);
    /// assert_eq!(foo.load(Ordering::SeqCst), true);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[cfg(target_has_atomic = "8")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_nand(&self, val: bool, order: Ordering) -> bool {
        // We can't use atomic_nand here because it can result in a bool with
        // an invalid value. This happens because the atomic operation is done
        // with an 8-bit integer internally, which would set the upper 7 bits.
        // So we just use fetch_xor or swap instead.
        if val {
            // !(x & true) == !x
            // We must invert the bool.
            self.fetch_xor(true, order)
        } else {
            // !(x & false) == true
            // We must set the bool to true.
            self.swap(true, order)
        }
    }
    /// Logical "or" with a boolean value.
    ///
    /// Performs a logical "or" operation on the current value and the argument `val`, and sets the
    /// new value to the result.
    ///
    /// Returns the previous value.
    ///
    /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. All ordering modes are possible. Note that using
    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
    /// using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on `u8`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicBool, Ordering};
    ///
    /// let foo = AtomicBool::new(true);
    /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), true);
    /// assert_eq!(foo.load(Ordering::SeqCst), true);
    ///
    /// let foo = AtomicBool::new(true);
    /// assert_eq!(foo.fetch_or(true, Ordering::SeqCst), true);
    /// assert_eq!(foo.load(Ordering::SeqCst), true);
    ///
    /// let foo = AtomicBool::new(false);
    /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), false);
    /// assert_eq!(foo.load(Ordering::SeqCst), false);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[cfg(target_has_atomic = "8")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_or(&self, val: bool, order: Ordering) -> bool {
        // SAFETY: data races are prevented by atomic intrinsics.
        unsafe { atomic_or(self.v.get(), val as u8, order) != 0 }
    }
    /// Logical "xor" with a boolean value.
    ///
    /// Performs a logical "xor" operation on the current value and the argument `val`, and sets
    /// the new value to the result.
    ///
    /// Returns the previous value.
    ///
    /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. All ordering modes are possible. Note that using
    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
    /// using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on `u8`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicBool, Ordering};
    ///
    /// let foo = AtomicBool::new(true);
    /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), true);
    /// assert_eq!(foo.load(Ordering::SeqCst), true);
    ///
    /// let foo = AtomicBool::new(true);
    /// assert_eq!(foo.fetch_xor(true, Ordering::SeqCst), true);
    /// assert_eq!(foo.load(Ordering::SeqCst), false);
    ///
    /// let foo = AtomicBool::new(false);
    /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), false);
    /// assert_eq!(foo.load(Ordering::SeqCst), false);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[cfg(target_has_atomic = "8")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_xor(&self, val: bool, order: Ordering) -> bool {
        // SAFETY: data races are prevented by atomic intrinsics.
        unsafe { atomic_xor(self.v.get(), val as u8, order) != 0 }
    }
    /// Logical "not" with a boolean value.
    ///
    /// Performs a logical "not" operation on the current value, and sets
    /// the new value to the result.
    ///
    /// Returns the previous value.
    ///
    /// `fetch_not` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. All ordering modes are possible. Note that using
    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
    /// using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on `u8`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicBool, Ordering};
    ///
    /// let foo = AtomicBool::new(true);
    /// assert_eq!(foo.fetch_not(Ordering::SeqCst), true);
    /// assert_eq!(foo.load(Ordering::SeqCst), false);
    ///
    /// let foo = AtomicBool::new(false);
    /// assert_eq!(foo.fetch_not(Ordering::SeqCst), false);
    /// assert_eq!(foo.load(Ordering::SeqCst), true);
    /// ```
    #[inline]
    #[stable(feature = "atomic_bool_fetch_not", since = "1.81.0")]
    #[cfg(target_has_atomic = "8")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_not(&self, order: Ordering) -> bool {
        self.fetch_xor(true, order)
    }
    /// Returns a mutable pointer to the underlying [`bool`].
    ///
    /// Doing non-atomic reads and writes on the resulting boolean can be a data race.
    /// This method is mostly useful for FFI, where the function signature may use
    /// `*mut bool` instead of `&AtomicBool`.
    ///
    /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
    /// atomic types work with interior mutability. All modifications of an atomic change the value
    /// through a shared reference, and can do so safely as long as they use atomic operations. Any
    /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
    /// requirements of the [memory model].
    ///
    /// # Examples
    ///
    /// ```ignore (extern-declaration)
    /// # fn main() {
    /// use std::sync::atomic::AtomicBool;
    ///
    /// extern "C" {
    ///     fn my_atomic_op(arg: *mut bool);
    /// }
    ///
    /// let mut atomic = AtomicBool::new(true);
    /// unsafe {
    ///     my_atomic_op(atomic.as_ptr());
    /// }
    /// # }
    /// ```
    ///
    /// [memory model]: self#memory-model-for-atomic-accesses
    #[inline]
    #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
    #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
    #[rustc_never_returns_null_ptr]
    pub const fn as_ptr(&self) -> *mut bool {
        self.v.get().cast()
    }
    /// Fetches the value, and applies a function to it that returns an optional
    /// new value. Returns a `Result` of `Ok(previous_value)` if the function
    /// returned `Some(_)`, else `Err(previous_value)`.
    ///
    /// Note: This may call the function multiple times if the value has been
    /// changed from other threads in the meantime, as long as the function
    /// returns `Some(_)`, but the function will have been applied only once to
    /// the stored value.
    ///
    /// `fetch_update` takes two [`Ordering`] arguments to describe the memory
    /// ordering of this operation. The first describes the required ordering for
    /// when the operation finally succeeds while the second describes the
    /// required ordering for loads. These correspond to the success and failure
    /// orderings of [`AtomicBool::compare_exchange`] respectively.
    ///
    /// Using [`Acquire`] as success ordering makes the store part of this
    /// operation [`Relaxed`], and using [`Release`] makes the final successful
    /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
    /// [`Acquire`] or [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on `u8`.
    ///
    /// # Considerations
    ///
    /// This method is not magic; it is not provided by the hardware, and does not act like a
    /// critical section or mutex.
    ///
    /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
    /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem].
    ///
    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::sync::atomic::{AtomicBool, Ordering};
    ///
    /// let x = AtomicBool::new(false);
    /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(false));
    /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(false));
    /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(true));
    /// assert_eq!(x.load(Ordering::SeqCst), false);
    /// ```
    #[inline]
    #[stable(feature = "atomic_fetch_update", since = "1.53.0")]
    #[cfg(target_has_atomic = "8")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_update<F>(
        &self,
        set_order: Ordering,
        fetch_order: Ordering,
        mut f: F,
    ) -> Result<bool, bool>
    where
        F: FnMut(bool) -> Option<bool>,
    {
        let mut prev = self.load(fetch_order);
        while let Some(next) = f(prev) {
            match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
                x @ Ok(_) => return x,
                Err(next_prev) => prev = next_prev,
            }
        }
        Err(prev)
    }
    /// Fetches the value, and applies a function to it that returns an optional
    /// new value. Returns a `Result` of `Ok(previous_value)` if the function
    /// returned `Some(_)`, else `Err(previous_value)`.
    ///
    /// See also: [`update`](`AtomicBool::update`).
    ///
    /// Note: This may call the function multiple times if the value has been
    /// changed from other threads in the meantime, as long as the function
    /// returns `Some(_)`, but the function will have been applied only once to
    /// the stored value.
    ///
    /// `try_update` takes two [`Ordering`] arguments to describe the memory
    /// ordering of this operation. The first describes the required ordering for
    /// when the operation finally succeeds while the second describes the
    /// required ordering for loads. These correspond to the success and failure
    /// orderings of [`AtomicBool::compare_exchange`] respectively.
    ///
    /// Using [`Acquire`] as success ordering makes the store part of this
    /// operation [`Relaxed`], and using [`Release`] makes the final successful
    /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
    /// [`Acquire`] or [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on `u8`.
    ///
    /// # Considerations
    ///
    /// This method is not magic; it is not provided by the hardware, and does not act like a
    /// critical section or mutex.
    ///
    /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
    /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem].
    ///
    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
    ///
    /// # Examples
    ///
    /// ```rust
    /// #![feature(atomic_try_update)]
    /// use std::sync::atomic::{AtomicBool, Ordering};
    ///
    /// let x = AtomicBool::new(false);
    /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(false));
    /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(false));
    /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(true));
    /// assert_eq!(x.load(Ordering::SeqCst), false);
    /// ```
    #[inline]
    #[unstable(feature = "atomic_try_update", issue = "135894")]
    #[cfg(target_has_atomic = "8")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn try_update(
        &self,
        set_order: Ordering,
        fetch_order: Ordering,
        f: impl FnMut(bool) -> Option<bool>,
    ) -> Result<bool, bool> {
        // FIXME(atomic_try_update): this is currently an unstable alias to `fetch_update`;
        //      when stabilizing, turn `fetch_update` into a deprecated alias to `try_update`.
        self.fetch_update(set_order, fetch_order, f)
    }
    /// Fetches the value, applies a function to it that it return a new value.
    /// The new value is stored and the old value is returned.
    ///
    /// See also: [`try_update`](`AtomicBool::try_update`).
    ///
    /// Note: This may call the function multiple times if the value has been changed from other threads in
    /// the meantime, but the function will have been applied only once to the stored value.
    ///
    /// `update` takes two [`Ordering`] arguments to describe the memory
    /// ordering of this operation. The first describes the required ordering for
    /// when the operation finally succeeds while the second describes the
    /// required ordering for loads. These correspond to the success and failure
    /// orderings of [`AtomicBool::compare_exchange`] respectively.
    ///
    /// Using [`Acquire`] as success ordering makes the store part
    /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
    /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic operations on `u8`.
    ///
    /// # Considerations
    ///
    /// This method is not magic; it is not provided by the hardware, and does not act like a
    /// critical section or mutex.
    ///
    /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
    /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem].
    ///
    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
    ///
    /// # Examples
    ///
    /// ```rust
    /// #![feature(atomic_try_update)]
    ///
    /// use std::sync::atomic::{AtomicBool, Ordering};
    ///
    /// let x = AtomicBool::new(false);
    /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| !x), false);
    /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| !x), true);
    /// assert_eq!(x.load(Ordering::SeqCst), false);
    /// ```
    #[inline]
    #[unstable(feature = "atomic_try_update", issue = "135894")]
    #[cfg(target_has_atomic = "8")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn update(
        &self,
        set_order: Ordering,
        fetch_order: Ordering,
        mut f: impl FnMut(bool) -> bool,
    ) -> bool {
        let mut prev = self.load(fetch_order);
        loop {
            match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
                Ok(x) => break x,
                Err(next_prev) => prev = next_prev,
            }
        }
    }
}
#[cfg(target_has_atomic_load_store = "ptr")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> AtomicPtr<T> {
    /// Creates a new `AtomicPtr`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::AtomicPtr;
    ///
    /// let ptr = &mut 5;
    /// let atomic_ptr = AtomicPtr::new(ptr);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")]
4
    pub const fn new(p: *mut T) -> AtomicPtr<T> {
4
        AtomicPtr { p: UnsafeCell::new(p) }
4
    }
    /// Creates a new `AtomicPtr` from a pointer.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{self, AtomicPtr};
    ///
    /// // Get a pointer to an allocated value
    /// let ptr: *mut *mut u8 = Box::into_raw(Box::new(std::ptr::null_mut()));
    ///
    /// assert!(ptr.cast::<AtomicPtr<u8>>().is_aligned());
    ///
    /// {
    ///     // Create an atomic view of the allocated value
    ///     let atomic = unsafe { AtomicPtr::from_ptr(ptr) };
    ///
    ///     // Use `atomic` for atomic operations, possibly share it with other threads
    ///     atomic.store(std::ptr::NonNull::dangling().as_ptr(), atomic::Ordering::Relaxed);
    /// }
    ///
    /// // It's ok to non-atomically access the value behind `ptr`,
    /// // since the reference to the atomic ended its lifetime in the block above
    /// assert!(!unsafe { *ptr }.is_null());
    ///
    /// // Deallocate the value
    /// unsafe { drop(Box::from_raw(ptr)) }
    /// ```
    ///
    /// # Safety
    ///
    /// * `ptr` must be aligned to `align_of::<AtomicPtr<T>>()` (note that on some platforms this
    ///   can be bigger than `align_of::<*mut T>()`).
    /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
    /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
    ///   allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
    ///   sizes, without synchronization.
    ///
    /// [valid]: crate::ptr#safety
    /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
    #[inline]
    #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
    #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
    pub const unsafe fn from_ptr<'a>(ptr: *mut *mut T) -> &'a AtomicPtr<T> {
        // SAFETY: guaranteed by the caller
        unsafe { &*ptr.cast() }
    }
    /// Returns a mutable reference to the underlying pointer.
    ///
    /// This is safe because the mutable reference guarantees that no other threads are
    /// concurrently accessing the atomic data.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let mut data = 10;
    /// let mut atomic_ptr = AtomicPtr::new(&mut data);
    /// let mut other_data = 5;
    /// *atomic_ptr.get_mut() = &mut other_data;
    /// assert_eq!(unsafe { *atomic_ptr.load(Ordering::SeqCst) }, 5);
    /// ```
    #[inline]
    #[stable(feature = "atomic_access", since = "1.15.0")]
    pub fn get_mut(&mut self) -> &mut *mut T {
        self.p.get_mut()
    }
    /// Gets atomic access to a pointer.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(atomic_from_mut)]
    /// use std::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let mut data = 123;
    /// let mut some_ptr = &mut data as *mut i32;
    /// let a = AtomicPtr::from_mut(&mut some_ptr);
    /// let mut other_data = 456;
    /// a.store(&mut other_data, Ordering::Relaxed);
    /// assert_eq!(unsafe { *some_ptr }, 456);
    /// ```
    #[inline]
    #[cfg(target_has_atomic_equal_alignment = "ptr")]
    #[unstable(feature = "atomic_from_mut", issue = "76314")]
    pub fn from_mut(v: &mut *mut T) -> &mut Self {
        let [] = [(); align_of::<AtomicPtr<()>>() - align_of::<*mut ()>()];
        // SAFETY:
        //  - the mutable reference guarantees unique ownership.
        //  - the alignment of `*mut T` and `Self` is the same on all platforms
        //    supported by rust, as verified above.
        unsafe { &mut *(v as *mut *mut T as *mut Self) }
    }
    /// Gets non-atomic access to a `&mut [AtomicPtr]` slice.
    ///
    /// This is safe because the mutable reference guarantees that no other threads are
    /// concurrently accessing the atomic data.
    ///
    /// # Examples
    ///
    /// ```ignore-wasm
    /// #![feature(atomic_from_mut)]
    /// use std::ptr::null_mut;
    /// use std::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let mut some_ptrs = [const { AtomicPtr::new(null_mut::<String>()) }; 10];
    ///
    /// let view: &mut [*mut String] = AtomicPtr::get_mut_slice(&mut some_ptrs);
    /// assert_eq!(view, [null_mut::<String>(); 10]);
    /// view
    ///     .iter_mut()
    ///     .enumerate()
    ///     .for_each(|(i, ptr)| *ptr = Box::into_raw(Box::new(format!("iteration#{i}"))));
    ///
    /// std::thread::scope(|s| {
    ///     for ptr in &some_ptrs {
    ///         s.spawn(move || {
    ///             let ptr = ptr.load(Ordering::Relaxed);
    ///             assert!(!ptr.is_null());
    ///
    ///             let name = unsafe { Box::from_raw(ptr) };
    ///             println!("Hello, {name}!");
    ///         });
    ///     }
    /// });
    /// ```
    #[inline]
    #[unstable(feature = "atomic_from_mut", issue = "76314")]
    pub fn get_mut_slice(this: &mut [Self]) -> &mut [*mut T] {
        // SAFETY: the mutable reference guarantees unique ownership.
        unsafe { &mut *(this as *mut [Self] as *mut [*mut T]) }
    }
    /// Gets atomic access to a slice of pointers.
    ///
    /// # Examples
    ///
    /// ```ignore-wasm
    /// #![feature(atomic_from_mut)]
    /// use std::ptr::null_mut;
    /// use std::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let mut some_ptrs = [null_mut::<String>(); 10];
    /// let a = &*AtomicPtr::from_mut_slice(&mut some_ptrs);
    /// std::thread::scope(|s| {
    ///     for i in 0..a.len() {
    ///         s.spawn(move || {
    ///             let name = Box::new(format!("thread{i}"));
    ///             a[i].store(Box::into_raw(name), Ordering::Relaxed);
    ///         });
    ///     }
    /// });
    /// for p in some_ptrs {
    ///     assert!(!p.is_null());
    ///     let name = unsafe { Box::from_raw(p) };
    ///     println!("Hello, {name}!");
    /// }
    /// ```
    #[inline]
    #[cfg(target_has_atomic_equal_alignment = "ptr")]
    #[unstable(feature = "atomic_from_mut", issue = "76314")]
    pub fn from_mut_slice(v: &mut [*mut T]) -> &mut [Self] {
        // SAFETY:
        //  - the mutable reference guarantees unique ownership.
        //  - the alignment of `*mut T` and `Self` is the same on all platforms
        //    supported by rust, as verified above.
        unsafe { &mut *(v as *mut [*mut T] as *mut [Self]) }
    }
    /// Consumes the atomic and returns the contained value.
    ///
    /// This is safe because passing `self` by value guarantees that no other threads are
    /// concurrently accessing the atomic data.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::AtomicPtr;
    ///
    /// let mut data = 5;
    /// let atomic_ptr = AtomicPtr::new(&mut data);
    /// assert_eq!(unsafe { *atomic_ptr.into_inner() }, 5);
    /// ```
    #[inline]
    #[stable(feature = "atomic_access", since = "1.15.0")]
    #[rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0")]
    pub const fn into_inner(self) -> *mut T {
        self.p.into_inner()
    }
    /// Loads a value from the pointer.
    ///
    /// `load` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
    ///
    /// # Panics
    ///
    /// Panics if `order` is [`Release`] or [`AcqRel`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let ptr = &mut 5;
    /// let some_ptr = AtomicPtr::new(ptr);
    ///
    /// let value = some_ptr.load(Ordering::Relaxed);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
7098
    pub fn load(&self, order: Ordering) -> *mut T {
        // SAFETY: data races are prevented by atomic intrinsics.
7098
        unsafe { atomic_load(self.p.get(), order) }
7098
    }
    /// Stores a value into the pointer.
    ///
    /// `store` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
    ///
    /// # Panics
    ///
    /// Panics if `order` is [`Acquire`] or [`AcqRel`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let ptr = &mut 5;
    /// let some_ptr = AtomicPtr::new(ptr);
    ///
    /// let other_ptr = &mut 10;
    ///
    /// some_ptr.store(other_ptr, Ordering::Relaxed);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1640
    pub fn store(&self, ptr: *mut T, order: Ordering) {
        // SAFETY: data races are prevented by atomic intrinsics.
1640
        unsafe {
1640
            atomic_store(self.p.get(), ptr, order);
1640
        }
1640
    }
    /// Stores a value into the pointer, returning the previous value.
    ///
    /// `swap` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. All ordering modes are possible. Note that using
    /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
    /// using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on pointers.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let ptr = &mut 5;
    /// let some_ptr = AtomicPtr::new(ptr);
    ///
    /// let other_ptr = &mut 10;
    ///
    /// let value = some_ptr.swap(other_ptr, Ordering::Relaxed);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[cfg(target_has_atomic = "ptr")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2
    pub fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T {
        // SAFETY: data races are prevented by atomic intrinsics.
2
        unsafe { atomic_swap(self.p.get(), ptr, order) }
2
    }
    /// Stores a value into the pointer if the current value is the same as the `current` value.
    ///
    /// The return value is always the previous value. If it is equal to `current`, then the value
    /// was updated.
    ///
    /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
    /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
    /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
    /// happens, and using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on pointers.
    ///
    /// # Migrating to `compare_exchange` and `compare_exchange_weak`
    ///
    /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
    /// memory orderings:
    ///
    /// Original | Success | Failure
    /// -------- | ------- | -------
    /// Relaxed  | Relaxed | Relaxed
    /// Acquire  | Acquire | Acquire
    /// Release  | Release | Relaxed
    /// AcqRel   | AcqRel  | Acquire
    /// SeqCst   | SeqCst  | SeqCst
    ///
    /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
    /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
    /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
    /// rather than to infer success vs failure based on the value that was read.
    ///
    /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
    /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
    /// which allows the compiler to generate better assembly code when the compare and swap
    /// is used in a loop.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let ptr = &mut 5;
    /// let some_ptr = AtomicPtr::new(ptr);
    ///
    /// let other_ptr = &mut 10;
    ///
    /// let value = some_ptr.compare_and_swap(ptr, other_ptr, Ordering::Relaxed);
    /// ```
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[deprecated(
        since = "1.50.0",
        note = "Use `compare_exchange` or `compare_exchange_weak` instead"
    )]
    #[cfg(target_has_atomic = "ptr")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn compare_and_swap(&self, current: *mut T, new: *mut T, order: Ordering) -> *mut T {
        match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
            Ok(x) => x,
            Err(x) => x,
        }
    }
    /// Stores a value into the pointer if the current value is the same as the `current` value.
    ///
    /// The return value is a result indicating whether the new value was written and containing
    /// the previous value. On success this value is guaranteed to be equal to `current`.
    ///
    /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
    /// ordering of this operation. `success` describes the required ordering for the
    /// read-modify-write operation that takes place if the comparison with `current` succeeds.
    /// `failure` describes the required ordering for the load operation that takes place when
    /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
    /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
    /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on pointers.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let ptr = &mut 5;
    /// let some_ptr = AtomicPtr::new(ptr);
    ///
    /// let other_ptr = &mut 10;
    ///
    /// let value = some_ptr.compare_exchange(ptr, other_ptr,
    ///                                       Ordering::SeqCst, Ordering::Relaxed);
    /// ```
    ///
    /// # Considerations
    ///
    /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
    /// of CAS operations. In particular, a load of the value followed by a successful
    /// `compare_exchange` with the previous load *does not ensure* that other threads have not
    /// changed the value in the interim. This is usually important when the *equality* check in
    /// the `compare_exchange` is being used to check the *identity* of a value, but equality
    /// does not necessarily imply identity. This is a particularly common case for pointers, as
    /// a pointer holding the same address does not imply that the same object exists at that
    /// address! In this case, `compare_exchange` can lead to the [ABA problem].
    ///
    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
    #[inline]
    #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
    #[cfg(target_has_atomic = "ptr")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2
    pub fn compare_exchange(
2
        &self,
2
        current: *mut T,
2
        new: *mut T,
2
        success: Ordering,
2
        failure: Ordering,
2
    ) -> Result<*mut T, *mut T> {
        // SAFETY: data races are prevented by atomic intrinsics.
2
        unsafe { atomic_compare_exchange(self.p.get(), current, new, success, failure) }
2
    }
    /// Stores a value into the pointer if the current value is the same as the `current` value.
    ///
    /// Unlike [`AtomicPtr::compare_exchange`], this function is allowed to spuriously fail even when the
    /// comparison succeeds, which can result in more efficient code on some platforms. The
    /// return value is a result indicating whether the new value was written and containing the
    /// previous value.
    ///
    /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
    /// ordering of this operation. `success` describes the required ordering for the
    /// read-modify-write operation that takes place if the comparison with `current` succeeds.
    /// `failure` describes the required ordering for the load operation that takes place when
    /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
    /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
    /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on pointers.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let some_ptr = AtomicPtr::new(&mut 5);
    ///
    /// let new = &mut 10;
    /// let mut old = some_ptr.load(Ordering::Relaxed);
    /// loop {
    ///     match some_ptr.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
    ///         Ok(_) => break,
    ///         Err(x) => old = x,
    ///     }
    /// }
    /// ```
    ///
    /// # Considerations
    ///
    /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
    /// of CAS operations. In particular, a load of the value followed by a successful
    /// `compare_exchange` with the previous load *does not ensure* that other threads have not
    /// changed the value in the interim. This is usually important when the *equality* check in
    /// the `compare_exchange` is being used to check the *identity* of a value, but equality
    /// does not necessarily imply identity. This is a particularly common case for pointers, as
    /// a pointer holding the same address does not imply that the same object exists at that
    /// address! In this case, `compare_exchange` can lead to the [ABA problem].
    ///
    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
    #[inline]
    #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
    #[cfg(target_has_atomic = "ptr")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn compare_exchange_weak(
        &self,
        current: *mut T,
        new: *mut T,
        success: Ordering,
        failure: Ordering,
    ) -> Result<*mut T, *mut T> {
        // SAFETY: This intrinsic is unsafe because it operates on a raw pointer
        // but we know for sure that the pointer is valid (we just got it from
        // an `UnsafeCell` that we have by reference) and the atomic operation
        // itself allows us to safely mutate the `UnsafeCell` contents.
        unsafe { atomic_compare_exchange_weak(self.p.get(), current, new, success, failure) }
    }
    /// Fetches the value, and applies a function to it that returns an optional
    /// new value. Returns a `Result` of `Ok(previous_value)` if the function
    /// returned `Some(_)`, else `Err(previous_value)`.
    ///
    /// Note: This may call the function multiple times if the value has been
    /// changed from other threads in the meantime, as long as the function
    /// returns `Some(_)`, but the function will have been applied only once to
    /// the stored value.
    ///
    /// `fetch_update` takes two [`Ordering`] arguments to describe the memory
    /// ordering of this operation. The first describes the required ordering for
    /// when the operation finally succeeds while the second describes the
    /// required ordering for loads. These correspond to the success and failure
    /// orderings of [`AtomicPtr::compare_exchange`] respectively.
    ///
    /// Using [`Acquire`] as success ordering makes the store part of this
    /// operation [`Relaxed`], and using [`Release`] makes the final successful
    /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
    /// [`Acquire`] or [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on pointers.
    ///
    /// # Considerations
    ///
    /// This method is not magic; it is not provided by the hardware, and does not act like a
    /// critical section or mutex.
    ///
    /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
    /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
    /// which is a particularly common pitfall for pointers!
    ///
    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let ptr: *mut _ = &mut 5;
    /// let some_ptr = AtomicPtr::new(ptr);
    ///
    /// let new: *mut _ = &mut 10;
    /// assert_eq!(some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr));
    /// let result = some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
    ///     if x == ptr {
    ///         Some(new)
    ///     } else {
    ///         None
    ///     }
    /// });
    /// assert_eq!(result, Ok(ptr));
    /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
    /// ```
    #[inline]
    #[stable(feature = "atomic_fetch_update", since = "1.53.0")]
    #[cfg(target_has_atomic = "ptr")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_update<F>(
        &self,
        set_order: Ordering,
        fetch_order: Ordering,
        mut f: F,
    ) -> Result<*mut T, *mut T>
    where
        F: FnMut(*mut T) -> Option<*mut T>,
    {
        let mut prev = self.load(fetch_order);
        while let Some(next) = f(prev) {
            match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
                x @ Ok(_) => return x,
                Err(next_prev) => prev = next_prev,
            }
        }
        Err(prev)
    }
    /// Fetches the value, and applies a function to it that returns an optional
    /// new value. Returns a `Result` of `Ok(previous_value)` if the function
    /// returned `Some(_)`, else `Err(previous_value)`.
    ///
    /// See also: [`update`](`AtomicPtr::update`).
    ///
    /// Note: This may call the function multiple times if the value has been
    /// changed from other threads in the meantime, as long as the function
    /// returns `Some(_)`, but the function will have been applied only once to
    /// the stored value.
    ///
    /// `try_update` takes two [`Ordering`] arguments to describe the memory
    /// ordering of this operation. The first describes the required ordering for
    /// when the operation finally succeeds while the second describes the
    /// required ordering for loads. These correspond to the success and failure
    /// orderings of [`AtomicPtr::compare_exchange`] respectively.
    ///
    /// Using [`Acquire`] as success ordering makes the store part of this
    /// operation [`Relaxed`], and using [`Release`] makes the final successful
    /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
    /// [`Acquire`] or [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on pointers.
    ///
    /// # Considerations
    ///
    /// This method is not magic; it is not provided by the hardware, and does not act like a
    /// critical section or mutex.
    ///
    /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
    /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
    /// which is a particularly common pitfall for pointers!
    ///
    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
    ///
    /// # Examples
    ///
    /// ```rust
    /// #![feature(atomic_try_update)]
    /// use std::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let ptr: *mut _ = &mut 5;
    /// let some_ptr = AtomicPtr::new(ptr);
    ///
    /// let new: *mut _ = &mut 10;
    /// assert_eq!(some_ptr.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr));
    /// let result = some_ptr.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
    ///     if x == ptr {
    ///         Some(new)
    ///     } else {
    ///         None
    ///     }
    /// });
    /// assert_eq!(result, Ok(ptr));
    /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
    /// ```
    #[inline]
    #[unstable(feature = "atomic_try_update", issue = "135894")]
    #[cfg(target_has_atomic = "ptr")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn try_update(
        &self,
        set_order: Ordering,
        fetch_order: Ordering,
        f: impl FnMut(*mut T) -> Option<*mut T>,
    ) -> Result<*mut T, *mut T> {
        // FIXME(atomic_try_update): this is currently an unstable alias to `fetch_update`;
        //      when stabilizing, turn `fetch_update` into a deprecated alias to `try_update`.
        self.fetch_update(set_order, fetch_order, f)
    }
    /// Fetches the value, applies a function to it that it return a new value.
    /// The new value is stored and the old value is returned.
    ///
    /// See also: [`try_update`](`AtomicPtr::try_update`).
    ///
    /// Note: This may call the function multiple times if the value has been changed from other threads in
    /// the meantime, but the function will have been applied only once to the stored value.
    ///
    /// `update` takes two [`Ordering`] arguments to describe the memory
    /// ordering of this operation. The first describes the required ordering for
    /// when the operation finally succeeds while the second describes the
    /// required ordering for loads. These correspond to the success and failure
    /// orderings of [`AtomicPtr::compare_exchange`] respectively.
    ///
    /// Using [`Acquire`] as success ordering makes the store part
    /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
    /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
    ///
    /// **Note:** This method is only available on platforms that support atomic
    /// operations on pointers.
    ///
    /// # Considerations
    ///
    /// This method is not magic; it is not provided by the hardware, and does not act like a
    /// critical section or mutex.
    ///
    /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
    /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
    /// which is a particularly common pitfall for pointers!
    ///
    /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
    /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
    ///
    /// # Examples
    ///
    /// ```rust
    /// #![feature(atomic_try_update)]
    ///
    /// use std::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let ptr: *mut _ = &mut 5;
    /// let some_ptr = AtomicPtr::new(ptr);
    ///
    /// let new: *mut _ = &mut 10;
    /// let result = some_ptr.update(Ordering::SeqCst, Ordering::SeqCst, |_| new);
    /// assert_eq!(result, ptr);
    /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
    /// ```
    #[inline]
    #[unstable(feature = "atomic_try_update", issue = "135894")]
    #[cfg(target_has_atomic = "8")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn update(
        &self,
        set_order: Ordering,
        fetch_order: Ordering,
        mut f: impl FnMut(*mut T) -> *mut T,
    ) -> *mut T {
        let mut prev = self.load(fetch_order);
        loop {
            match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
                Ok(x) => break x,
                Err(next_prev) => prev = next_prev,
            }
        }
    }
    /// Offsets the pointer's address by adding `val` (in units of `T`),
    /// returning the previous pointer.
    ///
    /// This is equivalent to using [`wrapping_add`] to atomically perform the
    /// equivalent of `ptr = ptr.wrapping_add(val);`.
    ///
    /// This method operates in units of `T`, which means that it cannot be used
    /// to offset the pointer by an amount which is not a multiple of
    /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
    /// work with a deliberately misaligned pointer. In such cases, you may use
    /// the [`fetch_byte_add`](Self::fetch_byte_add) method instead.
    ///
    /// `fetch_ptr_add` takes an [`Ordering`] argument which describes the
    /// memory ordering of this operation. All ordering modes are possible. Note
    /// that using [`Acquire`] makes the store part of this operation
    /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note**: This method is only available on platforms that support atomic
    /// operations on [`AtomicPtr`].
    ///
    /// [`wrapping_add`]: pointer::wrapping_add
    ///
    /// # Examples
    ///
    /// ```
    /// use core::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
    /// assert_eq!(atom.fetch_ptr_add(1, Ordering::Relaxed).addr(), 0);
    /// // Note: units of `size_of::<i64>()`.
    /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 8);
    /// ```
    #[inline]
    #[cfg(target_has_atomic = "ptr")]
    #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_ptr_add(&self, val: usize, order: Ordering) -> *mut T {
        self.fetch_byte_add(val.wrapping_mul(size_of::<T>()), order)
    }
    /// Offsets the pointer's address by subtracting `val` (in units of `T`),
    /// returning the previous pointer.
    ///
    /// This is equivalent to using [`wrapping_sub`] to atomically perform the
    /// equivalent of `ptr = ptr.wrapping_sub(val);`.
    ///
    /// This method operates in units of `T`, which means that it cannot be used
    /// to offset the pointer by an amount which is not a multiple of
    /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
    /// work with a deliberately misaligned pointer. In such cases, you may use
    /// the [`fetch_byte_sub`](Self::fetch_byte_sub) method instead.
    ///
    /// `fetch_ptr_sub` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible. Note that
    /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
    /// and using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note**: This method is only available on platforms that support atomic
    /// operations on [`AtomicPtr`].
    ///
    /// [`wrapping_sub`]: pointer::wrapping_sub
    ///
    /// # Examples
    ///
    /// ```
    /// use core::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let array = [1i32, 2i32];
    /// let atom = AtomicPtr::new(array.as_ptr().wrapping_add(1) as *mut _);
    ///
    /// assert!(core::ptr::eq(
    ///     atom.fetch_ptr_sub(1, Ordering::Relaxed),
    ///     &array[1],
    /// ));
    /// assert!(core::ptr::eq(atom.load(Ordering::Relaxed), &array[0]));
    /// ```
    #[inline]
    #[cfg(target_has_atomic = "ptr")]
    #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_ptr_sub(&self, val: usize, order: Ordering) -> *mut T {
        self.fetch_byte_sub(val.wrapping_mul(size_of::<T>()), order)
    }
    /// Offsets the pointer's address by adding `val` *bytes*, returning the
    /// previous pointer.
    ///
    /// This is equivalent to using [`wrapping_byte_add`] to atomically
    /// perform `ptr = ptr.wrapping_byte_add(val)`.
    ///
    /// `fetch_byte_add` takes an [`Ordering`] argument which describes the
    /// memory ordering of this operation. All ordering modes are possible. Note
    /// that using [`Acquire`] makes the store part of this operation
    /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note**: This method is only available on platforms that support atomic
    /// operations on [`AtomicPtr`].
    ///
    /// [`wrapping_byte_add`]: pointer::wrapping_byte_add
    ///
    /// # Examples
    ///
    /// ```
    /// use core::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
    /// assert_eq!(atom.fetch_byte_add(1, Ordering::Relaxed).addr(), 0);
    /// // Note: in units of bytes, not `size_of::<i64>()`.
    /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 1);
    /// ```
    #[inline]
    #[cfg(target_has_atomic = "ptr")]
    #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T {
        // SAFETY: data races are prevented by atomic intrinsics.
        unsafe { atomic_add(self.p.get(), val, order).cast() }
    }
    /// Offsets the pointer's address by subtracting `val` *bytes*, returning the
    /// previous pointer.
    ///
    /// This is equivalent to using [`wrapping_byte_sub`] to atomically
    /// perform `ptr = ptr.wrapping_byte_sub(val)`.
    ///
    /// `fetch_byte_sub` takes an [`Ordering`] argument which describes the
    /// memory ordering of this operation. All ordering modes are possible. Note
    /// that using [`Acquire`] makes the store part of this operation
    /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note**: This method is only available on platforms that support atomic
    /// operations on [`AtomicPtr`].
    ///
    /// [`wrapping_byte_sub`]: pointer::wrapping_byte_sub
    ///
    /// # Examples
    ///
    /// ```
    /// use core::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let mut arr = [0i64, 1];
    /// let atom = AtomicPtr::<i64>::new(&raw mut arr[1]);
    /// assert_eq!(atom.fetch_byte_sub(8, Ordering::Relaxed).addr(), (&raw const arr[1]).addr());
    /// assert_eq!(atom.load(Ordering::Relaxed).addr(), (&raw const arr[0]).addr());
    /// ```
    #[inline]
    #[cfg(target_has_atomic = "ptr")]
    #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T {
        // SAFETY: data races are prevented by atomic intrinsics.
        unsafe { atomic_sub(self.p.get(), val, order).cast() }
    }
    /// Performs a bitwise "or" operation on the address of the current pointer,
    /// and the argument `val`, and stores a pointer with provenance of the
    /// current pointer and the resulting address.
    ///
    /// This is equivalent to using [`map_addr`] to atomically perform
    /// `ptr = ptr.map_addr(|a| a | val)`. This can be used in tagged
    /// pointer schemes to atomically set tag bits.
    ///
    /// **Caveat**: This operation returns the previous value. To compute the
    /// stored value without losing provenance, you may use [`map_addr`]. For
    /// example: `a.fetch_or(val).map_addr(|a| a | val)`.
    ///
    /// `fetch_or` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible. Note that
    /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
    /// and using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note**: This method is only available on platforms that support atomic
    /// operations on [`AtomicPtr`].
    ///
    /// This API and its claimed semantics are part of the Strict Provenance
    /// experiment, see the [module documentation for `ptr`][crate::ptr] for
    /// details.
    ///
    /// [`map_addr`]: pointer::map_addr
    ///
    /// # Examples
    ///
    /// ```
    /// use core::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let pointer = &mut 3i64 as *mut i64;
    ///
    /// let atom = AtomicPtr::<i64>::new(pointer);
    /// // Tag the bottom bit of the pointer.
    /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 0);
    /// // Extract and untag.
    /// let tagged = atom.load(Ordering::Relaxed);
    /// assert_eq!(tagged.addr() & 1, 1);
    /// assert_eq!(tagged.map_addr(|p| p & !1), pointer);
    /// ```
    #[inline]
    #[cfg(target_has_atomic = "ptr")]
    #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T {
        // SAFETY: data races are prevented by atomic intrinsics.
        unsafe { atomic_or(self.p.get(), val, order).cast() }
    }
    /// Performs a bitwise "and" operation on the address of the current
    /// pointer, and the argument `val`, and stores a pointer with provenance of
    /// the current pointer and the resulting address.
    ///
    /// This is equivalent to using [`map_addr`] to atomically perform
    /// `ptr = ptr.map_addr(|a| a & val)`. This can be used in tagged
    /// pointer schemes to atomically unset tag bits.
    ///
    /// **Caveat**: This operation returns the previous value. To compute the
    /// stored value without losing provenance, you may use [`map_addr`]. For
    /// example: `a.fetch_and(val).map_addr(|a| a & val)`.
    ///
    /// `fetch_and` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible. Note that
    /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
    /// and using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note**: This method is only available on platforms that support atomic
    /// operations on [`AtomicPtr`].
    ///
    /// This API and its claimed semantics are part of the Strict Provenance
    /// experiment, see the [module documentation for `ptr`][crate::ptr] for
    /// details.
    ///
    /// [`map_addr`]: pointer::map_addr
    ///
    /// # Examples
    ///
    /// ```
    /// use core::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let pointer = &mut 3i64 as *mut i64;
    /// // A tagged pointer
    /// let atom = AtomicPtr::<i64>::new(pointer.map_addr(|a| a | 1));
    /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 1);
    /// // Untag, and extract the previously tagged pointer.
    /// let untagged = atom.fetch_and(!1, Ordering::Relaxed)
    ///     .map_addr(|a| a & !1);
    /// assert_eq!(untagged, pointer);
    /// ```
    #[inline]
    #[cfg(target_has_atomic = "ptr")]
    #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T {
        // SAFETY: data races are prevented by atomic intrinsics.
        unsafe { atomic_and(self.p.get(), val, order).cast() }
    }
    /// Performs a bitwise "xor" operation on the address of the current
    /// pointer, and the argument `val`, and stores a pointer with provenance of
    /// the current pointer and the resulting address.
    ///
    /// This is equivalent to using [`map_addr`] to atomically perform
    /// `ptr = ptr.map_addr(|a| a ^ val)`. This can be used in tagged
    /// pointer schemes to atomically toggle tag bits.
    ///
    /// **Caveat**: This operation returns the previous value. To compute the
    /// stored value without losing provenance, you may use [`map_addr`]. For
    /// example: `a.fetch_xor(val).map_addr(|a| a ^ val)`.
    ///
    /// `fetch_xor` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible. Note that
    /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
    /// and using [`Release`] makes the load part [`Relaxed`].
    ///
    /// **Note**: This method is only available on platforms that support atomic
    /// operations on [`AtomicPtr`].
    ///
    /// This API and its claimed semantics are part of the Strict Provenance
    /// experiment, see the [module documentation for `ptr`][crate::ptr] for
    /// details.
    ///
    /// [`map_addr`]: pointer::map_addr
    ///
    /// # Examples
    ///
    /// ```
    /// use core::sync::atomic::{AtomicPtr, Ordering};
    ///
    /// let pointer = &mut 3i64 as *mut i64;
    /// let atom = AtomicPtr::<i64>::new(pointer);
    ///
    /// // Toggle a tag bit on the pointer.
    /// atom.fetch_xor(1, Ordering::Relaxed);
    /// assert_eq!(atom.load(Ordering::Relaxed).addr() & 1, 1);
    /// ```
    #[inline]
    #[cfg(target_has_atomic = "ptr")]
    #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T {
        // SAFETY: data races are prevented by atomic intrinsics.
        unsafe { atomic_xor(self.p.get(), val, order).cast() }
    }
    /// Returns a mutable pointer to the underlying pointer.
    ///
    /// Doing non-atomic reads and writes on the resulting pointer can be a data race.
    /// This method is mostly useful for FFI, where the function signature may use
    /// `*mut *mut T` instead of `&AtomicPtr<T>`.
    ///
    /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
    /// atomic types work with interior mutability. All modifications of an atomic change the value
    /// through a shared reference, and can do so safely as long as they use atomic operations. Any
    /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
    /// requirements of the [memory model].
    ///
    /// # Examples
    ///
    /// ```ignore (extern-declaration)
    /// use std::sync::atomic::AtomicPtr;
    ///
    /// extern "C" {
    ///     fn my_atomic_op(arg: *mut *mut u32);
    /// }
    ///
    /// let mut value = 17;
    /// let atomic = AtomicPtr::new(&mut value);
    ///
    /// // SAFETY: Safe as long as `my_atomic_op` is atomic.
    /// unsafe {
    ///     my_atomic_op(atomic.as_ptr());
    /// }
    /// ```
    ///
    /// [memory model]: self#memory-model-for-atomic-accesses
    #[inline]
    #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
    #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
    #[rustc_never_returns_null_ptr]
    pub const fn as_ptr(&self) -> *mut *mut T {
        self.p.get()
    }
}
#[cfg(target_has_atomic_load_store = "8")]
#[stable(feature = "atomic_bool_from", since = "1.24.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[cfg(not(feature = "ferrocene_certified"))]
impl const From<bool> for AtomicBool {
    /// Converts a `bool` into an `AtomicBool`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::AtomicBool;
    /// let atomic_bool = AtomicBool::from(true);
    /// assert_eq!(format!("{atomic_bool:?}"), "true")
    /// ```
    #[inline]
    fn from(b: bool) -> Self {
        Self::new(b)
    }
}
#[cfg(target_has_atomic_load_store = "ptr")]
#[stable(feature = "atomic_from", since = "1.23.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> const From<*mut T> for AtomicPtr<T> {
    /// Converts a `*mut T` into an `AtomicPtr<T>`.
    #[inline]
    fn from(p: *mut T) -> Self {
        Self::new(p)
    }
}
#[allow(unused_macros)] // This macro ends up being unused on some architectures.
macro_rules! if_8_bit {
    (u8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) };
    (i8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) };
    ($_:ident, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($no)*)?) };
}
#[cfg(target_has_atomic_load_store)]
macro_rules! atomic_int {
    ($cfg_cas:meta,
     $cfg_align:meta,
     $stable:meta,
     $stable_cxchg:meta,
     $stable_debug:meta,
     $stable_access:meta,
     $stable_from:meta,
     $stable_nand:meta,
     $const_stable_new:meta,
     $const_stable_into_inner:meta,
     $diagnostic_item:meta,
     $s_int_type:literal,
     $extra_feature:expr,
     $min_fn:ident, $max_fn:ident,
     $align:expr,
     $int_type:ident $atomic_type:ident) => {
        /// An integer type which can be safely shared between threads.
        ///
        /// This type has the same
        #[doc = if_8_bit!(
            $int_type,
            yes = ["size, alignment, and bit validity"],
            no = ["size and bit validity"],
        )]
        /// as the underlying integer type, [`
        #[doc = $s_int_type]
        /// `].
        #[doc = if_8_bit! {
            $int_type,
            no = [
                "However, the alignment of this type is always equal to its ",
                "size, even on targets where [`", $s_int_type, "`] has a ",
                "lesser alignment."
            ],
        }]
        ///
        /// For more about the differences between atomic types and
        /// non-atomic types as well as information about the portability of
        /// this type, please see the [module-level documentation].
        ///
        /// **Note:** This type is only available on platforms that support
        /// atomic loads and stores of [`
        #[doc = $s_int_type]
        /// `].
        ///
        /// [module-level documentation]: crate::sync::atomic
        #[$stable]
        #[$diagnostic_item]
        #[repr(C, align($align))]
        pub struct $atomic_type {
            v: UnsafeCell<$int_type>,
        }
        #[$stable]
        impl Default for $atomic_type {
            #[inline]
            fn default() -> Self {
                Self::new(Default::default())
            }
        }
        #[$stable_from]
        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
        impl const From<$int_type> for $atomic_type {
            #[doc = concat!("Converts an `", stringify!($int_type), "` into an `", stringify!($atomic_type), "`.")]
            #[inline]
            fn from(v: $int_type) -> Self { Self::new(v) }
        }
        #[$stable_debug]
        #[cfg(not(feature = "ferrocene_certified"))]
        impl fmt::Debug for $atomic_type {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
            }
        }
        // Send is implicitly implemented.
        #[$stable]
        unsafe impl Sync for $atomic_type {}
        impl $atomic_type {
            /// Creates a new atomic integer.
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
            ///
            #[doc = concat!("let atomic_forty_two = ", stringify!($atomic_type), "::new(42);")]
            /// ```
            #[inline]
            #[$stable]
            #[$const_stable_new]
            #[must_use]
30191
            pub const fn new(v: $int_type) -> Self {
30191
                Self {v: UnsafeCell::new(v)}
30191
            }
            /// Creates a new reference to an atomic integer from a pointer.
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{self, ", stringify!($atomic_type), "};")]
            ///
            /// // Get a pointer to an allocated value
            #[doc = concat!("let ptr: *mut ", stringify!($int_type), " = Box::into_raw(Box::new(0));")]
            ///
            #[doc = concat!("assert!(ptr.cast::<", stringify!($atomic_type), ">().is_aligned());")]
            ///
            /// {
            ///     // Create an atomic view of the allocated value
            // SAFETY: this is a doc comment, tidy, it can't hurt you (also guaranteed by the construction of `ptr` and the assert above)
            #[doc = concat!("    let atomic = unsafe {", stringify!($atomic_type), "::from_ptr(ptr) };")]
            ///
            ///     // Use `atomic` for atomic operations, possibly share it with other threads
            ///     atomic.store(1, atomic::Ordering::Relaxed);
            /// }
            ///
            /// // It's ok to non-atomically access the value behind `ptr`,
            /// // since the reference to the atomic ended its lifetime in the block above
            /// assert_eq!(unsafe { *ptr }, 1);
            ///
            /// // Deallocate the value
            /// unsafe { drop(Box::from_raw(ptr)) }
            /// ```
            ///
            /// # Safety
            ///
            /// * `ptr` must be aligned to
            #[doc = concat!("  `align_of::<", stringify!($atomic_type), ">()`")]
            #[doc = if_8_bit!{
                $int_type,
                yes = [
                    "  (note that this is always true, since `align_of::<",
                    stringify!($atomic_type), ">() == 1`)."
                ],
                no = [
                    "  (note that on some platforms this can be bigger than `align_of::<",
                    stringify!($int_type), ">()`)."
                ],
            }]
            /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
            /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
            ///   allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
            ///   sizes, without synchronization.
            ///
            /// [valid]: crate::ptr#safety
            /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
            #[inline]
            #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
            #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
            pub const unsafe fn from_ptr<'a>(ptr: *mut $int_type) -> &'a $atomic_type {
                // SAFETY: guaranteed by the caller
                unsafe { &*ptr.cast() }
            }
            /// Returns a mutable reference to the underlying integer.
            ///
            /// This is safe because the mutable reference guarantees that no other threads are
            /// concurrently accessing the atomic data.
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let mut some_var = ", stringify!($atomic_type), "::new(10);")]
            /// assert_eq!(*some_var.get_mut(), 10);
            /// *some_var.get_mut() = 5;
            /// assert_eq!(some_var.load(Ordering::SeqCst), 5);
            /// ```
            #[inline]
            #[$stable_access]
            pub fn get_mut(&mut self) -> &mut $int_type {
                self.v.get_mut()
            }
            #[doc = concat!("Get atomic access to a `&mut ", stringify!($int_type), "`.")]
            ///
            #[doc = if_8_bit! {
                $int_type,
                no = [
                    "**Note:** This function is only available on targets where `",
                    stringify!($atomic_type), "` has the same alignment as `", stringify!($int_type), "`."
                ],
            }]
            ///
            /// # Examples
            ///
            /// ```
            /// #![feature(atomic_from_mut)]
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            /// let mut some_int = 123;
            #[doc = concat!("let a = ", stringify!($atomic_type), "::from_mut(&mut some_int);")]
            /// a.store(100, Ordering::Relaxed);
            /// assert_eq!(some_int, 100);
            /// ```
            ///
            #[inline]
            #[$cfg_align]
            #[unstable(feature = "atomic_from_mut", issue = "76314")]
            pub fn from_mut(v: &mut $int_type) -> &mut Self {
                let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
                // SAFETY:
                //  - the mutable reference guarantees unique ownership.
                //  - the alignment of `$int_type` and `Self` is the
                //    same, as promised by $cfg_align and verified above.
                unsafe { &mut *(v as *mut $int_type as *mut Self) }
            }
            #[doc = concat!("Get non-atomic access to a `&mut [", stringify!($atomic_type), "]` slice")]
            ///
            /// This is safe because the mutable reference guarantees that no other threads are
            /// concurrently accessing the atomic data.
            ///
            /// # Examples
            ///
            /// ```ignore-wasm
            /// #![feature(atomic_from_mut)]
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let mut some_ints = [const { ", stringify!($atomic_type), "::new(0) }; 10];")]
            ///
            #[doc = concat!("let view: &mut [", stringify!($int_type), "] = ", stringify!($atomic_type), "::get_mut_slice(&mut some_ints);")]
            /// assert_eq!(view, [0; 10]);
            /// view
            ///     .iter_mut()
            ///     .enumerate()
            ///     .for_each(|(idx, int)| *int = idx as _);
            ///
            /// std::thread::scope(|s| {
            ///     some_ints
            ///         .iter()
            ///         .enumerate()
            ///         .for_each(|(idx, int)| {
            ///             s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
            ///         })
            /// });
            /// ```
            #[inline]
            #[unstable(feature = "atomic_from_mut", issue = "76314")]
            pub fn get_mut_slice(this: &mut [Self]) -> &mut [$int_type] {
                // SAFETY: the mutable reference guarantees unique ownership.
                unsafe { &mut *(this as *mut [Self] as *mut [$int_type]) }
            }
            #[doc = concat!("Get atomic access to a `&mut [", stringify!($int_type), "]` slice.")]
            ///
            /// # Examples
            ///
            /// ```ignore-wasm
            /// #![feature(atomic_from_mut)]
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            /// let mut some_ints = [0; 10];
            #[doc = concat!("let a = &*", stringify!($atomic_type), "::from_mut_slice(&mut some_ints);")]
            /// std::thread::scope(|s| {
            ///     for i in 0..a.len() {
            ///         s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
            ///     }
            /// });
            /// for (i, n) in some_ints.into_iter().enumerate() {
            ///     assert_eq!(i, n as usize);
            /// }
            /// ```
            #[inline]
            #[$cfg_align]
            #[unstable(feature = "atomic_from_mut", issue = "76314")]
            pub fn from_mut_slice(v: &mut [$int_type]) -> &mut [Self] {
                let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
                // SAFETY:
                //  - the mutable reference guarantees unique ownership.
                //  - the alignment of `$int_type` and `Self` is the
                //    same, as promised by $cfg_align and verified above.
                unsafe { &mut *(v as *mut [$int_type] as *mut [Self]) }
            }
            /// Consumes the atomic and returns the contained value.
            ///
            /// This is safe because passing `self` by value guarantees that no other threads are
            /// concurrently accessing the atomic data.
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
            ///
            #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
            /// assert_eq!(some_var.into_inner(), 5);
            /// ```
            #[inline]
            #[$stable_access]
            #[$const_stable_into_inner]
            pub const fn into_inner(self) -> $int_type {
                self.v.into_inner()
            }
            /// Loads a value from the atomic integer.
            ///
            /// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
            /// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
            ///
            /// # Panics
            ///
            /// Panics if `order` is [`Release`] or [`AcqRel`].
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
            ///
            /// assert_eq!(some_var.load(Ordering::Relaxed), 5);
            /// ```
            #[inline]
            #[$stable]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
270349
            pub fn load(&self, order: Ordering) -> $int_type {
                // SAFETY: data races are prevented by atomic intrinsics.
270349
                unsafe { atomic_load(self.v.get(), order) }
270349
            }
            /// Stores a value into the atomic integer.
            ///
            /// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
            ///  Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
            ///
            /// # Panics
            ///
            /// Panics if `order` is [`Acquire`] or [`AcqRel`].
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
            ///
            /// some_var.store(10, Ordering::Relaxed);
            /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
            /// ```
            #[inline]
            #[$stable]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
20784
            pub fn store(&self, val: $int_type, order: Ordering) {
                // SAFETY: data races are prevented by atomic intrinsics.
20784
                unsafe { atomic_store(self.v.get(), val, order); }
20784
            }
            /// Stores a value into the atomic integer, returning the previous value.
            ///
            /// `swap` takes an [`Ordering`] argument which describes the memory ordering
            /// of this operation. All ordering modes are possible. Note that using
            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
            /// using [`Release`] makes the load part [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
            ///
            /// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
            /// ```
            #[inline]
            #[$stable]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
67977
            pub fn swap(&self, val: $int_type, order: Ordering) -> $int_type {
                // SAFETY: data races are prevented by atomic intrinsics.
67977
                unsafe { atomic_swap(self.v.get(), val, order) }
67977
            }
            /// Stores a value into the atomic integer if the current value is the same as
            /// the `current` value.
            ///
            /// The return value is always the previous value. If it is equal to `current`, then the
            /// value was updated.
            ///
            /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
            /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
            /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
            /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
            /// happens, and using [`Release`] makes the load part [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Migrating to `compare_exchange` and `compare_exchange_weak`
            ///
            /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
            /// memory orderings:
            ///
            /// Original | Success | Failure
            /// -------- | ------- | -------
            /// Relaxed  | Relaxed | Relaxed
            /// Acquire  | Acquire | Acquire
            /// Release  | Release | Relaxed
            /// AcqRel   | AcqRel  | Acquire
            /// SeqCst   | SeqCst  | SeqCst
            ///
            /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
            /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
            /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
            /// rather than to infer success vs failure based on the value that was read.
            ///
            /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
            /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
            /// which allows the compiler to generate better assembly code when the compare and swap
            /// is used in a loop.
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
            ///
            /// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
            /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
            ///
            /// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
            /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
            /// ```
            #[inline]
            #[$stable]
            #[deprecated(
                since = "1.50.0",
                note = "Use `compare_exchange` or `compare_exchange_weak` instead")
            ]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
            pub fn compare_and_swap(&self,
                                    current: $int_type,
                                    new: $int_type,
                                    order: Ordering) -> $int_type {
                match self.compare_exchange(current,
                                            new,
                                            order,
                                            strongest_failure_ordering(order)) {
                    Ok(x) => x,
                    Err(x) => x,
                }
            }
            /// Stores a value into the atomic integer if the current value is the same as
            /// the `current` value.
            ///
            /// The return value is a result indicating whether the new value was written and
            /// containing the previous value. On success this value is guaranteed to be equal to
            /// `current`.
            ///
            /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
            /// ordering of this operation. `success` describes the required ordering for the
            /// read-modify-write operation that takes place if the comparison with `current` succeeds.
            /// `failure` describes the required ordering for the load operation that takes place when
            /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
            /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
            /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
            ///
            /// assert_eq!(some_var.compare_exchange(5, 10,
            ///                                      Ordering::Acquire,
            ///                                      Ordering::Relaxed),
            ///            Ok(5));
            /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
            ///
            /// assert_eq!(some_var.compare_exchange(6, 12,
            ///                                      Ordering::SeqCst,
            ///                                      Ordering::Acquire),
            ///            Err(10));
            /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
            /// ```
            ///
            /// # Considerations
            ///
            /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
            /// of CAS operations. In particular, a load of the value followed by a successful
            /// `compare_exchange` with the previous load *does not ensure* that other threads have not
            /// changed the value in the interim! This is usually important when the *equality* check in
            /// the `compare_exchange` is being used to check the *identity* of a value, but equality
            /// does not necessarily imply identity. This is a particularly common case for pointers, as
            /// a pointer holding the same address does not imply that the same object exists at that
            /// address! In this case, `compare_exchange` can lead to the [ABA problem].
            ///
            /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
            /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
            #[inline]
            #[$stable_cxchg]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
74911
            pub fn compare_exchange(&self,
74911
                                    current: $int_type,
74911
                                    new: $int_type,
74911
                                    success: Ordering,
74911
                                    failure: Ordering) -> Result<$int_type, $int_type> {
                // SAFETY: data races are prevented by atomic intrinsics.
74911
                unsafe { atomic_compare_exchange(self.v.get(), current, new, success, failure) }
74911
            }
            /// Stores a value into the atomic integer if the current value is the same as
            /// the `current` value.
            ///
            #[doc = concat!("Unlike [`", stringify!($atomic_type), "::compare_exchange`],")]
            /// this function is allowed to spuriously fail even
            /// when the comparison succeeds, which can result in more efficient code on some
            /// platforms. The return value is a result indicating whether the new value was
            /// written and containing the previous value.
            ///
            /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
            /// ordering of this operation. `success` describes the required ordering for the
            /// read-modify-write operation that takes place if the comparison with `current` succeeds.
            /// `failure` describes the required ordering for the load operation that takes place when
            /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
            /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
            /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let val = ", stringify!($atomic_type), "::new(4);")]
            ///
            /// let mut old = val.load(Ordering::Relaxed);
            /// loop {
            ///     let new = old * 2;
            ///     match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
            ///         Ok(_) => break,
            ///         Err(x) => old = x,
            ///     }
            /// }
            /// ```
            ///
            /// # Considerations
            ///
            /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
            /// of CAS operations. In particular, a load of the value followed by a successful
            /// `compare_exchange` with the previous load *does not ensure* that other threads have not
            /// changed the value in the interim. This is usually important when the *equality* check in
            /// the `compare_exchange` is being used to check the *identity* of a value, but equality
            /// does not necessarily imply identity. This is a particularly common case for pointers, as
            /// a pointer holding the same address does not imply that the same object exists at that
            /// address! In this case, `compare_exchange` can lead to the [ABA problem].
            ///
            /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
            /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
            #[inline]
            #[$stable_cxchg]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
5547
            pub fn compare_exchange_weak(&self,
5547
                                         current: $int_type,
5547
                                         new: $int_type,
5547
                                         success: Ordering,
5547
                                         failure: Ordering) -> Result<$int_type, $int_type> {
                // SAFETY: data races are prevented by atomic intrinsics.
                unsafe {
5547
                    atomic_compare_exchange_weak(self.v.get(), current, new, success, failure)
                }
5547
            }
            /// Adds to the current value, returning the previous value.
            ///
            /// This operation wraps around on overflow.
            ///
            /// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
            /// of this operation. All ordering modes are possible. Note that using
            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
            /// using [`Release`] makes the load part [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0);")]
            /// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
            /// assert_eq!(foo.load(Ordering::SeqCst), 10);
            /// ```
            #[inline]
            #[$stable]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
42135
            pub fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type {
                // SAFETY: data races are prevented by atomic intrinsics.
42135
                unsafe { atomic_add(self.v.get(), val, order) }
42135
            }
            /// Subtracts from the current value, returning the previous value.
            ///
            /// This operation wraps around on overflow.
            ///
            /// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
            /// of this operation. All ordering modes are possible. Note that using
            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
            /// using [`Release`] makes the load part [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(20);")]
            /// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
            /// assert_eq!(foo.load(Ordering::SeqCst), 10);
            /// ```
            #[inline]
            #[$stable]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
63812
            pub fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type {
                // SAFETY: data races are prevented by atomic intrinsics.
63812
                unsafe { atomic_sub(self.v.get(), val, order) }
63812
            }
            /// Bitwise "and" with the current value.
            ///
            /// Performs a bitwise "and" operation on the current value and the argument `val`, and
            /// sets the new value to the result.
            ///
            /// Returns the previous value.
            ///
            /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
            /// of this operation. All ordering modes are possible. Note that using
            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
            /// using [`Release`] makes the load part [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
            /// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
            /// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
            /// ```
            #[inline]
            #[$stable]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
            pub fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type {
                // SAFETY: data races are prevented by atomic intrinsics.
                unsafe { atomic_and(self.v.get(), val, order) }
            }
            /// Bitwise "nand" with the current value.
            ///
            /// Performs a bitwise "nand" operation on the current value and the argument `val`, and
            /// sets the new value to the result.
            ///
            /// Returns the previous value.
            ///
            /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
            /// of this operation. All ordering modes are possible. Note that using
            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
            /// using [`Release`] makes the load part [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0x13);")]
            /// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
            /// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
            /// ```
            #[inline]
            #[$stable_nand]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
            pub fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type {
                // SAFETY: data races are prevented by atomic intrinsics.
                unsafe { atomic_nand(self.v.get(), val, order) }
            }
            /// Bitwise "or" with the current value.
            ///
            /// Performs a bitwise "or" operation on the current value and the argument `val`, and
            /// sets the new value to the result.
            ///
            /// Returns the previous value.
            ///
            /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
            /// of this operation. All ordering modes are possible. Note that using
            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
            /// using [`Release`] makes the load part [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
            /// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
            /// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
            /// ```
            #[inline]
            #[$stable]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
5462
            pub fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type {
                // SAFETY: data races are prevented by atomic intrinsics.
5462
                unsafe { atomic_or(self.v.get(), val, order) }
5462
            }
            /// Bitwise "xor" with the current value.
            ///
            /// Performs a bitwise "xor" operation on the current value and the argument `val`, and
            /// sets the new value to the result.
            ///
            /// Returns the previous value.
            ///
            /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
            /// of this operation. All ordering modes are possible. Note that using
            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
            /// using [`Release`] makes the load part [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
            /// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
            /// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
            /// ```
            #[inline]
            #[$stable]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
            pub fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type {
                // SAFETY: data races are prevented by atomic intrinsics.
                unsafe { atomic_xor(self.v.get(), val, order) }
            }
            /// Fetches the value, and applies a function to it that returns an optional
            /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
            /// `Err(previous_value)`.
            ///
            /// Note: This may call the function multiple times if the value has been changed from other threads in
            /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
            /// only once to the stored value.
            ///
            /// `fetch_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
            /// The first describes the required ordering for when the operation finally succeeds while the second
            /// describes the required ordering for loads. These correspond to the success and failure orderings of
            #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
            /// respectively.
            ///
            /// Using [`Acquire`] as success ordering makes the store part
            /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
            /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Considerations
            ///
            /// This method is not magic; it is not provided by the hardware, and does not act like a
            /// critical section or mutex.
            ///
            /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
            /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
            /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
            /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
            ///
            /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
            /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
            ///
            /// # Examples
            ///
            /// ```rust
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
            /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
            /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
            /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
            /// assert_eq!(x.load(Ordering::SeqCst), 9);
            /// ```
            #[inline]
            #[stable(feature = "no_more_cas", since = "1.45.0")]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
            pub fn fetch_update<F>(&self,
                                   set_order: Ordering,
                                   fetch_order: Ordering,
                                   mut f: F) -> Result<$int_type, $int_type>
            where F: FnMut($int_type) -> Option<$int_type> {
                let mut prev = self.load(fetch_order);
                while let Some(next) = f(prev) {
                    match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
                        x @ Ok(_) => return x,
                        Err(next_prev) => prev = next_prev
                    }
                }
                Err(prev)
            }
            /// Fetches the value, and applies a function to it that returns an optional
            /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
            /// `Err(previous_value)`.
            ///
            #[doc = concat!("See also: [`update`](`", stringify!($atomic_type), "::update`).")]
            ///
            /// Note: This may call the function multiple times if the value has been changed from other threads in
            /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
            /// only once to the stored value.
            ///
            /// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
            /// The first describes the required ordering for when the operation finally succeeds while the second
            /// describes the required ordering for loads. These correspond to the success and failure orderings of
            #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
            /// respectively.
            ///
            /// Using [`Acquire`] as success ordering makes the store part
            /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
            /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Considerations
            ///
            /// This method is not magic; it is not provided by the hardware, and does not act like a
            /// critical section or mutex.
            ///
            /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
            /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
            /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
            /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
            ///
            /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
            /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
            ///
            /// # Examples
            ///
            /// ```rust
            /// #![feature(atomic_try_update)]
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
            /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
            /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
            /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
            /// assert_eq!(x.load(Ordering::SeqCst), 9);
            /// ```
            #[inline]
            #[unstable(feature = "atomic_try_update", issue = "135894")]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
            pub fn try_update(
                &self,
                set_order: Ordering,
                fetch_order: Ordering,
                f: impl FnMut($int_type) -> Option<$int_type>,
            ) -> Result<$int_type, $int_type> {
                // FIXME(atomic_try_update): this is currently an unstable alias to `fetch_update`;
                //      when stabilizing, turn `fetch_update` into a deprecated alias to `try_update`.
                self.fetch_update(set_order, fetch_order, f)
            }
            /// Fetches the value, applies a function to it that it return a new value.
            /// The new value is stored and the old value is returned.
            ///
            #[doc = concat!("See also: [`try_update`](`", stringify!($atomic_type), "::try_update`).")]
            ///
            /// Note: This may call the function multiple times if the value has been changed from other threads in
            /// the meantime, but the function will have been applied only once to the stored value.
            ///
            /// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
            /// The first describes the required ordering for when the operation finally succeeds while the second
            /// describes the required ordering for loads. These correspond to the success and failure orderings of
            #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
            /// respectively.
            ///
            /// Using [`Acquire`] as success ordering makes the store part
            /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
            /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Considerations
            ///
            /// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
            /// This method is not magic; it is not provided by the hardware, and does not act like a
            /// critical section or mutex.
            ///
            /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
            /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
            /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
            /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
            ///
            /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
            /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
            ///
            /// # Examples
            ///
            /// ```rust
            /// #![feature(atomic_try_update)]
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
            /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
            /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
            /// assert_eq!(x.load(Ordering::SeqCst), 9);
            /// ```
            #[inline]
            #[unstable(feature = "atomic_try_update", issue = "135894")]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
            pub fn update(
                &self,
                set_order: Ordering,
                fetch_order: Ordering,
                mut f: impl FnMut($int_type) -> $int_type,
            ) -> $int_type {
                let mut prev = self.load(fetch_order);
                loop {
                    match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
                        Ok(x) => break x,
                        Err(next_prev) => prev = next_prev,
                    }
                }
            }
            /// Maximum with the current value.
            ///
            /// Finds the maximum of the current value and the argument `val`, and
            /// sets the new value to the result.
            ///
            /// Returns the previous value.
            ///
            /// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
            /// of this operation. All ordering modes are possible. Note that using
            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
            /// using [`Release`] makes the load part [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
            /// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
            /// assert_eq!(foo.load(Ordering::SeqCst), 42);
            /// ```
            ///
            /// If you want to obtain the maximum value in one step, you can use the following:
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
            /// let bar = 42;
            /// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
            /// assert!(max_foo == 42);
            /// ```
            #[inline]
            #[stable(feature = "atomic_min_max", since = "1.45.0")]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
            pub fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type {
                // SAFETY: data races are prevented by atomic intrinsics.
                unsafe { $max_fn(self.v.get(), val, order) }
            }
            /// Minimum with the current value.
            ///
            /// Finds the minimum of the current value and the argument `val`, and
            /// sets the new value to the result.
            ///
            /// Returns the previous value.
            ///
            /// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
            /// of this operation. All ordering modes are possible. Note that using
            /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
            /// using [`Release`] makes the load part [`Relaxed`].
            ///
            /// **Note**: This method is only available on platforms that support atomic operations on
            #[doc = concat!("[`", $s_int_type, "`].")]
            ///
            /// # Examples
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
            /// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
            /// assert_eq!(foo.load(Ordering::Relaxed), 23);
            /// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
            /// assert_eq!(foo.load(Ordering::Relaxed), 22);
            /// ```
            ///
            /// If you want to obtain the minimum value in one step, you can use the following:
            ///
            /// ```
            #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
            ///
            #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
            /// let bar = 12;
            /// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
            /// assert_eq!(min_foo, 12);
            /// ```
            #[inline]
            #[stable(feature = "atomic_min_max", since = "1.45.0")]
            #[$cfg_cas]
            #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
            pub fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type {
                // SAFETY: data races are prevented by atomic intrinsics.
                unsafe { $min_fn(self.v.get(), val, order) }
            }
            /// Returns a mutable pointer to the underlying integer.
            ///
            /// Doing non-atomic reads and writes on the resulting integer can be a data race.
            /// This method is mostly useful for FFI, where the function signature may use
            #[doc = concat!("`*mut ", stringify!($int_type), "` instead of `&", stringify!($atomic_type), "`.")]
            ///
            /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
            /// atomic types work with interior mutability. All modifications of an atomic change the value
            /// through a shared reference, and can do so safely as long as they use atomic operations. Any
            /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
            /// requirements of the [memory model].
            ///
            /// # Examples
            ///
            /// ```ignore (extern-declaration)
            /// # fn main() {
            #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
            ///
            /// extern "C" {
            #[doc = concat!("    fn my_atomic_op(arg: *mut ", stringify!($int_type), ");")]
            /// }
            ///
            #[doc = concat!("let atomic = ", stringify!($atomic_type), "::new(1);")]
            ///
            /// // SAFETY: Safe as long as `my_atomic_op` is atomic.
            /// unsafe {
            ///     my_atomic_op(atomic.as_ptr());
            /// }
            /// # }
            /// ```
            ///
            /// [memory model]: self#memory-model-for-atomic-accesses
            #[inline]
            #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
            #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
            #[rustc_never_returns_null_ptr]
            pub const fn as_ptr(&self) -> *mut $int_type {
                self.v.get()
            }
        }
    }
}
#[cfg(target_has_atomic_load_store = "8")]
#[cfg(not(feature = "ferrocene_certified"))]
atomic_int! {
    cfg(target_has_atomic = "8"),
    cfg(target_has_atomic_equal_alignment = "8"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
    rustc_diagnostic_item = "AtomicI8",
    "i8",
    "",
    atomic_min, atomic_max,
    1,
    i8 AtomicI8
}
#[cfg(target_has_atomic_load_store = "8")]
#[cfg(not(feature = "ferrocene_certified"))]
atomic_int! {
    cfg(target_has_atomic = "8"),
    cfg(target_has_atomic_equal_alignment = "8"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
    rustc_diagnostic_item = "AtomicU8",
    "u8",
    "",
    atomic_umin, atomic_umax,
    1,
    u8 AtomicU8
}
#[cfg(target_has_atomic_load_store = "16")]
#[cfg(not(feature = "ferrocene_certified"))]
atomic_int! {
    cfg(target_has_atomic = "16"),
    cfg(target_has_atomic_equal_alignment = "16"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
    rustc_diagnostic_item = "AtomicI16",
    "i16",
    "",
    atomic_min, atomic_max,
    2,
    i16 AtomicI16
}
#[cfg(target_has_atomic_load_store = "16")]
#[cfg(not(feature = "ferrocene_certified"))]
atomic_int! {
    cfg(target_has_atomic = "16"),
    cfg(target_has_atomic_equal_alignment = "16"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
    rustc_diagnostic_item = "AtomicU16",
    "u16",
    "",
    atomic_umin, atomic_umax,
    2,
    u16 AtomicU16
}
#[cfg(target_has_atomic_load_store = "32")]
#[cfg(not(feature = "ferrocene_certified"))]
atomic_int! {
    cfg(target_has_atomic = "32"),
    cfg(target_has_atomic_equal_alignment = "32"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
    rustc_diagnostic_item = "AtomicI32",
    "i32",
    "",
    atomic_min, atomic_max,
    4,
    i32 AtomicI32
}
#[cfg(target_has_atomic_load_store = "32")]
atomic_int! {
    cfg(target_has_atomic = "32"),
    cfg(target_has_atomic_equal_alignment = "32"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
    rustc_diagnostic_item = "AtomicU32",
    "u32",
    "",
    atomic_umin, atomic_umax,
    4,
    u32 AtomicU32
}
#[cfg(target_has_atomic_load_store = "64")]
#[cfg(not(feature = "ferrocene_certified"))]
atomic_int! {
    cfg(target_has_atomic = "64"),
    cfg(target_has_atomic_equal_alignment = "64"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
    rustc_diagnostic_item = "AtomicI64",
    "i64",
    "",
    atomic_min, atomic_max,
    8,
    i64 AtomicI64
}
#[cfg(target_has_atomic_load_store = "64")]
#[cfg(not(feature = "ferrocene_certified"))]
atomic_int! {
    cfg(target_has_atomic = "64"),
    cfg(target_has_atomic_equal_alignment = "64"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    stable(feature = "integer_atomics_stable", since = "1.34.0"),
    rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
    rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
    rustc_diagnostic_item = "AtomicU64",
    "u64",
    "",
    atomic_umin, atomic_umax,
    8,
    u64 AtomicU64
}
#[cfg(target_has_atomic_load_store = "128")]
#[cfg(not(feature = "ferrocene_certified"))]
atomic_int! {
    cfg(target_has_atomic = "128"),
    cfg(target_has_atomic_equal_alignment = "128"),
    unstable(feature = "integer_atomics", issue = "99069"),
    unstable(feature = "integer_atomics", issue = "99069"),
    unstable(feature = "integer_atomics", issue = "99069"),
    unstable(feature = "integer_atomics", issue = "99069"),
    unstable(feature = "integer_atomics", issue = "99069"),
    unstable(feature = "integer_atomics", issue = "99069"),
    rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
    rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
    rustc_diagnostic_item = "AtomicI128",
    "i128",
    "#![feature(integer_atomics)]\n\n",
    atomic_min, atomic_max,
    16,
    i128 AtomicI128
}
#[cfg(target_has_atomic_load_store = "128")]
#[cfg(not(feature = "ferrocene_certified"))]
atomic_int! {
    cfg(target_has_atomic = "128"),
    cfg(target_has_atomic_equal_alignment = "128"),
    unstable(feature = "integer_atomics", issue = "99069"),
    unstable(feature = "integer_atomics", issue = "99069"),
    unstable(feature = "integer_atomics", issue = "99069"),
    unstable(feature = "integer_atomics", issue = "99069"),
    unstable(feature = "integer_atomics", issue = "99069"),
    unstable(feature = "integer_atomics", issue = "99069"),
    rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
    rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
    rustc_diagnostic_item = "AtomicU128",
    "u128",
    "#![feature(integer_atomics)]\n\n",
    atomic_umin, atomic_umax,
    16,
    u128 AtomicU128
}
#[cfg(target_has_atomic_load_store = "ptr")]
#[cfg(not(feature = "ferrocene_certified"))]
macro_rules! atomic_int_ptr_sized {
    ( $($target_pointer_width:literal $align:literal)* ) => { $(
        #[cfg(target_pointer_width = $target_pointer_width)]
        atomic_int! {
            cfg(target_has_atomic = "ptr"),
            cfg(target_has_atomic_equal_alignment = "ptr"),
            stable(feature = "rust1", since = "1.0.0"),
            stable(feature = "extended_compare_and_swap", since = "1.10.0"),
            stable(feature = "atomic_debug", since = "1.3.0"),
            stable(feature = "atomic_access", since = "1.15.0"),
            stable(feature = "atomic_from", since = "1.23.0"),
            stable(feature = "atomic_nand", since = "1.27.0"),
            rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
            rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
            rustc_diagnostic_item = "AtomicIsize",
            "isize",
            "",
            atomic_min, atomic_max,
            $align,
            isize AtomicIsize
        }
        #[cfg(target_pointer_width = $target_pointer_width)]
        atomic_int! {
            cfg(target_has_atomic = "ptr"),
            cfg(target_has_atomic_equal_alignment = "ptr"),
            stable(feature = "rust1", since = "1.0.0"),
            stable(feature = "extended_compare_and_swap", since = "1.10.0"),
            stable(feature = "atomic_debug", since = "1.3.0"),
            stable(feature = "atomic_access", since = "1.15.0"),
            stable(feature = "atomic_from", since = "1.23.0"),
            stable(feature = "atomic_nand", since = "1.27.0"),
            rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
            rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
            rustc_diagnostic_item = "AtomicUsize",
            "usize",
            "",
            atomic_umin, atomic_umax,
            $align,
            usize AtomicUsize
        }
        /// An [`AtomicIsize`] initialized to `0`.
        #[cfg(target_pointer_width = $target_pointer_width)]
        #[stable(feature = "rust1", since = "1.0.0")]
        #[deprecated(
            since = "1.34.0",
            note = "the `new` function is now preferred",
            suggestion = "AtomicIsize::new(0)",
        )]
        pub const ATOMIC_ISIZE_INIT: AtomicIsize = AtomicIsize::new(0);
        /// An [`AtomicUsize`] initialized to `0`.
        #[cfg(target_pointer_width = $target_pointer_width)]
        #[stable(feature = "rust1", since = "1.0.0")]
        #[deprecated(
            since = "1.34.0",
            note = "the `new` function is now preferred",
            suggestion = "AtomicUsize::new(0)",
        )]
        pub const ATOMIC_USIZE_INIT: AtomicUsize = AtomicUsize::new(0);
    )* };
}
#[cfg(target_has_atomic_load_store = "ptr")]
#[cfg(not(feature = "ferrocene_certified"))]
atomic_int_ptr_sized! {
    "16" 2
    "32" 4
    "64" 8
}
#[inline]
#[cfg(target_has_atomic)]
fn strongest_failure_ordering(order: Ordering) -> Ordering {
    match order {
        Release => Relaxed,
        Relaxed => Relaxed,
        SeqCst => SeqCst,
        Acquire => Acquire,
        AcqRel => Acquire,
    }
}
#[inline]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
8582
unsafe fn atomic_store<T: Copy>(dst: *mut T, val: T, order: Ordering) {
    // SAFETY: the caller must uphold the safety contract for `atomic_store`.
    unsafe {
8582
        match order {
2
            Relaxed => intrinsics::atomic_store::<T, { AO::Relaxed }>(dst, val),
5838
            Release => intrinsics::atomic_store::<T, { AO::Release }>(dst, val),
2742
            SeqCst => intrinsics::atomic_store::<T, { AO::SeqCst }>(dst, val),
            Acquire => panic!("there is no such thing as an acquire store"),
            AcqRel => panic!("there is no such thing as an acquire-release store"),
        }
    }
8582
}
#[inline]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
64721
unsafe fn atomic_load<T: Copy>(dst: *const T, order: Ordering) -> T {
    // SAFETY: the caller must uphold the safety contract for `atomic_load`.
    unsafe {
64721
        match order {
31612
            Relaxed => intrinsics::atomic_load::<T, { AO::Relaxed }>(dst),
24848
            Acquire => intrinsics::atomic_load::<T, { AO::Acquire }>(dst),
8261
            SeqCst => intrinsics::atomic_load::<T, { AO::SeqCst }>(dst),
            Release => panic!("there is no such thing as a release load"),
            AcqRel => panic!("there is no such thing as an acquire-release load"),
        }
    }
64721
}
#[inline]
#[cfg(target_has_atomic)]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
9595
unsafe fn atomic_swap<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
    // SAFETY: the caller must uphold the safety contract for `atomic_swap`.
    unsafe {
9595
        match order {
            Relaxed => intrinsics::atomic_xchg::<T, { AO::Relaxed }>(dst, val),
            Acquire => intrinsics::atomic_xchg::<T, { AO::Acquire }>(dst, val),
9589
            Release => intrinsics::atomic_xchg::<T, { AO::Release }>(dst, val),
6
            AcqRel => intrinsics::atomic_xchg::<T, { AO::AcqRel }>(dst, val),
            SeqCst => intrinsics::atomic_xchg::<T, { AO::SeqCst }>(dst, val),
        }
    }
9595
}
/// Returns the previous value (like __sync_fetch_and_add).
#[inline]
#[cfg(target_has_atomic)]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
17913
unsafe fn atomic_add<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
    // SAFETY: the caller must uphold the safety contract for `atomic_add`.
    unsafe {
17913
        match order {
17824
            Relaxed => intrinsics::atomic_xadd::<T, U, { AO::Relaxed }>(dst, val),
            Acquire => intrinsics::atomic_xadd::<T, U, { AO::Acquire }>(dst, val),
89
            Release => intrinsics::atomic_xadd::<T, U, { AO::Release }>(dst, val),
            AcqRel => intrinsics::atomic_xadd::<T, U, { AO::AcqRel }>(dst, val),
            SeqCst => intrinsics::atomic_xadd::<T, U, { AO::SeqCst }>(dst, val),
        }
    }
17913
}
/// Returns the previous value (like __sync_fetch_and_sub).
#[inline]
#[cfg(target_has_atomic)]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
31514
unsafe fn atomic_sub<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
    // SAFETY: the caller must uphold the safety contract for `atomic_sub`.
    unsafe {
31514
        match order {
            Relaxed => intrinsics::atomic_xsub::<T, U, { AO::Relaxed }>(dst, val),
            Acquire => intrinsics::atomic_xsub::<T, U, { AO::Acquire }>(dst, val),
28737
            Release => intrinsics::atomic_xsub::<T, U, { AO::Release }>(dst, val),
2777
            AcqRel => intrinsics::atomic_xsub::<T, U, { AO::AcqRel }>(dst, val),
            SeqCst => intrinsics::atomic_xsub::<T, U, { AO::SeqCst }>(dst, val),
        }
    }
31514
}
/// Publicly exposed for stdarch; nobody else should use this.
#[inline]
#[cfg(target_has_atomic)]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
#[unstable(feature = "core_intrinsics", issue = "none")]
#[doc(hidden)]
12329
pub unsafe fn atomic_compare_exchange<T: Copy>(
12329
    dst: *mut T,
12329
    old: T,
12329
    new: T,
12329
    success: Ordering,
12329
    failure: Ordering,
12329
) -> Result<T, T> {
    // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`.
12329
    let (val, ok) = unsafe {
12329
        match (success, failure) {
            (Relaxed, Relaxed) => {
                intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::Relaxed }>(dst, old, new)
            }
            (Relaxed, Acquire) => {
                intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::Acquire }>(dst, old, new)
            }
            (Relaxed, SeqCst) => {
                intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::SeqCst }>(dst, old, new)
            }
            (Acquire, Relaxed) => {
10956
                intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::Relaxed }>(dst, old, new)
            }
            (Acquire, Acquire) => {
                intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::Acquire }>(dst, old, new)
            }
            (Acquire, SeqCst) => {
                intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::SeqCst }>(dst, old, new)
            }
            (Release, Relaxed) => {
2
                intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::Relaxed }>(dst, old, new)
            }
            (Release, Acquire) => {
                intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::Acquire }>(dst, old, new)
            }
            (Release, SeqCst) => {
                intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::SeqCst }>(dst, old, new)
            }
            (AcqRel, Relaxed) => {
                intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::Relaxed }>(dst, old, new)
            }
            (AcqRel, Acquire) => {
1371
                intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::Acquire }>(dst, old, new)
            }
            (AcqRel, SeqCst) => {
                intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::SeqCst }>(dst, old, new)
            }
            (SeqCst, Relaxed) => {
                intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::Relaxed }>(dst, old, new)
            }
            (SeqCst, Acquire) => {
                intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::Acquire }>(dst, old, new)
            }
            (SeqCst, SeqCst) => {
                intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::SeqCst }>(dst, old, new)
            }
            (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
            (_, Release) => panic!("there is no such thing as a release failure ordering"),
        }
    };
12329
    if ok { Ok(val) } else { Err(val) }
12329
}
#[inline]
#[cfg(target_has_atomic)]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
5547
unsafe fn atomic_compare_exchange_weak<T: Copy>(
5547
    dst: *mut T,
5547
    old: T,
5547
    new: T,
5547
    success: Ordering,
5547
    failure: Ordering,
5547
) -> Result<T, T> {
    // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`.
5547
    let (val, ok) = unsafe {
5547
        match (success, failure) {
            (Relaxed, Relaxed) => {
                intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::Relaxed }>(dst, old, new)
            }
            (Relaxed, Acquire) => {
                intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::Acquire }>(dst, old, new)
            }
            (Relaxed, SeqCst) => {
                intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::SeqCst }>(dst, old, new)
            }
            (Acquire, Relaxed) => {
                intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::Relaxed }>(dst, old, new)
            }
            (Acquire, Acquire) => {
                intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::Acquire }>(dst, old, new)
            }
            (Acquire, SeqCst) => {
                intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::SeqCst }>(dst, old, new)
            }
            (Release, Relaxed) => {
                intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::Relaxed }>(dst, old, new)
            }
            (Release, Acquire) => {
                intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::Acquire }>(dst, old, new)
            }
            (Release, SeqCst) => {
                intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::SeqCst }>(dst, old, new)
            }
            (AcqRel, Relaxed) => {
                intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::Relaxed }>(dst, old, new)
            }
            (AcqRel, Acquire) => {
                intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::Acquire }>(dst, old, new)
            }
            (AcqRel, SeqCst) => {
                intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::SeqCst }>(dst, old, new)
            }
            (SeqCst, Relaxed) => {
                intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::Relaxed }>(dst, old, new)
            }
            (SeqCst, Acquire) => {
5547
                intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::Acquire }>(dst, old, new)
            }
            (SeqCst, SeqCst) => {
                intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::SeqCst }>(dst, old, new)
            }
            (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
            (_, Release) => panic!("there is no such thing as a release failure ordering"),
        }
    };
5547
    if ok { Ok(val) } else { Err(val) }
5547
}
#[inline]
#[cfg(target_has_atomic)]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
unsafe fn atomic_and<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
    // SAFETY: the caller must uphold the safety contract for `atomic_and`
    unsafe {
        match order {
            Relaxed => intrinsics::atomic_and::<T, U, { AO::Relaxed }>(dst, val),
            Acquire => intrinsics::atomic_and::<T, U, { AO::Acquire }>(dst, val),
            Release => intrinsics::atomic_and::<T, U, { AO::Release }>(dst, val),
            AcqRel => intrinsics::atomic_and::<T, U, { AO::AcqRel }>(dst, val),
            SeqCst => intrinsics::atomic_and::<T, U, { AO::SeqCst }>(dst, val),
        }
    }
}
#[inline]
#[cfg(target_has_atomic)]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
unsafe fn atomic_nand<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
    // SAFETY: the caller must uphold the safety contract for `atomic_nand`
    unsafe {
        match order {
            Relaxed => intrinsics::atomic_nand::<T, U, { AO::Relaxed }>(dst, val),
            Acquire => intrinsics::atomic_nand::<T, U, { AO::Acquire }>(dst, val),
            Release => intrinsics::atomic_nand::<T, U, { AO::Release }>(dst, val),
            AcqRel => intrinsics::atomic_nand::<T, U, { AO::AcqRel }>(dst, val),
            SeqCst => intrinsics::atomic_nand::<T, U, { AO::SeqCst }>(dst, val),
        }
    }
}
#[inline]
#[cfg(target_has_atomic)]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
5461
unsafe fn atomic_or<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
    // SAFETY: the caller must uphold the safety contract for `atomic_or`
    unsafe {
5461
        match order {
4
            SeqCst => intrinsics::atomic_or::<T, U, { AO::SeqCst }>(dst, val),
            Acquire => intrinsics::atomic_or::<T, U, { AO::Acquire }>(dst, val),
2773
            Release => intrinsics::atomic_or::<T, U, { AO::Release }>(dst, val),
2684
            AcqRel => intrinsics::atomic_or::<T, U, { AO::AcqRel }>(dst, val),
            Relaxed => intrinsics::atomic_or::<T, U, { AO::Relaxed }>(dst, val),
        }
    }
5461
}
#[inline]
#[cfg(target_has_atomic)]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
unsafe fn atomic_xor<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
    // SAFETY: the caller must uphold the safety contract for `atomic_xor`
    unsafe {
        match order {
            SeqCst => intrinsics::atomic_xor::<T, U, { AO::SeqCst }>(dst, val),
            Acquire => intrinsics::atomic_xor::<T, U, { AO::Acquire }>(dst, val),
            Release => intrinsics::atomic_xor::<T, U, { AO::Release }>(dst, val),
            AcqRel => intrinsics::atomic_xor::<T, U, { AO::AcqRel }>(dst, val),
            Relaxed => intrinsics::atomic_xor::<T, U, { AO::Relaxed }>(dst, val),
        }
    }
}
/// Updates `*dst` to the max value of `val` and the old value (signed comparison)
#[inline]
#[cfg(target_has_atomic)]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
#[cfg(not(feature = "ferrocene_certified"))]
unsafe fn atomic_max<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
    // SAFETY: the caller must uphold the safety contract for `atomic_max`
    unsafe {
        match order {
            Relaxed => intrinsics::atomic_max::<T, { AO::Relaxed }>(dst, val),
            Acquire => intrinsics::atomic_max::<T, { AO::Acquire }>(dst, val),
            Release => intrinsics::atomic_max::<T, { AO::Release }>(dst, val),
            AcqRel => intrinsics::atomic_max::<T, { AO::AcqRel }>(dst, val),
            SeqCst => intrinsics::atomic_max::<T, { AO::SeqCst }>(dst, val),
        }
    }
}
/// Updates `*dst` to the min value of `val` and the old value (signed comparison)
#[inline]
#[cfg(target_has_atomic)]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
#[cfg(not(feature = "ferrocene_certified"))]
unsafe fn atomic_min<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
    // SAFETY: the caller must uphold the safety contract for `atomic_min`
    unsafe {
        match order {
            Relaxed => intrinsics::atomic_min::<T, { AO::Relaxed }>(dst, val),
            Acquire => intrinsics::atomic_min::<T, { AO::Acquire }>(dst, val),
            Release => intrinsics::atomic_min::<T, { AO::Release }>(dst, val),
            AcqRel => intrinsics::atomic_min::<T, { AO::AcqRel }>(dst, val),
            SeqCst => intrinsics::atomic_min::<T, { AO::SeqCst }>(dst, val),
        }
    }
}
/// Updates `*dst` to the max value of `val` and the old value (unsigned comparison)
#[inline]
#[cfg(target_has_atomic)]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
unsafe fn atomic_umax<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
    // SAFETY: the caller must uphold the safety contract for `atomic_umax`
    unsafe {
        match order {
            Relaxed => intrinsics::atomic_umax::<T, { AO::Relaxed }>(dst, val),
            Acquire => intrinsics::atomic_umax::<T, { AO::Acquire }>(dst, val),
            Release => intrinsics::atomic_umax::<T, { AO::Release }>(dst, val),
            AcqRel => intrinsics::atomic_umax::<T, { AO::AcqRel }>(dst, val),
            SeqCst => intrinsics::atomic_umax::<T, { AO::SeqCst }>(dst, val),
        }
    }
}
/// Updates `*dst` to the min value of `val` and the old value (unsigned comparison)
#[inline]
#[cfg(target_has_atomic)]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
unsafe fn atomic_umin<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
    // SAFETY: the caller must uphold the safety contract for `atomic_umin`
    unsafe {
        match order {
            Relaxed => intrinsics::atomic_umin::<T, { AO::Relaxed }>(dst, val),
            Acquire => intrinsics::atomic_umin::<T, { AO::Acquire }>(dst, val),
            Release => intrinsics::atomic_umin::<T, { AO::Release }>(dst, val),
            AcqRel => intrinsics::atomic_umin::<T, { AO::AcqRel }>(dst, val),
            SeqCst => intrinsics::atomic_umin::<T, { AO::SeqCst }>(dst, val),
        }
    }
}
/// An atomic fence.
///
/// Fences create synchronization between themselves and atomic operations or fences in other
/// threads. To achieve this, a fence prevents the compiler and CPU from reordering certain types of
/// memory operations around it.
///
/// A fence 'A' which has (at least) [`Release`] ordering semantics, synchronizes
/// with a fence 'B' with (at least) [`Acquire`] semantics, if and only if there
/// exist operations X and Y, both operating on some atomic object 'm' such
/// that A is sequenced before X, Y is sequenced before B and Y observes
/// the change to m. This provides a happens-before dependence between A and B.
///
/// ```text
///     Thread 1                                          Thread 2
///
/// fence(Release);      A --------------
/// m.store(3, Relaxed); X ---------    |
///                                |    |
///                                |    |
///                                -------------> Y  if m.load(Relaxed) == 3 {
///                                     |-------> B      fence(Acquire);
///                                                      ...
///                                                  }
/// ```
///
/// Note that in the example above, it is crucial that the accesses to `m` are atomic. Fences cannot
/// be used to establish synchronization among non-atomic accesses in different threads. However,
/// thanks to the happens-before relationship between A and B, any non-atomic accesses that
/// happen-before A are now also properly synchronized with any non-atomic accesses that
/// happen-after B.
///
/// Atomic operations with [`Release`] or [`Acquire`] semantics can also synchronize
/// with a fence.
///
/// A fence which has [`SeqCst`] ordering, in addition to having both [`Acquire`]
/// and [`Release`] semantics, participates in the global program order of the
/// other [`SeqCst`] operations and/or fences.
///
/// Accepts [`Acquire`], [`Release`], [`AcqRel`] and [`SeqCst`] orderings.
///
/// # Panics
///
/// Panics if `order` is [`Relaxed`].
///
/// # Examples
///
/// ```
/// use std::sync::atomic::AtomicBool;
/// use std::sync::atomic::fence;
/// use std::sync::atomic::Ordering;
///
/// // A mutual exclusion primitive based on spinlock.
/// pub struct Mutex {
///     flag: AtomicBool,
/// }
///
/// impl Mutex {
///     pub fn new() -> Mutex {
///         Mutex {
///             flag: AtomicBool::new(false),
///         }
///     }
///
///     pub fn lock(&self) {
///         // Wait until the old value is `false`.
///         while self
///             .flag
///             .compare_exchange_weak(false, true, Ordering::Relaxed, Ordering::Relaxed)
///             .is_err()
///         {}
///         // This fence synchronizes-with store in `unlock`.
///         fence(Ordering::Acquire);
///     }
///
///     pub fn unlock(&self) {
///         self.flag.store(false, Ordering::Release);
///     }
/// }
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_diagnostic_item = "fence"]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
#[cfg(not(feature = "ferrocene_certified"))]
pub fn fence(order: Ordering) {
    // SAFETY: using an atomic fence is safe.
    unsafe {
        match order {
            Acquire => intrinsics::atomic_fence::<{ AO::Acquire }>(),
            Release => intrinsics::atomic_fence::<{ AO::Release }>(),
            AcqRel => intrinsics::atomic_fence::<{ AO::AcqRel }>(),
            SeqCst => intrinsics::atomic_fence::<{ AO::SeqCst }>(),
            Relaxed => panic!("there is no such thing as a relaxed fence"),
        }
    }
}
/// A "compiler-only" atomic fence.
///
/// Like [`fence`], this function establishes synchronization with other atomic operations and
/// fences. However, unlike [`fence`], `compiler_fence` only establishes synchronization with
/// operations *in the same thread*. This may at first sound rather useless, since code within a
/// thread is typically already totally ordered and does not need any further synchronization.
/// However, there are cases where code can run on the same thread without being ordered:
/// - The most common case is that of a *signal handler*: a signal handler runs in the same thread
///   as the code it interrupted, but it is not ordered with respect to that code. `compiler_fence`
///   can be used to establish synchronization between a thread and its signal handler, the same way
///   that `fence` can be used to establish synchronization across threads.
/// - Similar situations can arise in embedded programming with interrupt handlers, or in custom
///   implementations of preemptive green threads. In general, `compiler_fence` can establish
///   synchronization with code that is guaranteed to run on the same hardware CPU.
///
/// See [`fence`] for how a fence can be used to achieve synchronization. Note that just like
/// [`fence`], synchronization still requires atomic operations to be used in both threads -- it is
/// not possible to perform synchronization entirely with fences and non-atomic operations.
///
/// `compiler_fence` does not emit any machine code, but restricts the kinds of memory re-ordering
/// the compiler is allowed to do. `compiler_fence` corresponds to [`atomic_signal_fence`] in C and
/// C++.
///
/// [`atomic_signal_fence`]: https://en.cppreference.com/w/cpp/atomic/atomic_signal_fence
///
/// # Panics
///
/// Panics if `order` is [`Relaxed`].
///
/// # Examples
///
/// Without the two `compiler_fence` calls, the read of `IMPORTANT_VARIABLE` in `signal_handler`
/// is *undefined behavior* due to a data race, despite everything happening in a single thread.
/// This is because the signal handler is considered to run concurrently with its associated
/// thread, and explicit synchronization is required to pass data between a thread and its
/// signal handler. The code below uses two `compiler_fence` calls to establish the usual
/// release-acquire synchronization pattern (see [`fence`] for an image).
///
/// ```
/// use std::sync::atomic::AtomicBool;
/// use std::sync::atomic::Ordering;
/// use std::sync::atomic::compiler_fence;
///
/// static mut IMPORTANT_VARIABLE: usize = 0;
/// static IS_READY: AtomicBool = AtomicBool::new(false);
///
/// fn main() {
///     unsafe { IMPORTANT_VARIABLE = 42 };
///     // Marks earlier writes as being released with future relaxed stores.
///     compiler_fence(Ordering::Release);
///     IS_READY.store(true, Ordering::Relaxed);
/// }
///
/// fn signal_handler() {
///     if IS_READY.load(Ordering::Relaxed) {
///         // Acquires writes that were released with relaxed stores that we read from.
///         compiler_fence(Ordering::Acquire);
///         assert_eq!(unsafe { IMPORTANT_VARIABLE }, 42);
///     }
/// }
/// ```
#[inline]
#[stable(feature = "compiler_fences", since = "1.21.0")]
#[rustc_diagnostic_item = "compiler_fence"]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
#[cfg(not(feature = "ferrocene_certified"))]
pub fn compiler_fence(order: Ordering) {
    // SAFETY: using an atomic fence is safe.
    unsafe {
        match order {
            Acquire => intrinsics::atomic_singlethreadfence::<{ AO::Acquire }>(),
            Release => intrinsics::atomic_singlethreadfence::<{ AO::Release }>(),
            AcqRel => intrinsics::atomic_singlethreadfence::<{ AO::AcqRel }>(),
            SeqCst => intrinsics::atomic_singlethreadfence::<{ AO::SeqCst }>(),
            Relaxed => panic!("there is no such thing as a relaxed fence"),
        }
    }
}
#[cfg(target_has_atomic_load_store = "8")]
#[stable(feature = "atomic_debug", since = "1.3.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl fmt::Debug for AtomicBool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
    }
}
#[cfg(target_has_atomic_load_store = "ptr")]
#[stable(feature = "atomic_debug", since = "1.3.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> fmt::Debug for AtomicPtr<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
    }
}
#[cfg(target_has_atomic_load_store = "ptr")]
#[stable(feature = "atomic_pointer", since = "1.24.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> fmt::Pointer for AtomicPtr<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Pointer::fmt(&self.load(Ordering::Relaxed), f)
    }
}
/// Signals the processor that it is inside a busy-wait spin-loop ("spin lock").
///
/// This function is deprecated in favor of [`hint::spin_loop`].
///
/// [`hint::spin_loop`]: crate::hint::spin_loop
#[inline]
#[stable(feature = "spin_loop_hint", since = "1.24.0")]
#[deprecated(since = "1.51.0", note = "use hint::spin_loop instead")]
#[cfg(not(feature = "ferrocene_certified"))]
pub fn spin_loop_hint() {
    spin_loop()
}