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