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