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