1//! Atomic types
2//!
3//! Atomic types provide primitive shared-memory communication between
4//! threads, and are the building blocks of other concurrent
5//! types.
6//!
7//! This module defines atomic versions of a select number of primitive
8//! types, including [`AtomicBool`], [`AtomicIsize`], [`AtomicUsize`],
9//! [`AtomicI8`], [`AtomicU16`], etc.
10//! Atomic types present operations that, when used correctly, synchronize
11//! updates between threads.
12//!
13//! Atomic variables are safe to share between threads (they implement [`Sync`])
14//! but they do not themselves provide the mechanism for sharing and follow the
15//! [threading model](../../../std/thread/index.html#the-threading-model) of Rust.
16//! The most common way to share an atomic variable is to put it into an [`Arc`][arc] (an
17//! atomically-reference-counted shared pointer).
18//!
19//! [arc]: ../../../std/sync/struct.Arc.html
20//!
21//! Atomic types may be stored in static variables, initialized using
22//! the constant initializers like [`AtomicBool::new`]. Atomic statics
23//! are often used for lazy global initialization.
24//!
25//! ## Memory model for atomic accesses
26//!
27//! Rust atomics currently follow the same rules as [C++20 atomics][cpp], specifically the rules
28//! from the [`intro.races`][cpp-intro.races] section, without the "consume" memory ordering. Since
29//! C++ uses an object-based memory model whereas Rust is access-based, a bit of translation work
30//! has to be done to apply the C++ rules to Rust: whenever C++ talks about "the value of an
31//! object", we understand that to mean the resulting bytes obtained when doing a read. When the C++
32//! standard talks about "the value of an atomic object", this refers to the result of doing an
33//! atomic load (via the operations provided in this module). A "modification of an atomic object"
34//! refers to an atomic store.
35//!
36//! The end result is *almost* equivalent to saying that creating a *shared reference* to one of the
37//! Rust atomic types corresponds to creating an `atomic_ref` in C++, with the `atomic_ref` being
38//! destroyed when the lifetime of the shared reference ends. The main difference is that Rust
39//! permits concurrent atomic and non-atomic reads to the same memory as those cause no issue in the
40//! C++ memory model, they are just forbidden in C++ because memory is partitioned into "atomic
41//! objects" and "non-atomic objects" (with `atomic_ref` temporarily converting a non-atomic object
42//! into an atomic object).
43//!
44//! The most important aspect of this model is that *data races* are undefined behavior. A data race
45//! is defined as conflicting non-synchronized accesses where at least one of the accesses is
46//! non-atomic. Here, accesses are *conflicting* if they affect overlapping regions of memory and at
47//! least one of them is a write. (A `compare_exchange` or `compare_exchange_weak` that does not
48//! succeed is not considered a write.) They are *non-synchronized* if neither of them
49//! *happens-before* the other, according to the happens-before order of the memory model.
50//!
51//! The other possible cause of undefined behavior in the memory model are mixed-size accesses: Rust
52//! inherits the C++ limitation that non-synchronized conflicting atomic accesses may not partially
53//! overlap. In other words, every pair of non-synchronized atomic accesses must be either disjoint,
54//! access the exact same memory (including using the same access size), or both be reads.
55//!
56//! Each atomic access takes an [`Ordering`] which defines how the operation interacts with the
57//! happens-before order. These orderings behave the same as the corresponding [C++20 atomic
58//! orderings][cpp_memory_order]. For more information, see the [nomicon].
59//!
60//! [cpp]: https://en.cppreference.com/w/cpp/atomic
61//! [cpp-intro.races]: https://timsong-cpp.github.io/cppwp/n4868/intro.multithread#intro.races
62//! [cpp_memory_order]: https://en.cppreference.com/w/cpp/atomic/memory_order
63//! [nomicon]: ../../../nomicon/atomics.html
64//!
65//! ```rust,no_run undefined_behavior
66//! use std::sync::atomic::{AtomicU16, AtomicU8, Ordering};
67//! use std::mem::transmute;
68//! use std::thread;
69//!
70//! let atomic = AtomicU16::new(0);
71//!
72//! thread::scope(|s| {
73//! // This is UB: conflicting non-synchronized accesses, at least one of which is non-atomic.
74//! s.spawn(|| atomic.store(1, Ordering::Relaxed)); // atomic store
75//! s.spawn(|| unsafe { atomic.as_ptr().write(2) }); // non-atomic write
76//! });
77//!
78//! thread::scope(|s| {
79//! // This is fine: the accesses do not conflict (as none of them performs any modification).
80//! // In C++ this would be disallowed since creating an `atomic_ref` precludes
81//! // further non-atomic accesses, but Rust does not have that limitation.
82//! s.spawn(|| atomic.load(Ordering::Relaxed)); // atomic load
83//! s.spawn(|| unsafe { atomic.as_ptr().read() }); // non-atomic read
84//! });
85//!
86//! thread::scope(|s| {
87//! // This is fine: `join` synchronizes the code in a way such that the atomic
88//! // store happens-before the non-atomic write.
89//! let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed)); // atomic store
90//! handle.join().expect("thread won't panic"); // synchronize
91//! s.spawn(|| unsafe { atomic.as_ptr().write(2) }); // non-atomic write
92//! });
93//!
94//! thread::scope(|s| {
95//! // This is UB: non-synchronized conflicting differently-sized atomic accesses.
96//! s.spawn(|| atomic.store(1, Ordering::Relaxed));
97//! s.spawn(|| unsafe {
98//! let differently_sized = transmute::<&AtomicU16, &AtomicU8>(&atomic);
99//! differently_sized.store(2, Ordering::Relaxed);
100//! });
101//! });
102//!
103//! thread::scope(|s| {
104//! // This is fine: `join` synchronizes the code in a way such that
105//! // the 1-byte store happens-before the 2-byte store.
106//! let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed));
107//! handle.join().expect("thread won't panic");
108//! s.spawn(|| unsafe {
109//! let differently_sized = transmute::<&AtomicU16, &AtomicU8>(&atomic);
110//! differently_sized.store(2, Ordering::Relaxed);
111//! });
112//! });
113//! ```
114//!
115//! # Portability
116//!
117//! All atomic types in this module are guaranteed to be [lock-free] if they're
118//! available. This means they don't internally acquire a global mutex. Atomic
119//! types and operations are not guaranteed to be wait-free. This means that
120//! operations like `fetch_or` may be implemented with a compare-and-swap loop.
121//!
122//! Atomic operations may be implemented at the instruction layer with
123//! larger-size atomics. For example some platforms use 4-byte atomic
124//! instructions to implement `AtomicI8`. Note that this emulation should not
125//! have an impact on correctness of code, it's just something to be aware of.
126//!
127//! The atomic types in this module might not be available on all platforms. The
128//! atomic types here are all widely available, however, and can generally be
129//! relied upon existing. Some notable exceptions are:
130//!
131//! * PowerPC and MIPS platforms with 32-bit pointers do not have `AtomicU64` or
132//! `AtomicI64` types.
133//! * Legacy ARM platforms like ARMv4T and ARMv5TE have very limited hardware
134//! support for atomics. The bare-metal targets disable this module
135//! entirely, but the Linux targets [use the kernel] to assist (which comes
136//! with a performance penalty). It's not until ARMv6K onwards that ARM CPUs
137//! have support for load/store and Compare and Swap (CAS) atomics in hardware.
138//! * ARMv6-M and ARMv8-M baseline targets (`thumbv6m-*` and
139//! `thumbv8m.base-*`) only provide `load` and `store` operations, and do
140//! not support Compare and Swap (CAS) operations, such as `swap`,
141//! `fetch_add`, etc. Full CAS support is available on ARMv7-M and ARMv8-M
142//! Mainline (`thumbv7m-*`, `thumbv7em*` and `thumbv8m.main-*`).
143//!
144//! [use the kernel]: https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt
145//!
146//! Note that future platforms may be added that also do not have support for
147//! some atomic operations. Maximally portable code will want to be careful
148//! about which atomic types are used. `AtomicUsize` and `AtomicIsize` are
149//! generally the most portable, but even then they're not available everywhere.
150//! For reference, the `std` library requires `AtomicBool`s and pointer-sized atomics, although
151//! `core` does not.
152//!
153//! The `#[cfg(target_has_atomic)]` attribute can be used to conditionally
154//! compile based on the target's supported bit widths. It is a key-value
155//! option set for each supported size, with values "8", "16", "32", "64",
156//! "128", and "ptr" for pointer-sized atomics.
157//!
158//! [lock-free]: https://en.wikipedia.org/wiki/Non-blocking_algorithm
159//!
160//! # Atomic accesses to read-only memory
161//!
162//! In general, *all* atomic accesses on read-only memory are undefined behavior. For instance, attempting
163//! to do a `compare_exchange` that will definitely fail (making it conceptually a read-only
164//! operation) can still cause a segmentation fault if the underlying memory page is mapped read-only. Since
165//! atomic `load`s might be implemented using compare-exchange operations, even a `load` can fault
166//! on read-only memory.
167//!
168//! For the purpose of this section, "read-only memory" is defined as memory that is read-only in
169//! the underlying target, i.e., the pages are mapped with a read-only flag and any attempt to write
170//! will cause a page fault. In particular, an `&u128` reference that points to memory that is
171//! read-write mapped is *not* considered to point to "read-only memory". In Rust, almost all memory
172//! is read-write; the only exceptions are memory created by `const` items or `static` items without
173//! interior mutability, and memory that was specifically marked as read-only by the operating
174//! system via platform-specific APIs.
175//!
176//! As an exception from the general rule stated above, "sufficiently small" atomic loads with
177//! `Ordering::Relaxed` are implemented in a way that works on read-only memory, and are hence not
178//! undefined behavior. The exact size limit for what makes a load "sufficiently small" varies
179//! depending on the target:
180//!
181//! | `target_arch` | Size limit |
182//! |---------------|---------|
183//! | `x86`, `arm`, `loongarch32`, `mips`, `mips32r6`, `powerpc`, `riscv32`, `sparc`, `hexagon` | 4 bytes |
184//! | `x86_64`, `aarch64`, `loongarch64`, `mips64`, `mips64r6`, `powerpc64`, `riscv64`, `sparc64`, `s390x` | 8 bytes |
185//!
186//! Atomics loads that are larger than this limit as well as atomic loads with ordering other
187//! than `Relaxed`, as well as *all* atomic loads on targets not listed in the table, might still be
188//! read-only under certain conditions, but that is not a stable guarantee and should not be relied
189//! upon.
190//!
191//! If you need to do an acquire load on read-only memory, you can do a relaxed load followed by an
192//! acquire fence instead.
193//!
194//! # Examples
195//!
196//! A simple spinlock:
197//!
198//! ```ignore-wasm
199//! use std::sync::Arc;
200//! use std::sync::atomic::{AtomicUsize, Ordering};
201//! use std::{hint, thread};
202//!
203//! fn main() {
204//! let spinlock = Arc::new(AtomicUsize::new(1));
205//!
206//! let spinlock_clone = Arc::clone(&spinlock);
207//!
208//! let thread = thread::spawn(move || {
209//! spinlock_clone.store(0, Ordering::Release);
210//! });
211//!
212//! // Wait for the other thread to release the lock
213//! while spinlock.load(Ordering::Acquire) != 0 {
214//! hint::spin_loop();
215//! }
216//!
217//! if let Err(panic) = thread.join() {
218//! println!("Thread had an error: {panic:?}");
219//! }
220//! }
221//! ```
222//!
223//! Keep a global count of live threads:
224//!
225//! ```
226//! use std::sync::atomic::{AtomicUsize, Ordering};
227//!
228//! static GLOBAL_THREAD_COUNT: AtomicUsize = AtomicUsize::new(0);
229//!
230//! // Note that Relaxed ordering doesn't synchronize anything
231//! // except the global thread counter itself.
232//! let old_thread_count = GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::Relaxed);
233//! // Note that this number may not be true at the moment of printing
234//! // because some other thread may have changed static value already.
235//! println!("live threads: {}", old_thread_count + 1);
236//! ```
237238#![stable(feature = "rust1", since = "1.0.0")]
239#![cfg_attr(not(target_has_atomic_load_store = "8"), allow(dead_code))]
240#![cfg_attr(not(target_has_atomic_load_store = "8"), allow(unused_imports))]
241// Clippy complains about the pattern of "safe function calling unsafe function taking pointers".
242// This happens with AtomicPtr intrinsics but is fine, as the pointers clippy is concerned about
243// are just normal values that get loaded/stored, but not dereferenced.
244#![allow(clippy::not_unsafe_ptr_arg_deref)]
245246use self::Ordering::*;
247use crate::cell::UnsafeCell;
248use crate::hint::spin_loop;
249use crate::intrinsics::AtomicOrderingas AO;
250use crate::mem::transmute;
251use crate::{fmt, intrinsics};
252253#[unstable(
254 feature = "atomic_internals",
255 reason = "implementation detail which may disappear or be replaced at any time",
256 issue = "none"
257)]
258#[expect(missing_debug_implementations)]
259mod private {
260#[cfg(target_has_atomic_load_store = "8")]
261 #[repr(C, align(1))]
262pub struct Align1<T>(T);
263#[cfg(target_has_atomic_load_store = "16")]
264 #[repr(C, align(2))]
265pub struct Align2<T>(T);
266#[cfg(target_has_atomic_load_store = "32")]
267 #[repr(C, align(4))]
268pub struct Align4<T>(T);
269#[cfg(target_has_atomic_load_store = "64")]
270 #[repr(C, align(8))]
271pub struct Align8<T>(T);
272#[cfg(any(target_has_atomic_load_store = "128", doc))]
273 #[repr(C, align(16))]
274pub struct Align16<T>(T);
275}
276277/// A marker trait for primitive types which can be modified atomically.
278///
279/// This is an implementation detail for <code>[Atomic]\<T></code> which may disappear or be replaced at any time.
280//
281// # Safety
282//
283// Types implementing this trait must be primitives that can be modified atomically.
284//
285// The associated `Self::Storage` type must have the same size, but may have fewer validity
286// invariants or a higher alignment requirement than `Self`.
287#[unstable(
288 feature = "atomic_internals",
289 reason = "implementation detail which may disappear or be replaced at any time",
290 issue = "none"
291)]
292pub impl(self) unsafe trait AtomicPrimitive: Sized + Copy {
293/// Temporary implementation detail.
294type Storage: Sized;
295}
296297macro impl_atomic_primitive {
298 (
299 @impl [$($T:ident)?] $Primitive:ty as $Storage:ident<$Operand:ty>,
300$cfg:meta
301 ) => {
302#[unstable(
303 feature = "atomic_internals",
304 reason = "implementation detail which may disappear or be replaced at any time",
305 issue = "none"
306)]
307 #[cfg($cfg)]
308unsafe impl $(<$T>)? AtomicPrimitive for $Primitive {
309type Storage = private::$Storage<$Operand>;
310 }
311 },
312313 (
314 [$($T:ident)?] $Primitive:ty as $Storage:ident<$Operand:ty>,
315 size($size:literal)
316 ) => {
317impl_atomic_primitive!(
318 @impl [$($T)?] $Primitive as $Storage<$Operand>,
319 target_has_atomic_load_store = $size
320);
321 },
322323 (
324 [$($T:ident)?] $Primitive:ty as $Storage:ident<$Operand:ty>,
325 size($size:literal),
326 doc
327 ) => {
328impl_atomic_primitive!(
329 @impl [$($T)?] $Primitive as $Storage<$Operand>,
330 any(target_has_atomic_load_store = $size, doc)
331 );
332 },
333}
334335#[unstable(feature = "atomic_internals", reason =
"implementation detail which may disappear or be replaced at any time", issue
= "none")]
unsafe impl AtomicPrimitive for bool {
type Storage = private::Align1<u8>;
}impl_atomic_primitive!([] boolas Align1<u8>, size("8"));
336#[unstable(feature = "atomic_internals", reason =
"implementation detail which may disappear or be replaced at any time", issue
= "none")]
unsafe impl AtomicPrimitive for i8 {
type Storage = private::Align1<i8>;
}impl_atomic_primitive!([] i8as Align1<i8>, size("8"));
337#[unstable(feature = "atomic_internals", reason =
"implementation detail which may disappear or be replaced at any time", issue
= "none")]
unsafe impl AtomicPrimitive for u8 {
type Storage = private::Align1<u8>;
}impl_atomic_primitive!([] u8as Align1<u8>, size("8"));
338#[unstable(feature = "atomic_internals", reason =
"implementation detail which may disappear or be replaced at any time", issue
= "none")]
unsafe impl AtomicPrimitive for i16 {
type Storage = private::Align2<i16>;
}impl_atomic_primitive!([] i16as Align2<i16>, size("16"));
339#[unstable(feature = "atomic_internals", reason =
"implementation detail which may disappear or be replaced at any time", issue
= "none")]
unsafe impl AtomicPrimitive for u16 {
type Storage = private::Align2<u16>;
}impl_atomic_primitive!([] u16as Align2<u16>, size("16"));
340#[unstable(feature = "atomic_internals", reason =
"implementation detail which may disappear or be replaced at any time", issue
= "none")]
unsafe impl AtomicPrimitive for i32 {
type Storage = private::Align4<i32>;
}impl_atomic_primitive!([] i32as Align4<i32>, size("32"));
341#[unstable(feature = "atomic_internals", reason =
"implementation detail which may disappear or be replaced at any time", issue
= "none")]
unsafe impl AtomicPrimitive for u32 {
type Storage = private::Align4<u32>;
}impl_atomic_primitive!([] u32as Align4<u32>, size("32"));
342#[unstable(feature = "atomic_internals", reason =
"implementation detail which may disappear or be replaced at any time", issue
= "none")]
unsafe impl AtomicPrimitive for i64 {
type Storage = private::Align8<i64>;
}impl_atomic_primitive!([] i64as Align8<i64>, size("64"));
343#[unstable(feature = "atomic_internals", reason =
"implementation detail which may disappear or be replaced at any time", issue
= "none")]
unsafe impl AtomicPrimitive for u64 {
type Storage = private::Align8<u64>;
}impl_atomic_primitive!([] u64as Align8<u64>, size("64"));
344impl_atomic_primitive!([] i128 as Align16<i128>, size("128"), doc);
345impl_atomic_primitive!([] u128 as Align16<u128>, size("128"), doc);
346347#[cfg(target_pointer_width = "16")]
348impl_atomic_primitive!([] isize as Align2<isize>, size("ptr"));
349#[cfg(target_pointer_width = "32")]
350impl_atomic_primitive!([] isize as Align4<isize>, size("ptr"));
351#[cfg(target_pointer_width = "64")]
352#[unstable(feature = "atomic_internals", reason =
"implementation detail which may disappear or be replaced at any time", issue
= "none")]
unsafe impl AtomicPrimitive for isize {
type Storage = private::Align8<isize>;
}impl_atomic_primitive!([] isizeas Align8<isize>, size("ptr"));
353354#[cfg(target_pointer_width = "16")]
355impl_atomic_primitive!([] usize as Align2<usize>, size("ptr"));
356#[cfg(target_pointer_width = "32")]
357impl_atomic_primitive!([] usize as Align4<usize>, size("ptr"));
358#[cfg(target_pointer_width = "64")]
359#[unstable(feature = "atomic_internals", reason =
"implementation detail which may disappear or be replaced at any time", issue
= "none")]
unsafe impl AtomicPrimitive for usize {
type Storage = private::Align8<usize>;
}impl_atomic_primitive!([] usizeas Align8<usize>, size("ptr"));
360361#[cfg(target_pointer_width = "16")]
362impl_atomic_primitive!([T] *mut T as Align2<*mut T>, size("ptr"));
363#[cfg(target_pointer_width = "32")]
364impl_atomic_primitive!([T] *mut T as Align4<*mut T>, size("ptr"));
365#[cfg(target_pointer_width = "64")]
366#[unstable(feature = "atomic_internals", reason =
"implementation detail which may disappear or be replaced at any time", issue
= "none")]
unsafe impl<T> AtomicPrimitive for *mut T {
type Storage = private::Align8<*mut T>;
}impl_atomic_primitive!([T] *mut T as Align8<*mut T>, size("ptr"));
367368/// A memory location which can be safely modified from multiple threads.
369///
370/// This has the same size and bit validity as the underlying type `T`. However,
371/// the alignment of this type is always equal to its size, even on targets where
372/// `T` has alignment less than its size.
373///
374/// For more about the differences between atomic types and non-atomic types as
375/// well as information about the portability of this type, please see the
376/// [module-level documentation].
377///
378/// **Note:** This type is only available on platforms that support atomic loads
379/// and stores of `T`.
380///
381/// [module-level documentation]: crate::sync::atomic
382#[unstable(feature = "generic_atomic", issue = "130539")]
383#[repr(C)]
384#[rustc_diagnostic_item = "Atomic"]
385pub struct Atomic<T: AtomicPrimitive> {
386 v: UnsafeCell<T::Storage>,
387}
388389#[stable(feature = "rust1", since = "1.0.0")]
390unsafe impl<T: AtomicPrimitive> Sendfor Atomic<T> {}
391#[stable(feature = "rust1", since = "1.0.0")]
392unsafe impl<T: AtomicPrimitive> Syncfor Atomic<T> {}
393394// Some architectures don't have byte-sized atomics, which results in LLVM
395// emulating them using a LL/SC loop. However for AtomicBool we can take
396// advantage of the fact that it only ever contains 0 or 1 and use atomic OR/AND
397// instead, which LLVM can emulate using a larger atomic OR/AND operation.
398//
399// This list should only contain architectures which have word-sized atomic-or/
400// atomic-and instructions but don't natively support byte-sized atomics.
401#[cfg(target_has_atomic = "8")]
402const EMULATE_ATOMIC_BOOL: bool = falsecfg!(any(
403 target_arch = "riscv32",
404 target_arch = "riscv64",
405 target_arch = "loongarch32",
406 target_arch = "loongarch64"
407));
408409/// A boolean type which can be safely shared between threads.
410///
411/// This type has the same size, alignment, and bit validity as a [`bool`].
412///
413/// **Note**: This type is only available on platforms that support atomic
414/// loads and stores of `u8`.
415#[cfg(target_has_atomic_load_store = "8")]
416#[stable(feature = "rust1", since = "1.0.0")]
417pub type AtomicBool = Atomic<bool>;
418419#[cfg(target_has_atomic_load_store = "8")]
420#[stable(feature = "rust1", since = "1.0.0")]
421impl Defaultfor AtomicBool {
422/// Creates an `AtomicBool` initialized to `false`.
423#[inline]
424fn default() -> Self {
425Self::new(false)
426 }
427}
428429/// A raw pointer type which can be safely shared between threads.
430///
431/// This type has the same size and bit validity as a `*mut T`.
432///
433/// **Note**: This type is only available on platforms that support atomic
434/// loads and stores of pointers. Its size depends on the target pointer's size.
435#[cfg(target_has_atomic_load_store = "ptr")]
436#[stable(feature = "rust1", since = "1.0.0")]
437pub type AtomicPtr<T> = Atomic<*mut T>;
438439#[cfg(target_has_atomic_load_store = "ptr")]
440#[stable(feature = "rust1", since = "1.0.0")]
441impl<T> Defaultfor AtomicPtr<T> {
442/// Creates a null `AtomicPtr<T>`.
443fn default() -> AtomicPtr<T> {
444AtomicPtr::new(crate::ptr::null_mut())
445 }
446}
447448/// Atomic memory orderings
449///
450/// Memory orderings specify the way atomic operations synchronize memory.
451/// In its weakest [`Ordering::Relaxed`], only the memory directly touched by the
452/// operation is synchronized. On the other hand, a store-load pair of [`Ordering::SeqCst`]
453/// operations synchronize other memory while additionally preserving a total order of such
454/// operations across all threads.
455///
456/// Rust's memory orderings are [the same as those of
457/// C++20](https://en.cppreference.com/w/cpp/atomic/memory_order).
458///
459/// For more information see the [nomicon].
460///
461/// [nomicon]: ../../../nomicon/atomics.html
462#[stable(feature = "rust1", since = "1.0.0")]
463#[derive(#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::marker::Copy for Ordering { }Copy, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::clone::Clone for Ordering {
#[inline]
fn clone(&self) -> Ordering { *self }
}Clone, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::fmt::Debug for Ordering {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::write_str(f,
match self {
Ordering::Relaxed => "Relaxed",
Ordering::Release => "Release",
Ordering::Acquire => "Acquire",
Ordering::AcqRel => "AcqRel",
Ordering::SeqCst => "SeqCst",
})
}
}Debug, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::cmp::Eq for Ordering {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::cmp::PartialEq for Ordering {
#[inline]
fn eq(&self, other: &Ordering) -> bool {
let __self_discr = crate::intrinsics::discriminant_value(self);
let __arg1_discr = crate::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::hash::Hash for Ordering {
#[inline]
fn hash<__H: crate::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = crate::intrinsics::discriminant_value(self);
crate::hash::Hash::hash(&__self_discr, state)
}
}Hash)]
464#[non_exhaustive]
465#[rustc_diagnostic_item = "Ordering"]
466pub enum Ordering {
467/// No ordering constraints, only atomic operations.
468 ///
469 /// Corresponds to [`memory_order_relaxed`] in C++20.
470 ///
471 /// [`memory_order_relaxed`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Relaxed_ordering
472#[stable(feature = "rust1", since = "1.0.0")]
473Relaxed,
474/// When coupled with a store, all previous operations become ordered
475 /// before any load of this value with [`Acquire`] (or stronger) ordering.
476 /// In particular, all previous writes become visible to all threads
477 /// that perform an [`Acquire`] (or stronger) load of this value.
478 ///
479 /// Notice that using this ordering for an operation that combines loads
480 /// and stores leads to a [`Relaxed`] load operation!
481 ///
482 /// This ordering is only applicable for operations that can perform a store.
483 ///
484 /// Corresponds to [`memory_order_release`] in C++20.
485 ///
486 /// [`memory_order_release`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
487#[stable(feature = "rust1", since = "1.0.0")]
488Release,
489/// When coupled with a load, if the loaded value was written by a store operation with
490 /// [`Release`] (or stronger) ordering, then all subsequent operations
491 /// become ordered after that store. In particular, all subsequent loads will see data
492 /// written before the store.
493 ///
494 /// Notice that using this ordering for an operation that combines loads
495 /// and stores leads to a [`Relaxed`] store operation!
496 ///
497 /// This ordering is only applicable for operations that can perform a load.
498 ///
499 /// Corresponds to [`memory_order_acquire`] in C++20.
500 ///
501 /// [`memory_order_acquire`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
502#[stable(feature = "rust1", since = "1.0.0")]
503Acquire,
504/// Has the effects of both [`Acquire`] and [`Release`] together:
505 /// For loads it uses [`Acquire`] ordering. For stores it uses the [`Release`] ordering.
506 ///
507 /// Notice that in the case of `compare_and_swap`, it is possible that the operation ends up
508 /// not performing any store and hence it has just [`Acquire`] ordering. However,
509 /// `AcqRel` will never perform [`Relaxed`] accesses.
510 ///
511 /// This ordering is only applicable for operations that combine both loads and stores.
512 ///
513 /// Corresponds to [`memory_order_acq_rel`] in C++20.
514 ///
515 /// [`memory_order_acq_rel`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
516#[stable(feature = "rust1", since = "1.0.0")]
517AcqRel,
518/// Like [`Acquire`]/[`Release`]/[`AcqRel`] (for load, store, and load-with-store
519 /// operations, respectively) with the additional guarantee that all threads see all
520 /// sequentially consistent operations in the same order.
521 ///
522 /// Corresponds to [`memory_order_seq_cst`] in C++20.
523 ///
524 /// [`memory_order_seq_cst`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Sequentially-consistent_ordering
525#[stable(feature = "rust1", since = "1.0.0")]
526SeqCst,
527}
528529/// An [`AtomicBool`] initialized to `false`.
530#[cfg(target_has_atomic_load_store = "8")]
531#[stable(feature = "rust1", since = "1.0.0")]
532#[deprecated(
533 since = "1.34.0",
534 note = "the `new` function is now preferred",
535 suggestion = "AtomicBool::new(false)"
536)]
537pub const ATOMIC_BOOL_INIT: AtomicBool = AtomicBool::new(false);
538539#[cfg(target_has_atomic_load_store = "8")]
540impl AtomicBool {
541/// Creates a new `AtomicBool`.
542 ///
543 /// # Examples
544 ///
545 /// ```
546 /// use std::sync::atomic::AtomicBool;
547 ///
548 /// let atomic_true = AtomicBool::new(true);
549 /// let atomic_false = AtomicBool::new(false);
550 /// ```
551#[inline]
552 #[stable(feature = "rust1", since = "1.0.0")]
553 #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")]
554 #[must_use]
555pub const fn new(v: bool) -> AtomicBool {
556// SAFETY:
557 // `Atomic<T>` is essentially a transparent wrapper around `T`.
558unsafe { transmute(v) }
559 }
560561/// Creates a new `AtomicBool` from a pointer.
562 ///
563 /// # Examples
564 ///
565 /// ```
566 /// use std::sync::atomic::{self, AtomicBool};
567 ///
568 /// // Get a pointer to an allocated value
569 /// let ptr: *mut bool = Box::into_raw(Box::new(false));
570 ///
571 /// assert!(ptr.cast::<AtomicBool>().is_aligned());
572 ///
573 /// {
574 /// // Create an atomic view of the allocated value
575 /// let atomic = unsafe { AtomicBool::from_ptr(ptr) };
576 ///
577 /// // Use `atomic` for atomic operations, possibly share it with other threads
578 /// atomic.store(true, atomic::Ordering::Relaxed);
579 /// }
580 ///
581 /// // It's ok to non-atomically access the value behind `ptr`,
582 /// // since the reference to the atomic ended its lifetime in the block above
583 /// assert_eq!(unsafe { *ptr }, true);
584 ///
585 /// // Deallocate the value
586 /// unsafe { drop(Box::from_raw(ptr)) }
587 /// ```
588 ///
589 /// # Safety
590 ///
591 /// * `ptr` must be aligned to `align_of::<AtomicBool>()` (note that this is always true, since
592 /// `align_of::<AtomicBool>() == 1`).
593 /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
594 /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
595 /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
596 /// sizes, without synchronization.
597 ///
598 /// [valid]: crate::ptr#safety
599 /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
600#[inline]
601 #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
602 #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
603pub const unsafe fn from_ptr<'a>(ptr: *mut bool) -> &'a AtomicBool {
604// SAFETY: guaranteed by the caller
605unsafe { &*ptr.cast() }
606 }
607608/// Returns a mutable reference to the underlying [`bool`].
609 ///
610 /// This is safe because the mutable reference guarantees that no other threads are
611 /// concurrently accessing the atomic data.
612 ///
613 /// # Examples
614 ///
615 /// ```
616 /// use std::sync::atomic::{AtomicBool, Ordering};
617 ///
618 /// let mut some_bool = AtomicBool::new(true);
619 /// assert_eq!(*some_bool.get_mut(), true);
620 /// *some_bool.get_mut() = false;
621 /// assert_eq!(some_bool.load(Ordering::SeqCst), false);
622 /// ```
623#[inline]
624 #[stable(feature = "atomic_access", since = "1.15.0")]
625pub fn get_mut(&mut self) -> &mut bool {
626// SAFETY: the mutable reference guarantees unique ownership.
627unsafe { &mut *self.as_ptr() }
628 }
629630/// Gets atomic access to a `&mut bool`.
631 ///
632 /// # Examples
633 ///
634 /// ```
635 /// use std::sync::atomic::{AtomicBool, Ordering};
636 ///
637 /// let mut some_bool = true;
638 /// let a = AtomicBool::from_mut(&mut some_bool);
639 /// a.store(false, Ordering::Relaxed);
640 /// assert_eq!(some_bool, false);
641 /// ```
642#[inline]
643 #[cfg(target_has_atomic_primitive_alignment = "8")]
644 #[stable(feature = "atomic_from_mut", since = "1.98.0")]
645pub fn from_mut(v: &mut bool) -> &mut Self {
646// SAFETY: the mutable reference guarantees unique ownership, and
647 // alignment of both `bool` and `Self` is 1.
648unsafe { &mut *(vas *mut boolas *mut Self) }
649 }
650651/// Gets non-atomic access to a `&mut [AtomicBool]` slice.
652 ///
653 /// This is safe because the mutable reference guarantees that no other threads are
654 /// concurrently accessing the atomic data.
655 ///
656 /// # Examples
657 ///
658 /// ```ignore-wasm
659 /// use std::sync::atomic::{AtomicBool, Ordering};
660 ///
661 /// let mut some_bools = [const { AtomicBool::new(false) }; 10];
662 ///
663 /// let view: &mut [bool] = AtomicBool::get_mut_slice(&mut some_bools);
664 /// assert_eq!(view, [false; 10]);
665 /// view[..5].copy_from_slice(&[true; 5]);
666 ///
667 /// std::thread::scope(|s| {
668 /// for t in &some_bools[..5] {
669 /// s.spawn(move || assert_eq!(t.load(Ordering::Relaxed), true));
670 /// }
671 ///
672 /// for f in &some_bools[5..] {
673 /// s.spawn(move || assert_eq!(f.load(Ordering::Relaxed), false));
674 /// }
675 /// });
676 /// ```
677#[inline]
678 #[stable(feature = "atomic_from_mut", since = "1.98.0")]
679pub fn get_mut_slice(this: &mut [Self]) -> &mut [bool] {
680// SAFETY: the mutable reference guarantees unique ownership.
681unsafe { &mut *(thisas *mut [Self] as *mut [bool]) }
682 }
683684/// Gets atomic access to a `&mut [bool]` slice.
685 ///
686 /// # Examples
687 ///
688 /// ```rust,ignore-wasm
689 /// use std::sync::atomic::{AtomicBool, Ordering};
690 ///
691 /// let mut some_bools = [false; 10];
692 /// let a = &*AtomicBool::from_mut_slice(&mut some_bools);
693 /// std::thread::scope(|s| {
694 /// for i in 0..a.len() {
695 /// s.spawn(move || a[i].store(true, Ordering::Relaxed));
696 /// }
697 /// });
698 /// assert_eq!(some_bools, [true; 10]);
699 /// ```
700#[inline]
701 #[cfg(target_has_atomic_primitive_alignment = "8")]
702 #[stable(feature = "atomic_from_mut", since = "1.98.0")]
703pub fn from_mut_slice(v: &mut [bool]) -> &mut [Self] {
704// SAFETY: the mutable reference guarantees unique ownership, and
705 // alignment of both `bool` and `Self` is 1.
706unsafe { &mut *(vas *mut [bool] as *mut [Self]) }
707 }
708709/// Consumes the atomic and returns the contained value.
710 ///
711 /// This is safe because passing `self` by value guarantees that no other threads are
712 /// concurrently accessing the atomic data.
713 ///
714 /// # Examples
715 ///
716 /// ```
717 /// use std::sync::atomic::AtomicBool;
718 ///
719 /// let some_bool = AtomicBool::new(true);
720 /// assert_eq!(some_bool.into_inner(), true);
721 /// ```
722#[inline]
723 #[stable(feature = "atomic_access", since = "1.15.0")]
724 #[rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0")]
725pub const fn into_inner(self) -> bool {
726// SAFETY:
727 // * `Atomic<T>` is essentially a transparent wrapper around `T`.
728 // * all operations on `Atomic<bool>` ensure that `T::Storage` remains
729 // a valid `bool`.
730unsafe { transmute(self) }
731 }
732733/// Loads a value from the bool.
734 ///
735 /// `load` takes an [`Ordering`] argument which describes the memory ordering
736 /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
737 ///
738 /// # Panics
739 ///
740 /// Panics if `order` is [`Release`] or [`AcqRel`].
741 ///
742 /// # Examples
743 ///
744 /// ```
745 /// use std::sync::atomic::{AtomicBool, Ordering};
746 ///
747 /// let some_bool = AtomicBool::new(true);
748 ///
749 /// assert_eq!(some_bool.load(Ordering::Relaxed), true);
750 /// ```
751#[inline]
752 #[stable(feature = "rust1", since = "1.0.0")]
753 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
754pub fn load(&self, order: Ordering) -> bool {
755// SAFETY: any data races are prevented by atomic intrinsics and the raw
756 // pointer passed in is valid because we got it from a reference.
757unsafe { atomic_load(self.v.get().cast::<u8>(), order) != 0 }
758 }
759760/// Stores a value into the bool.
761 ///
762 /// `store` takes an [`Ordering`] argument which describes the memory ordering
763 /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
764 ///
765 /// # Panics
766 ///
767 /// Panics if `order` is [`Acquire`] or [`AcqRel`].
768 ///
769 /// # Examples
770 ///
771 /// ```
772 /// use std::sync::atomic::{AtomicBool, Ordering};
773 ///
774 /// let some_bool = AtomicBool::new(true);
775 ///
776 /// some_bool.store(false, Ordering::Relaxed);
777 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
778 /// ```
779#[inline]
780 #[stable(feature = "rust1", since = "1.0.0")]
781 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
782#[rustc_should_not_be_called_on_const_items]
783pub fn store(&self, val: bool, order: Ordering) {
784// SAFETY: any data races are prevented by atomic intrinsics and the raw
785 // pointer passed in is valid because we got it from a reference.
786unsafe {
787atomic_store(self.v.get().cast::<u8>(), valas u8, order);
788 }
789 }
790791/// Stores a value into the bool, returning the previous value.
792 ///
793 /// `swap` takes an [`Ordering`] argument which describes the memory ordering
794 /// of this operation. All ordering modes are possible. Note that using
795 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
796 /// using [`Release`] makes the load part [`Relaxed`].
797 ///
798 /// **Note:** This method is only available on platforms that support atomic
799 /// operations on `u8`.
800 ///
801 /// # Examples
802 ///
803 /// ```
804 /// use std::sync::atomic::{AtomicBool, Ordering};
805 ///
806 /// let some_bool = AtomicBool::new(true);
807 ///
808 /// assert_eq!(some_bool.swap(false, Ordering::Relaxed), true);
809 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
810 /// ```
811#[inline]
812 #[stable(feature = "rust1", since = "1.0.0")]
813 #[cfg(target_has_atomic = "8")]
814 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
815#[rustc_should_not_be_called_on_const_items]
816pub fn swap(&self, val: bool, order: Ordering) -> bool {
817if EMULATE_ATOMIC_BOOL {
818if val { self.fetch_or(true, order) } else { self.fetch_and(false, order) }
819 } else {
820// SAFETY: data races are prevented by atomic intrinsics.
821unsafe { atomic_swap(self.v.get().cast::<u8>(), valas u8, order) != 0 }
822 }
823 }
824825/// Stores a value into the [`bool`] if the current value is the same as the `current` value.
826 ///
827 /// The return value is always the previous value. If it is equal to `current`, then the value
828 /// was updated.
829 ///
830 /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
831 /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
832 /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
833 /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
834 /// happens, and using [`Release`] makes the load part [`Relaxed`].
835 ///
836 /// **Note:** This method is only available on platforms that support atomic
837 /// operations on `u8`.
838 ///
839 /// # Migrating to `compare_exchange` and `compare_exchange_weak`
840 ///
841 /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
842 /// memory orderings:
843 ///
844 /// Original | Success | Failure
845 /// -------- | ------- | -------
846 /// Relaxed | Relaxed | Relaxed
847 /// Acquire | Acquire | Acquire
848 /// Release | Release | Relaxed
849 /// AcqRel | AcqRel | Acquire
850 /// SeqCst | SeqCst | SeqCst
851 ///
852 /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
853 /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
854 /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
855 /// rather than to infer success vs failure based on the value that was read.
856 ///
857 /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
858 /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
859 /// which allows the compiler to generate better assembly code when the compare and swap
860 /// is used in a loop.
861 ///
862 /// # Examples
863 ///
864 /// ```
865 /// use std::sync::atomic::{AtomicBool, Ordering};
866 ///
867 /// let some_bool = AtomicBool::new(true);
868 ///
869 /// assert_eq!(some_bool.compare_and_swap(true, false, Ordering::Relaxed), true);
870 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
871 ///
872 /// assert_eq!(some_bool.compare_and_swap(true, true, Ordering::Relaxed), false);
873 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
874 /// ```
875#[inline]
876 #[stable(feature = "rust1", since = "1.0.0")]
877 #[deprecated(
878 since = "1.50.0",
879 note = "Use `compare_exchange` or `compare_exchange_weak` instead"
880)]
881 #[cfg(target_has_atomic = "8")]
882 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
883#[rustc_should_not_be_called_on_const_items]
884pub fn compare_and_swap(&self, current: bool, new: bool, order: Ordering) -> bool {
885match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
886Ok(x) => x,
887Err(x) => x,
888 }
889 }
890891/// Stores a value into the [`bool`] if the current value is the same as the `current` value.
892 ///
893 /// The return value is a result indicating whether the new value was written and containing
894 /// the previous value. On success this value is guaranteed to be equal to `current`.
895 ///
896 /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
897 /// ordering of this operation. `success` describes the required ordering for the
898 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
899 /// `failure` describes the required ordering for the load operation that takes place when
900 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
901 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
902 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
903 ///
904 /// **Note:** This method is only available on platforms that support atomic
905 /// operations on `u8`.
906 ///
907 /// # Examples
908 ///
909 /// ```
910 /// use std::sync::atomic::{AtomicBool, Ordering};
911 ///
912 /// let some_bool = AtomicBool::new(true);
913 ///
914 /// assert_eq!(some_bool.compare_exchange(true,
915 /// false,
916 /// Ordering::Acquire,
917 /// Ordering::Relaxed),
918 /// Ok(true));
919 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
920 ///
921 /// assert_eq!(some_bool.compare_exchange(true, true,
922 /// Ordering::SeqCst,
923 /// Ordering::Acquire),
924 /// Err(false));
925 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
926 /// ```
927 ///
928 /// # Considerations
929 ///
930 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
931 /// of CAS operations. In particular, a load of the value followed by a successful
932 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
933 /// changed the value in the interim. This is usually important when the *equality* check in
934 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
935 /// does not necessarily imply identity. In this case, `compare_exchange` can lead to the
936 /// [ABA problem].
937 ///
938 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
939 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
940#[inline]
941 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
942 #[doc(alias = "compare_and_swap")]
943 #[cfg(target_has_atomic = "8")]
944 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
945#[rustc_should_not_be_called_on_const_items]
946pub fn compare_exchange(
947&self,
948 current: bool,
949 new: bool,
950 success: Ordering,
951 failure: Ordering,
952 ) -> Result<bool, bool> {
953if EMULATE_ATOMIC_BOOL {
954// Pick the strongest ordering from success and failure.
955let order = match (success, failure) {
956 (SeqCst, _) => SeqCst,
957 (_, SeqCst) => SeqCst,
958 (AcqRel, _) => AcqRel,
959 (_, AcqRel) => {
960{
crate::panicking::panic_fmt(format_args!("there is no such thing as an acquire-release failure ordering"));
}panic!("there is no such thing as an acquire-release failure ordering")961 }
962 (Release, Acquire) => AcqRel,
963 (Acquire, _) => Acquire,
964 (_, Acquire) => Acquire,
965 (Release, Relaxed) => Release,
966 (_, Release) => {
crate::panicking::panic_fmt(format_args!("there is no such thing as a release failure ordering"));
}panic!("there is no such thing as a release failure ordering"),
967 (Relaxed, Relaxed) => Relaxed,
968 };
969let old = if current == new {
970// This is a no-op, but we still need to perform the operation
971 // for memory ordering reasons.
972self.fetch_or(false, order)
973 } else {
974// This sets the value to the new one and returns the old one.
975self.swap(new, order)
976 };
977if old == current { Ok(old) } else { Err(old) }
978 } else {
979// SAFETY: data races are prevented by atomic intrinsics.
980match unsafe {
981atomic_compare_exchange(
982self.v.get().cast::<u8>(),
983currentas u8,
984newas u8,
985success,
986failure,
987 )
988 } {
989Ok(x) => Ok(x != 0),
990Err(x) => Err(x != 0),
991 }
992 }
993 }
994995/// Stores a value into the [`bool`] if the current value is the same as the `current` value.
996 ///
997 /// Unlike [`AtomicBool::compare_exchange`], this function is allowed to spuriously fail even when the
998 /// comparison succeeds, which can result in more efficient code on some platforms. The
999 /// return value is a result indicating whether the new value was written and containing the
1000 /// previous value.
1001 ///
1002 /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
1003 /// ordering of this operation. `success` describes the required ordering for the
1004 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1005 /// `failure` describes the required ordering for the load operation that takes place when
1006 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1007 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1008 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
1009 ///
1010 /// **Note:** This method is only available on platforms that support atomic
1011 /// operations on `u8`.
1012 ///
1013 /// # Examples
1014 ///
1015 /// ```
1016 /// use std::sync::atomic::{AtomicBool, Ordering};
1017 ///
1018 /// let val = AtomicBool::new(false);
1019 ///
1020 /// let new = true;
1021 /// let mut old = val.load(Ordering::Relaxed);
1022 /// loop {
1023 /// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
1024 /// Ok(_) => break,
1025 /// Err(x) => old = x,
1026 /// }
1027 /// }
1028 /// ```
1029 ///
1030 /// # Considerations
1031 ///
1032 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
1033 /// of CAS operations. In particular, a load of the value followed by a successful
1034 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
1035 /// changed the value in the interim. This is usually important when the *equality* check in
1036 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
1037 /// does not necessarily imply identity. In this case, `compare_exchange` can lead to the
1038 /// [ABA problem].
1039 ///
1040 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1041 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1042#[inline]
1043 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1044 #[doc(alias = "compare_and_swap")]
1045 #[cfg(target_has_atomic = "8")]
1046 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1047#[rustc_should_not_be_called_on_const_items]
1048pub fn compare_exchange_weak(
1049&self,
1050 current: bool,
1051 new: bool,
1052 success: Ordering,
1053 failure: Ordering,
1054 ) -> Result<bool, bool> {
1055if EMULATE_ATOMIC_BOOL {
1056return self.compare_exchange(current, new, success, failure);
1057 }
10581059// SAFETY: data races are prevented by atomic intrinsics.
1060match unsafe {
1061atomic_compare_exchange_weak(
1062self.v.get().cast::<u8>(),
1063currentas u8,
1064newas u8,
1065success,
1066failure,
1067 )
1068 } {
1069Ok(x) => Ok(x != 0),
1070Err(x) => Err(x != 0),
1071 }
1072 }
10731074/// Logical "and" with a boolean value.
1075 ///
1076 /// Performs a logical "and" operation on the current value and the argument `val`, and sets
1077 /// the new value to the result.
1078 ///
1079 /// Returns the previous value.
1080 ///
1081 /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
1082 /// of this operation. All ordering modes are possible. Note that using
1083 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1084 /// using [`Release`] makes the load part [`Relaxed`].
1085 ///
1086 /// **Note:** This method is only available on platforms that support atomic
1087 /// operations on `u8`.
1088 ///
1089 /// # Examples
1090 ///
1091 /// ```
1092 /// use std::sync::atomic::{AtomicBool, Ordering};
1093 ///
1094 /// let foo = AtomicBool::new(true);
1095 /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), true);
1096 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1097 ///
1098 /// let foo = AtomicBool::new(true);
1099 /// assert_eq!(foo.fetch_and(true, Ordering::SeqCst), true);
1100 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1101 ///
1102 /// let foo = AtomicBool::new(false);
1103 /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), false);
1104 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1105 /// ```
1106#[inline]
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 #[cfg(target_has_atomic = "8")]
1109 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1110#[rustc_should_not_be_called_on_const_items]
1111pub fn fetch_and(&self, val: bool, order: Ordering) -> bool {
1112// SAFETY: data races are prevented by atomic intrinsics.
1113unsafe { atomic_and(self.v.get().cast::<u8>(), valas u8, order) != 0 }
1114 }
11151116/// Logical "nand" with a boolean value.
1117 ///
1118 /// Performs a logical "nand" operation on the current value and the argument `val`, and sets
1119 /// the new value to the result.
1120 ///
1121 /// Returns the previous value.
1122 ///
1123 /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
1124 /// of this operation. All ordering modes are possible. Note that using
1125 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1126 /// using [`Release`] makes the load part [`Relaxed`].
1127 ///
1128 /// **Note:** This method is only available on platforms that support atomic
1129 /// operations on `u8`.
1130 ///
1131 /// # Examples
1132 ///
1133 /// ```
1134 /// use std::sync::atomic::{AtomicBool, Ordering};
1135 ///
1136 /// let foo = AtomicBool::new(true);
1137 /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), true);
1138 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1139 ///
1140 /// let foo = AtomicBool::new(true);
1141 /// assert_eq!(foo.fetch_nand(true, Ordering::SeqCst), true);
1142 /// assert_eq!(foo.load(Ordering::SeqCst) as usize, 0);
1143 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1144 ///
1145 /// let foo = AtomicBool::new(false);
1146 /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), false);
1147 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1148 /// ```
1149#[inline]
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 #[cfg(target_has_atomic = "8")]
1152 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1153#[rustc_should_not_be_called_on_const_items]
1154pub fn fetch_nand(&self, val: bool, order: Ordering) -> bool {
1155// We can't use atomic_nand here because it can result in a bool with
1156 // an invalid value. This happens because the atomic operation is done
1157 // with an 8-bit integer internally, which would set the upper 7 bits.
1158 // So we just use fetch_xor or swap instead.
1159if val {
1160// !(x & true) == !x
1161 // We must invert the bool.
1162self.fetch_xor(true, order)
1163 } else {
1164// !(x & false) == true
1165 // We must set the bool to true.
1166self.swap(true, order)
1167 }
1168 }
11691170/// Logical "or" with a boolean value.
1171 ///
1172 /// Performs a logical "or" operation on the current value and the argument `val`, and sets the
1173 /// new value to the result.
1174 ///
1175 /// Returns the previous value.
1176 ///
1177 /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
1178 /// of this operation. All ordering modes are possible. Note that using
1179 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1180 /// using [`Release`] makes the load part [`Relaxed`].
1181 ///
1182 /// **Note:** This method is only available on platforms that support atomic
1183 /// operations on `u8`.
1184 ///
1185 /// # Examples
1186 ///
1187 /// ```
1188 /// use std::sync::atomic::{AtomicBool, Ordering};
1189 ///
1190 /// let foo = AtomicBool::new(true);
1191 /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), true);
1192 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1193 ///
1194 /// let foo = AtomicBool::new(false);
1195 /// assert_eq!(foo.fetch_or(true, Ordering::SeqCst), false);
1196 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1197 ///
1198 /// let foo = AtomicBool::new(false);
1199 /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), false);
1200 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1201 /// ```
1202#[inline]
1203 #[stable(feature = "rust1", since = "1.0.0")]
1204 #[cfg(target_has_atomic = "8")]
1205 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1206#[rustc_should_not_be_called_on_const_items]
1207pub fn fetch_or(&self, val: bool, order: Ordering) -> bool {
1208// SAFETY: data races are prevented by atomic intrinsics.
1209unsafe { atomic_or(self.v.get().cast::<u8>(), valas u8, order) != 0 }
1210 }
12111212/// Logical "xor" with a boolean value.
1213 ///
1214 /// Performs a logical "xor" operation on the current value and the argument `val`, and sets
1215 /// the new value to the result.
1216 ///
1217 /// Returns the previous value.
1218 ///
1219 /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
1220 /// of this operation. All ordering modes are possible. Note that using
1221 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1222 /// using [`Release`] makes the load part [`Relaxed`].
1223 ///
1224 /// **Note:** This method is only available on platforms that support atomic
1225 /// operations on `u8`.
1226 ///
1227 /// # Examples
1228 ///
1229 /// ```
1230 /// use std::sync::atomic::{AtomicBool, Ordering};
1231 ///
1232 /// let foo = AtomicBool::new(true);
1233 /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), true);
1234 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1235 ///
1236 /// let foo = AtomicBool::new(true);
1237 /// assert_eq!(foo.fetch_xor(true, Ordering::SeqCst), true);
1238 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1239 ///
1240 /// let foo = AtomicBool::new(false);
1241 /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), false);
1242 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1243 /// ```
1244#[inline]
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 #[cfg(target_has_atomic = "8")]
1247 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1248#[rustc_should_not_be_called_on_const_items]
1249pub fn fetch_xor(&self, val: bool, order: Ordering) -> bool {
1250// SAFETY: data races are prevented by atomic intrinsics.
1251unsafe { atomic_xor(self.v.get().cast::<u8>(), valas u8, order) != 0 }
1252 }
12531254/// Logical "not" with a boolean value.
1255 ///
1256 /// Performs a logical "not" operation on the current value, and sets
1257 /// the new value to the result.
1258 ///
1259 /// Returns the previous value.
1260 ///
1261 /// `fetch_not` takes an [`Ordering`] argument which describes the memory ordering
1262 /// of this operation. All ordering modes are possible. Note that using
1263 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1264 /// using [`Release`] makes the load part [`Relaxed`].
1265 ///
1266 /// **Note:** This method is only available on platforms that support atomic
1267 /// operations on `u8`.
1268 ///
1269 /// # Examples
1270 ///
1271 /// ```
1272 /// use std::sync::atomic::{AtomicBool, Ordering};
1273 ///
1274 /// let foo = AtomicBool::new(true);
1275 /// assert_eq!(foo.fetch_not(Ordering::SeqCst), true);
1276 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1277 ///
1278 /// let foo = AtomicBool::new(false);
1279 /// assert_eq!(foo.fetch_not(Ordering::SeqCst), false);
1280 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1281 /// ```
1282#[inline]
1283 #[stable(feature = "atomic_bool_fetch_not", since = "1.81.0")]
1284 #[cfg(target_has_atomic = "8")]
1285 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1286#[rustc_should_not_be_called_on_const_items]
1287pub fn fetch_not(&self, order: Ordering) -> bool {
1288self.fetch_xor(true, order)
1289 }
12901291/// Returns a mutable pointer to the underlying [`bool`].
1292 ///
1293 /// Doing non-atomic reads and writes on the resulting boolean can be a data race.
1294 /// This method is mostly useful for FFI, where the function signature may use
1295 /// `*mut bool` instead of `&AtomicBool`.
1296 ///
1297 /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
1298 /// atomic types work with interior mutability. All modifications of an atomic change the value
1299 /// through a shared reference, and can do so safely as long as they use atomic operations. Any
1300 /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
1301 /// requirements of the [memory model].
1302 ///
1303 /// # Examples
1304 ///
1305 /// ```ignore (extern-declaration)
1306 /// # fn main() {
1307 /// use std::sync::atomic::AtomicBool;
1308 ///
1309 /// extern "C" {
1310 /// fn my_atomic_op(arg: *mut bool);
1311 /// }
1312 ///
1313 /// let mut atomic = AtomicBool::new(true);
1314 /// unsafe {
1315 /// my_atomic_op(atomic.as_ptr());
1316 /// }
1317 /// # }
1318 /// ```
1319 ///
1320 /// [memory model]: self#memory-model-for-atomic-accesses
1321#[inline]
1322 #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
1323 #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
1324 #[rustc_never_returns_null_ptr]
1325 #[rustc_should_not_be_called_on_const_items]
1326pub const fn as_ptr(&self) -> *mut bool {
1327self.v.get().cast()
1328 }
13291330/// An alias for [`AtomicBool::try_update`].
1331#[inline]
1332 #[stable(feature = "atomic_fetch_update", since = "1.53.0")]
1333 #[cfg(target_has_atomic = "8")]
1334 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1335#[rustc_should_not_be_called_on_const_items]
1336 #[deprecated(
1337 since = "1.99.0",
1338 note = "renamed to `try_update` for consistency",
1339 suggestion = "try_update"
1340)]
1341pub fn fetch_update<F>(
1342&self,
1343 set_order: Ordering,
1344 fetch_order: Ordering,
1345 f: F,
1346 ) -> Result<bool, bool>
1347where
1348F: FnMut(bool) -> Option<bool>,
1349 {
1350self.try_update(set_order, fetch_order, f)
1351 }
13521353/// Fetches the value, and applies a function to it that returns an optional
1354 /// new value. Returns a `Result` of `Ok(previous_value)` if the function
1355 /// returned `Some(_)`, else `Err(previous_value)`.
1356 ///
1357 /// See also: [`update`](`AtomicBool::update`).
1358 ///
1359 /// Note: This may call the function multiple times if the value has been
1360 /// changed from other threads in the meantime, as long as the function
1361 /// returns `Some(_)`, but the function will have been applied only once to
1362 /// the stored value.
1363 ///
1364 /// `try_update` takes two [`Ordering`] arguments to describe the memory
1365 /// ordering of this operation. The first describes the required ordering for
1366 /// when the operation finally succeeds while the second describes the
1367 /// required ordering for loads. These correspond to the success and failure
1368 /// orderings of [`AtomicBool::compare_exchange`] respectively.
1369 ///
1370 /// Using [`Acquire`] as success ordering makes the store part of this
1371 /// operation [`Relaxed`], and using [`Release`] makes the final successful
1372 /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
1373 /// [`Acquire`] or [`Relaxed`].
1374 ///
1375 /// **Note:** This method is only available on platforms that support atomic
1376 /// operations on `u8`.
1377 ///
1378 /// # Considerations
1379 ///
1380 /// This method is not magic; it is not provided by the hardware, and does not act like a
1381 /// critical section or mutex.
1382 ///
1383 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
1384 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem].
1385 ///
1386 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1387 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1388 ///
1389 /// # Examples
1390 ///
1391 /// ```rust
1392 /// use std::sync::atomic::{AtomicBool, Ordering};
1393 ///
1394 /// let x = AtomicBool::new(false);
1395 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(false));
1396 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(false));
1397 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(true));
1398 /// assert_eq!(x.load(Ordering::SeqCst), false);
1399 /// ```
1400#[inline]
1401 #[stable(feature = "atomic_try_update", since = "1.95.0")]
1402 #[cfg(target_has_atomic = "8")]
1403 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1404#[rustc_should_not_be_called_on_const_items]
1405pub fn try_update(
1406&self,
1407 set_order: Ordering,
1408 fetch_order: Ordering,
1409mut f: impl FnMut(bool) -> Option<bool>,
1410 ) -> Result<bool, bool> {
1411let mut prev = self.load(fetch_order);
1412while let Some(next) = f(prev) {
1413match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
1414 x @ Ok(_) => return x,
1415Err(next_prev) => prev = next_prev,
1416 }
1417 }
1418Err(prev)
1419 }
14201421/// Fetches the value, applies a function to it that it return a new value.
1422 /// The new value is stored and the old value is returned.
1423 ///
1424 /// See also: [`try_update`](`AtomicBool::try_update`).
1425 ///
1426 /// Note: This may call the function multiple times if the value has been changed from other threads in
1427 /// the meantime, but the function will have been applied only once to the stored value.
1428 ///
1429 /// `update` takes two [`Ordering`] arguments to describe the memory
1430 /// ordering of this operation. The first describes the required ordering for
1431 /// when the operation finally succeeds while the second describes the
1432 /// required ordering for loads. These correspond to the success and failure
1433 /// orderings of [`AtomicBool::compare_exchange`] respectively.
1434 ///
1435 /// Using [`Acquire`] as success ordering makes the store part
1436 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
1437 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
1438 ///
1439 /// **Note:** This method is only available on platforms that support atomic operations on `u8`.
1440 ///
1441 /// # Considerations
1442 ///
1443 /// This method is not magic; it is not provided by the hardware, and does not act like a
1444 /// critical section or mutex.
1445 ///
1446 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
1447 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem].
1448 ///
1449 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1450 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1451 ///
1452 /// # Examples
1453 ///
1454 /// ```rust
1455 ///
1456 /// use std::sync::atomic::{AtomicBool, Ordering};
1457 ///
1458 /// let x = AtomicBool::new(false);
1459 /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| !x), false);
1460 /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| !x), true);
1461 /// assert_eq!(x.load(Ordering::SeqCst), false);
1462 /// ```
1463#[inline]
1464 #[stable(feature = "atomic_try_update", since = "1.95.0")]
1465 #[cfg(target_has_atomic = "8")]
1466 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1467#[rustc_should_not_be_called_on_const_items]
1468pub fn update(
1469&self,
1470 set_order: Ordering,
1471 fetch_order: Ordering,
1472mut f: impl FnMut(bool) -> bool,
1473 ) -> bool {
1474let mut prev = self.load(fetch_order);
1475loop {
1476match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
1477Ok(x) => break x,
1478Err(next_prev) => prev = next_prev,
1479 }
1480 }
1481 }
1482}
14831484#[cfg(target_has_atomic_load_store = "ptr")]
1485impl<T> AtomicPtr<T> {
1486/// Creates a new `AtomicPtr`.
1487 ///
1488 /// # Examples
1489 ///
1490 /// ```
1491 /// use std::sync::atomic::AtomicPtr;
1492 ///
1493 /// let ptr = &mut 5;
1494 /// let atomic_ptr = AtomicPtr::new(ptr);
1495 /// ```
1496#[inline]
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")]
1499pub const fn new(p: *mut T) -> AtomicPtr<T> {
1500// SAFETY:
1501 // `Atomic<T>` is essentially a transparent wrapper around `T`.
1502unsafe { transmute(p) }
1503 }
15041505/// Creates a new `AtomicPtr` from a pointer.
1506 ///
1507 /// # Examples
1508 ///
1509 /// ```
1510 /// use std::sync::atomic::{self, AtomicPtr};
1511 ///
1512 /// // Get a pointer to an allocated value
1513 /// let ptr: *mut *mut u8 = Box::into_raw(Box::new(std::ptr::null_mut()));
1514 ///
1515 /// assert!(ptr.cast::<AtomicPtr<u8>>().is_aligned());
1516 ///
1517 /// {
1518 /// // Create an atomic view of the allocated value
1519 /// let atomic = unsafe { AtomicPtr::from_ptr(ptr) };
1520 ///
1521 /// // Use `atomic` for atomic operations, possibly share it with other threads
1522 /// atomic.store(std::ptr::NonNull::dangling().as_ptr(), atomic::Ordering::Relaxed);
1523 /// }
1524 ///
1525 /// // It's ok to non-atomically access the value behind `ptr`,
1526 /// // since the reference to the atomic ended its lifetime in the block above
1527 /// assert!(!unsafe { *ptr }.is_null());
1528 ///
1529 /// // Deallocate the value
1530 /// unsafe { drop(Box::from_raw(ptr)) }
1531 /// ```
1532 ///
1533 /// # Safety
1534 ///
1535 /// * `ptr` must be aligned to `align_of::<AtomicPtr<T>>()` (note that on some platforms this
1536 /// can be bigger than `align_of::<*mut T>()`).
1537 /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
1538 /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
1539 /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
1540 /// sizes, without synchronization.
1541 ///
1542 /// [valid]: crate::ptr#safety
1543 /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
1544#[inline]
1545 #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
1546 #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
1547pub const unsafe fn from_ptr<'a>(ptr: *mut *mut T) -> &'a AtomicPtr<T> {
1548// SAFETY: guaranteed by the caller
1549unsafe { &*ptr.cast() }
1550 }
15511552/// Creates a new `AtomicPtr` initialized with a null pointer.
1553 ///
1554 /// # Examples
1555 ///
1556 /// ```
1557 /// #![feature(atomic_ptr_null)]
1558 /// use std::sync::atomic::{AtomicPtr, Ordering};
1559 ///
1560 /// let atomic_ptr = AtomicPtr::<()>::null();
1561 /// assert!(atomic_ptr.load(Ordering::Relaxed).is_null());
1562 /// ```
1563#[inline]
1564 #[must_use]
1565 #[unstable(feature = "atomic_ptr_null", issue = "150733")]
1566pub const fn null() -> AtomicPtr<T> {
1567AtomicPtr::new(crate::ptr::null_mut())
1568 }
15691570/// Returns a mutable reference to the underlying pointer.
1571 ///
1572 /// This is safe because the mutable reference guarantees that no other threads are
1573 /// concurrently accessing the atomic data.
1574 ///
1575 /// # Examples
1576 ///
1577 /// ```
1578 /// use std::sync::atomic::{AtomicPtr, Ordering};
1579 ///
1580 /// let mut data = 10;
1581 /// let mut atomic_ptr = AtomicPtr::new(&mut data);
1582 /// let mut other_data = 5;
1583 /// *atomic_ptr.get_mut() = &mut other_data;
1584 /// assert_eq!(unsafe { *atomic_ptr.load(Ordering::SeqCst) }, 5);
1585 /// ```
1586#[inline]
1587 #[stable(feature = "atomic_access", since = "1.15.0")]
1588pub fn get_mut(&mut self) -> &mut *mut T {
1589// SAFETY:
1590 // `Atomic<T>` is essentially a transparent wrapper around `T`.
1591unsafe { &mut *self.as_ptr() }
1592 }
15931594/// Gets atomic access to a pointer.
1595 ///
1596 /// **Note:** This function is only available on targets where `AtomicPtr<T>` has the same alignment as `*const T`
1597 ///
1598 /// # Examples
1599 ///
1600 /// ```
1601 /// use std::sync::atomic::{AtomicPtr, Ordering};
1602 ///
1603 /// let mut data = 123;
1604 /// let mut some_ptr = &mut data as *mut i32;
1605 /// let a = AtomicPtr::from_mut(&mut some_ptr);
1606 /// let mut other_data = 456;
1607 /// a.store(&mut other_data, Ordering::Relaxed);
1608 /// assert_eq!(unsafe { *some_ptr }, 456);
1609 /// ```
1610#[inline]
1611 #[cfg(target_has_atomic_primitive_alignment = "ptr")]
1612 #[stable(feature = "atomic_from_mut", since = "1.98.0")]
1613pub fn from_mut(v: &mut *mut T) -> &mut Self {
1614let [] = [(); align_of::<AtomicPtr<()>>() - align_of::<*mut ()>()];
1615// SAFETY:
1616 // - the mutable reference guarantees unique ownership.
1617 // - the alignment of `*mut T` and `Self` is the same on all platforms
1618 // supported by rust, as verified above.
1619unsafe { &mut *(vas *mut *mut T as *mut Self) }
1620 }
16211622/// Gets non-atomic access to a `&mut [AtomicPtr]` slice.
1623 ///
1624 /// This is safe because the mutable reference guarantees that no other threads are
1625 /// concurrently accessing the atomic data.
1626 ///
1627 /// # Examples
1628 ///
1629 /// ```ignore-wasm
1630 /// use std::ptr::null_mut;
1631 /// use std::sync::atomic::{AtomicPtr, Ordering};
1632 ///
1633 /// let mut some_ptrs = [const { AtomicPtr::new(null_mut::<String>()) }; 10];
1634 ///
1635 /// let view: &mut [*mut String] = AtomicPtr::get_mut_slice(&mut some_ptrs);
1636 /// assert_eq!(view, [null_mut::<String>(); 10]);
1637 /// view
1638 /// .iter_mut()
1639 /// .enumerate()
1640 /// .for_each(|(i, ptr)| *ptr = Box::into_raw(Box::new(format!("iteration#{i}"))));
1641 ///
1642 /// std::thread::scope(|s| {
1643 /// for ptr in &some_ptrs {
1644 /// s.spawn(move || {
1645 /// let ptr = ptr.load(Ordering::Relaxed);
1646 /// assert!(!ptr.is_null());
1647 ///
1648 /// let name = unsafe { Box::from_raw(ptr) };
1649 /// println!("Hello, {name}!");
1650 /// });
1651 /// }
1652 /// });
1653 /// ```
1654#[inline]
1655 #[stable(feature = "atomic_from_mut", since = "1.98.0")]
1656pub fn get_mut_slice(this: &mut [Self]) -> &mut [*mut T] {
1657// SAFETY: the mutable reference guarantees unique ownership.
1658unsafe { &mut *(thisas *mut [Self] as *mut [*mut T]) }
1659 }
16601661/// Gets atomic access to a slice of pointers.
1662 ///
1663 /// **Note:** This function is only available on targets where `AtomicPtr<T>` has the same alignment as `*const T`
1664 ///
1665 /// # Examples
1666 ///
1667 /// ```ignore-wasm
1668 /// use std::ptr::null_mut;
1669 /// use std::sync::atomic::{AtomicPtr, Ordering};
1670 ///
1671 /// let mut some_ptrs = [null_mut::<String>(); 10];
1672 /// let a = &*AtomicPtr::from_mut_slice(&mut some_ptrs);
1673 /// std::thread::scope(|s| {
1674 /// for i in 0..a.len() {
1675 /// s.spawn(move || {
1676 /// let name = Box::new(format!("thread{i}"));
1677 /// a[i].store(Box::into_raw(name), Ordering::Relaxed);
1678 /// });
1679 /// }
1680 /// });
1681 /// for p in some_ptrs {
1682 /// assert!(!p.is_null());
1683 /// let name = unsafe { Box::from_raw(p) };
1684 /// println!("Hello, {name}!");
1685 /// }
1686 /// ```
1687#[inline]
1688 #[cfg(target_has_atomic_primitive_alignment = "ptr")]
1689 #[stable(feature = "atomic_from_mut", since = "1.98.0")]
1690pub fn from_mut_slice(v: &mut [*mut T]) -> &mut [Self] {
1691// SAFETY:
1692 // - the mutable reference guarantees unique ownership.
1693 // - the alignment of `*mut T` and `Self` is the same on all platforms
1694 // supported by rust, as verified above.
1695unsafe { &mut *(vas *mut [*mut T] as *mut [Self]) }
1696 }
16971698/// Consumes the atomic and returns the contained value.
1699 ///
1700 /// This is safe because passing `self` by value guarantees that no other threads are
1701 /// concurrently accessing the atomic data.
1702 ///
1703 /// # Examples
1704 ///
1705 /// ```
1706 /// use std::sync::atomic::AtomicPtr;
1707 ///
1708 /// let mut data = 5;
1709 /// let atomic_ptr = AtomicPtr::new(&mut data);
1710 /// assert_eq!(unsafe { *atomic_ptr.into_inner() }, 5);
1711 /// ```
1712#[inline]
1713 #[stable(feature = "atomic_access", since = "1.15.0")]
1714 #[rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0")]
1715pub const fn into_inner(self) -> *mut T {
1716// SAFETY:
1717 // `Atomic<T>` is essentially a transparent wrapper around `T`.
1718unsafe { transmute(self) }
1719 }
17201721/// Loads a value from the pointer.
1722 ///
1723 /// `load` takes an [`Ordering`] argument which describes the memory ordering
1724 /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
1725 ///
1726 /// # Panics
1727 ///
1728 /// Panics if `order` is [`Release`] or [`AcqRel`].
1729 ///
1730 /// # Examples
1731 ///
1732 /// ```
1733 /// use std::sync::atomic::{AtomicPtr, Ordering};
1734 ///
1735 /// let ptr = &mut 5;
1736 /// let some_ptr = AtomicPtr::new(ptr);
1737 ///
1738 /// let value = some_ptr.load(Ordering::Relaxed);
1739 /// ```
1740#[inline]
1741 #[stable(feature = "rust1", since = "1.0.0")]
1742 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1743pub fn load(&self, order: Ordering) -> *mut T {
1744// SAFETY: data races are prevented by atomic intrinsics.
1745unsafe { atomic_load(self.as_ptr(), order) }
1746 }
17471748/// Stores a value into the pointer.
1749 ///
1750 /// `store` takes an [`Ordering`] argument which describes the memory ordering
1751 /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
1752 ///
1753 /// # Panics
1754 ///
1755 /// Panics if `order` is [`Acquire`] or [`AcqRel`].
1756 ///
1757 /// # Examples
1758 ///
1759 /// ```
1760 /// use std::sync::atomic::{AtomicPtr, Ordering};
1761 ///
1762 /// let ptr = &mut 5;
1763 /// let some_ptr = AtomicPtr::new(ptr);
1764 ///
1765 /// let other_ptr = &mut 10;
1766 ///
1767 /// some_ptr.store(other_ptr, Ordering::Relaxed);
1768 /// ```
1769#[inline]
1770 #[stable(feature = "rust1", since = "1.0.0")]
1771 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1772#[rustc_should_not_be_called_on_const_items]
1773pub fn store(&self, ptr: *mut T, order: Ordering) {
1774// SAFETY: data races are prevented by atomic intrinsics.
1775unsafe {
1776atomic_store(self.as_ptr(), ptr, order);
1777 }
1778 }
17791780/// Stores a value into the pointer, returning the previous value.
1781 ///
1782 /// `swap` takes an [`Ordering`] argument which describes the memory ordering
1783 /// of this operation. All ordering modes are possible. Note that using
1784 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1785 /// using [`Release`] makes the load part [`Relaxed`].
1786 ///
1787 /// **Note:** This method is only available on platforms that support atomic
1788 /// operations on pointers.
1789 ///
1790 /// # Examples
1791 ///
1792 /// ```
1793 /// use std::sync::atomic::{AtomicPtr, Ordering};
1794 ///
1795 /// let ptr = &mut 5;
1796 /// let some_ptr = AtomicPtr::new(ptr);
1797 ///
1798 /// let other_ptr = &mut 10;
1799 ///
1800 /// let value = some_ptr.swap(other_ptr, Ordering::Relaxed);
1801 /// ```
1802#[inline]
1803 #[stable(feature = "rust1", since = "1.0.0")]
1804 #[cfg(target_has_atomic = "ptr")]
1805 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1806#[rustc_should_not_be_called_on_const_items]
1807pub fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T {
1808// SAFETY: data races are prevented by atomic intrinsics.
1809unsafe { atomic_swap(self.as_ptr(), ptr, order) }
1810 }
18111812/// Stores a value into the pointer if the current value is the same as the `current` value.
1813 ///
1814 /// The return value is always the previous value. If it is equal to `current`, then the value
1815 /// was updated.
1816 ///
1817 /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
1818 /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
1819 /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
1820 /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
1821 /// happens, and using [`Release`] makes the load part [`Relaxed`].
1822 ///
1823 /// **Note:** This method is only available on platforms that support atomic
1824 /// operations on pointers.
1825 ///
1826 /// # Migrating to `compare_exchange` and `compare_exchange_weak`
1827 ///
1828 /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
1829 /// memory orderings:
1830 ///
1831 /// Original | Success | Failure
1832 /// -------- | ------- | -------
1833 /// Relaxed | Relaxed | Relaxed
1834 /// Acquire | Acquire | Acquire
1835 /// Release | Release | Relaxed
1836 /// AcqRel | AcqRel | Acquire
1837 /// SeqCst | SeqCst | SeqCst
1838 ///
1839 /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
1840 /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
1841 /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
1842 /// rather than to infer success vs failure based on the value that was read.
1843 ///
1844 /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
1845 /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
1846 /// which allows the compiler to generate better assembly code when the compare and swap
1847 /// is used in a loop.
1848 ///
1849 /// # Examples
1850 ///
1851 /// ```
1852 /// use std::sync::atomic::{AtomicPtr, Ordering};
1853 ///
1854 /// let ptr = &mut 5;
1855 /// let some_ptr = AtomicPtr::new(ptr);
1856 ///
1857 /// let other_ptr = &mut 10;
1858 ///
1859 /// let value = some_ptr.compare_and_swap(ptr, other_ptr, Ordering::Relaxed);
1860 /// ```
1861#[inline]
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 #[deprecated(
1864 since = "1.50.0",
1865 note = "Use `compare_exchange` or `compare_exchange_weak` instead"
1866)]
1867 #[cfg(target_has_atomic = "ptr")]
1868 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1869#[rustc_should_not_be_called_on_const_items]
1870pub fn compare_and_swap(&self, current: *mut T, new: *mut T, order: Ordering) -> *mut T {
1871match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
1872Ok(x) => x,
1873Err(x) => x,
1874 }
1875 }
18761877/// Stores a value into the pointer if the current value is the same as the `current` value.
1878 ///
1879 /// The return value is a result indicating whether the new value was written and containing
1880 /// the previous value. On success this value is guaranteed to be equal to `current`.
1881 ///
1882 /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
1883 /// ordering of this operation. `success` describes the required ordering for the
1884 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1885 /// `failure` describes the required ordering for the load operation that takes place when
1886 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1887 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1888 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
1889 ///
1890 /// **Note:** This method is only available on platforms that support atomic
1891 /// operations on pointers.
1892 ///
1893 /// # Examples
1894 ///
1895 /// ```
1896 /// use std::sync::atomic::{AtomicPtr, Ordering};
1897 ///
1898 /// let ptr = &mut 5;
1899 /// let some_ptr = AtomicPtr::new(ptr);
1900 ///
1901 /// let other_ptr = &mut 10;
1902 ///
1903 /// let value = some_ptr.compare_exchange(ptr, other_ptr,
1904 /// Ordering::SeqCst, Ordering::Relaxed);
1905 /// ```
1906 ///
1907 /// # Considerations
1908 ///
1909 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
1910 /// of CAS operations. In particular, a load of the value followed by a successful
1911 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
1912 /// changed the value in the interim. This is usually important when the *equality* check in
1913 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
1914 /// does not necessarily imply identity. This is a particularly common case for pointers, as
1915 /// a pointer holding the same address does not imply that the same object exists at that
1916 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
1917 ///
1918 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1919 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1920#[inline]
1921 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1922 #[cfg(target_has_atomic = "ptr")]
1923 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1924#[rustc_should_not_be_called_on_const_items]
1925pub fn compare_exchange(
1926&self,
1927 current: *mut T,
1928 new: *mut T,
1929 success: Ordering,
1930 failure: Ordering,
1931 ) -> Result<*mut T, *mut T> {
1932// SAFETY: data races are prevented by atomic intrinsics.
1933unsafe { atomic_compare_exchange(self.as_ptr(), current, new, success, failure) }
1934 }
19351936/// Stores a value into the pointer if the current value is the same as the `current` value.
1937 ///
1938 /// Unlike [`AtomicPtr::compare_exchange`], this function is allowed to spuriously fail even when the
1939 /// comparison succeeds, which can result in more efficient code on some platforms. The
1940 /// return value is a result indicating whether the new value was written and containing the
1941 /// previous value.
1942 ///
1943 /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
1944 /// ordering of this operation. `success` describes the required ordering for the
1945 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1946 /// `failure` describes the required ordering for the load operation that takes place when
1947 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1948 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1949 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
1950 ///
1951 /// **Note:** This method is only available on platforms that support atomic
1952 /// operations on pointers.
1953 ///
1954 /// # Examples
1955 ///
1956 /// ```
1957 /// use std::sync::atomic::{AtomicPtr, Ordering};
1958 ///
1959 /// let some_ptr = AtomicPtr::new(&mut 5);
1960 ///
1961 /// let new = &mut 10;
1962 /// let mut old = some_ptr.load(Ordering::Relaxed);
1963 /// loop {
1964 /// match some_ptr.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
1965 /// Ok(_) => break,
1966 /// Err(x) => old = x,
1967 /// }
1968 /// }
1969 /// ```
1970 ///
1971 /// # Considerations
1972 ///
1973 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
1974 /// of CAS operations. In particular, a load of the value followed by a successful
1975 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
1976 /// changed the value in the interim. This is usually important when the *equality* check in
1977 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
1978 /// does not necessarily imply identity. This is a particularly common case for pointers, as
1979 /// a pointer holding the same address does not imply that the same object exists at that
1980 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
1981 ///
1982 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1983 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1984#[inline]
1985 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1986 #[cfg(target_has_atomic = "ptr")]
1987 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1988#[rustc_should_not_be_called_on_const_items]
1989pub fn compare_exchange_weak(
1990&self,
1991 current: *mut T,
1992 new: *mut T,
1993 success: Ordering,
1994 failure: Ordering,
1995 ) -> Result<*mut T, *mut T> {
1996// SAFETY: This intrinsic is unsafe because it operates on a raw pointer
1997 // but we know for sure that the pointer is valid (we just got it from
1998 // an `UnsafeCell` that we have by reference) and the atomic operation
1999 // itself allows us to safely mutate the `UnsafeCell` contents.
2000unsafe { atomic_compare_exchange_weak(self.as_ptr(), current, new, success, failure) }
2001 }
20022003/// An alias for [`AtomicPtr::try_update`].
2004#[inline]
2005 #[stable(feature = "atomic_fetch_update", since = "1.53.0")]
2006 #[cfg(target_has_atomic = "ptr")]
2007 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2008#[rustc_should_not_be_called_on_const_items]
2009 #[deprecated(
2010 since = "1.99.0",
2011 note = "renamed to `try_update` for consistency",
2012 suggestion = "try_update"
2013)]
2014pub fn fetch_update<F>(
2015&self,
2016 set_order: Ordering,
2017 fetch_order: Ordering,
2018 f: F,
2019 ) -> Result<*mut T, *mut T>
2020where
2021F: FnMut(*mut T) -> Option<*mut T>,
2022 {
2023self.try_update(set_order, fetch_order, f)
2024 }
2025/// Fetches the value, and applies a function to it that returns an optional
2026 /// new value. Returns a `Result` of `Ok(previous_value)` if the function
2027 /// returned `Some(_)`, else `Err(previous_value)`.
2028 ///
2029 /// See also: [`update`](`AtomicPtr::update`).
2030 ///
2031 /// Note: This may call the function multiple times if the value has been
2032 /// changed from other threads in the meantime, as long as the function
2033 /// returns `Some(_)`, but the function will have been applied only once to
2034 /// the stored value.
2035 ///
2036 /// `try_update` takes two [`Ordering`] arguments to describe the memory
2037 /// ordering of this operation. The first describes the required ordering for
2038 /// when the operation finally succeeds while the second describes the
2039 /// required ordering for loads. These correspond to the success and failure
2040 /// orderings of [`AtomicPtr::compare_exchange`] respectively.
2041 ///
2042 /// Using [`Acquire`] as success ordering makes the store part of this
2043 /// operation [`Relaxed`], and using [`Release`] makes the final successful
2044 /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
2045 /// [`Acquire`] or [`Relaxed`].
2046 ///
2047 /// **Note:** This method is only available on platforms that support atomic
2048 /// operations on pointers.
2049 ///
2050 /// # Considerations
2051 ///
2052 /// This method is not magic; it is not provided by the hardware, and does not act like a
2053 /// critical section or mutex.
2054 ///
2055 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
2056 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
2057 /// which is a particularly common pitfall for pointers!
2058 ///
2059 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
2060 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
2061 ///
2062 /// # Examples
2063 ///
2064 /// ```rust
2065 /// use std::sync::atomic::{AtomicPtr, Ordering};
2066 ///
2067 /// let ptr: *mut _ = &mut 5;
2068 /// let some_ptr = AtomicPtr::new(ptr);
2069 ///
2070 /// let new: *mut _ = &mut 10;
2071 /// assert_eq!(some_ptr.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr));
2072 /// let result = some_ptr.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
2073 /// if x == ptr {
2074 /// Some(new)
2075 /// } else {
2076 /// None
2077 /// }
2078 /// });
2079 /// assert_eq!(result, Ok(ptr));
2080 /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
2081 /// ```
2082#[inline]
2083 #[stable(feature = "atomic_try_update", since = "1.95.0")]
2084 #[cfg(target_has_atomic = "ptr")]
2085 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2086#[rustc_should_not_be_called_on_const_items]
2087pub fn try_update(
2088&self,
2089 set_order: Ordering,
2090 fetch_order: Ordering,
2091mut f: impl FnMut(*mut T) -> Option<*mut T>,
2092 ) -> Result<*mut T, *mut T> {
2093let mut prev = self.load(fetch_order);
2094while let Some(next) = f(prev) {
2095match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
2096 x @ Ok(_) => return x,
2097Err(next_prev) => prev = next_prev,
2098 }
2099 }
2100Err(prev)
2101 }
21022103/// Fetches the value, applies a function to it that it return a new value.
2104 /// The new value is stored and the old value is returned.
2105 ///
2106 /// See also: [`try_update`](`AtomicPtr::try_update`).
2107 ///
2108 /// Note: This may call the function multiple times if the value has been changed from other threads in
2109 /// the meantime, but the function will have been applied only once to the stored value.
2110 ///
2111 /// `update` takes two [`Ordering`] arguments to describe the memory
2112 /// ordering of this operation. The first describes the required ordering for
2113 /// when the operation finally succeeds while the second describes the
2114 /// required ordering for loads. These correspond to the success and failure
2115 /// orderings of [`AtomicPtr::compare_exchange`] respectively.
2116 ///
2117 /// Using [`Acquire`] as success ordering makes the store part
2118 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
2119 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
2120 ///
2121 /// **Note:** This method is only available on platforms that support atomic
2122 /// operations on pointers.
2123 ///
2124 /// # Considerations
2125 ///
2126 /// This method is not magic; it is not provided by the hardware, and does not act like a
2127 /// critical section or mutex.
2128 ///
2129 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
2130 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
2131 /// which is a particularly common pitfall for pointers!
2132 ///
2133 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
2134 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
2135 ///
2136 /// # Examples
2137 ///
2138 /// ```rust
2139 ///
2140 /// use std::sync::atomic::{AtomicPtr, Ordering};
2141 ///
2142 /// let ptr: *mut _ = &mut 5;
2143 /// let some_ptr = AtomicPtr::new(ptr);
2144 ///
2145 /// let new: *mut _ = &mut 10;
2146 /// let result = some_ptr.update(Ordering::SeqCst, Ordering::SeqCst, |_| new);
2147 /// assert_eq!(result, ptr);
2148 /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
2149 /// ```
2150#[inline]
2151 #[stable(feature = "atomic_try_update", since = "1.95.0")]
2152 #[cfg(target_has_atomic = "ptr")]
2153 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2154#[rustc_should_not_be_called_on_const_items]
2155pub fn update(
2156&self,
2157 set_order: Ordering,
2158 fetch_order: Ordering,
2159mut f: impl FnMut(*mut T) -> *mut T,
2160 ) -> *mut T {
2161let mut prev = self.load(fetch_order);
2162loop {
2163match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
2164Ok(x) => break x,
2165Err(next_prev) => prev = next_prev,
2166 }
2167 }
2168 }
21692170/// Offsets the pointer's address by adding `val` (in units of `T`),
2171 /// returning the previous pointer.
2172 ///
2173 /// This is equivalent to using [`wrapping_add`] to atomically perform the
2174 /// equivalent of `ptr = ptr.wrapping_add(val);`.
2175 ///
2176 /// This method operates in units of `T`, which means that it cannot be used
2177 /// to offset the pointer by an amount which is not a multiple of
2178 /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
2179 /// work with a deliberately misaligned pointer. In such cases, you may use
2180 /// the [`fetch_byte_add`](Self::fetch_byte_add) method instead.
2181 ///
2182 /// `fetch_ptr_add` takes an [`Ordering`] argument which describes the
2183 /// memory ordering of this operation. All ordering modes are possible. Note
2184 /// that using [`Acquire`] makes the store part of this operation
2185 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2186 ///
2187 /// **Note**: This method is only available on platforms that support atomic
2188 /// operations on [`AtomicPtr`].
2189 ///
2190 /// [`wrapping_add`]: pointer::wrapping_add
2191 ///
2192 /// # Examples
2193 ///
2194 /// ```
2195 /// use core::sync::atomic::{AtomicPtr, Ordering};
2196 ///
2197 /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
2198 /// assert_eq!(atom.fetch_ptr_add(1, Ordering::Relaxed).addr(), 0);
2199 /// // Note: units of `size_of::<i64>()`.
2200 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 8);
2201 /// ```
2202#[inline]
2203 #[cfg(target_has_atomic = "ptr")]
2204 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2205 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2206#[rustc_should_not_be_called_on_const_items]
2207pub fn fetch_ptr_add(&self, val: usize, order: Ordering) -> *mut T {
2208self.fetch_byte_add(val.wrapping_mul(size_of::<T>()), order)
2209 }
22102211/// Offsets the pointer's address by subtracting `val` (in units of `T`),
2212 /// returning the previous pointer.
2213 ///
2214 /// This is equivalent to using [`wrapping_sub`] to atomically perform the
2215 /// equivalent of `ptr = ptr.wrapping_sub(val);`.
2216 ///
2217 /// This method operates in units of `T`, which means that it cannot be used
2218 /// to offset the pointer by an amount which is not a multiple of
2219 /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
2220 /// work with a deliberately misaligned pointer. In such cases, you may use
2221 /// the [`fetch_byte_sub`](Self::fetch_byte_sub) method instead.
2222 ///
2223 /// `fetch_ptr_sub` takes an [`Ordering`] argument which describes the memory
2224 /// ordering of this operation. All ordering modes are possible. Note that
2225 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2226 /// and using [`Release`] makes the load part [`Relaxed`].
2227 ///
2228 /// **Note**: This method is only available on platforms that support atomic
2229 /// operations on [`AtomicPtr`].
2230 ///
2231 /// [`wrapping_sub`]: pointer::wrapping_sub
2232 ///
2233 /// # Examples
2234 ///
2235 /// ```
2236 /// use core::sync::atomic::{AtomicPtr, Ordering};
2237 ///
2238 /// let array = [1i32, 2i32];
2239 /// let atom = AtomicPtr::new(array.as_ptr().wrapping_add(1) as *mut _);
2240 ///
2241 /// assert!(core::ptr::eq(
2242 /// atom.fetch_ptr_sub(1, Ordering::Relaxed),
2243 /// &array[1],
2244 /// ));
2245 /// assert!(core::ptr::eq(atom.load(Ordering::Relaxed), &array[0]));
2246 /// ```
2247#[inline]
2248 #[cfg(target_has_atomic = "ptr")]
2249 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2250 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2251#[rustc_should_not_be_called_on_const_items]
2252pub fn fetch_ptr_sub(&self, val: usize, order: Ordering) -> *mut T {
2253self.fetch_byte_sub(val.wrapping_mul(size_of::<T>()), order)
2254 }
22552256/// Offsets the pointer's address by adding `val` *bytes*, returning the
2257 /// previous pointer.
2258 ///
2259 /// This is equivalent to using [`wrapping_byte_add`] to atomically
2260 /// perform `ptr = ptr.wrapping_byte_add(val)`.
2261 ///
2262 /// `fetch_byte_add` takes an [`Ordering`] argument which describes the
2263 /// memory ordering of this operation. All ordering modes are possible. Note
2264 /// that using [`Acquire`] makes the store part of this operation
2265 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2266 ///
2267 /// **Note**: This method is only available on platforms that support atomic
2268 /// operations on [`AtomicPtr`].
2269 ///
2270 /// [`wrapping_byte_add`]: pointer::wrapping_byte_add
2271 ///
2272 /// # Examples
2273 ///
2274 /// ```
2275 /// use core::sync::atomic::{AtomicPtr, Ordering};
2276 ///
2277 /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
2278 /// assert_eq!(atom.fetch_byte_add(1, Ordering::Relaxed).addr(), 0);
2279 /// // Note: in units of bytes, not `size_of::<i64>()`.
2280 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 1);
2281 /// ```
2282#[inline]
2283 #[cfg(target_has_atomic = "ptr")]
2284 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2285 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2286#[rustc_should_not_be_called_on_const_items]
2287pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T {
2288// SAFETY: data races are prevented by atomic intrinsics.
2289unsafe { atomic_add(self.as_ptr(), val, order).cast() }
2290 }
22912292/// Offsets the pointer's address by subtracting `val` *bytes*, returning the
2293 /// previous pointer.
2294 ///
2295 /// This is equivalent to using [`wrapping_byte_sub`] to atomically
2296 /// perform `ptr = ptr.wrapping_byte_sub(val)`.
2297 ///
2298 /// `fetch_byte_sub` takes an [`Ordering`] argument which describes the
2299 /// memory ordering of this operation. All ordering modes are possible. Note
2300 /// that using [`Acquire`] makes the store part of this operation
2301 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2302 ///
2303 /// **Note**: This method is only available on platforms that support atomic
2304 /// operations on [`AtomicPtr`].
2305 ///
2306 /// [`wrapping_byte_sub`]: pointer::wrapping_byte_sub
2307 ///
2308 /// # Examples
2309 ///
2310 /// ```
2311 /// use core::sync::atomic::{AtomicPtr, Ordering};
2312 ///
2313 /// let mut arr = [0i64, 1];
2314 /// let atom = AtomicPtr::<i64>::new(&raw mut arr[1]);
2315 /// assert_eq!(atom.fetch_byte_sub(8, Ordering::Relaxed).addr(), (&raw const arr[1]).addr());
2316 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), (&raw const arr[0]).addr());
2317 /// ```
2318#[inline]
2319 #[cfg(target_has_atomic = "ptr")]
2320 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2321 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2322#[rustc_should_not_be_called_on_const_items]
2323pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T {
2324// SAFETY: data races are prevented by atomic intrinsics.
2325unsafe { atomic_sub(self.as_ptr(), val, order).cast() }
2326 }
23272328/// Performs a bitwise "or" operation on the address of the current pointer,
2329 /// and the argument `val`, and stores a pointer with provenance of the
2330 /// current pointer and the resulting address.
2331 ///
2332 /// This is equivalent to using [`map_addr`] to atomically perform
2333 /// `ptr = ptr.map_addr(|a| a | val)`. This can be used in tagged
2334 /// pointer schemes to atomically set tag bits.
2335 ///
2336 /// **Caveat**: This operation returns the previous value. To compute the
2337 /// stored value without losing provenance, you may use [`map_addr`]. For
2338 /// example: `a.fetch_or(val).map_addr(|a| a | val)`.
2339 ///
2340 /// `fetch_or` takes an [`Ordering`] argument which describes the memory
2341 /// ordering of this operation. All ordering modes are possible. Note that
2342 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2343 /// and using [`Release`] makes the load part [`Relaxed`].
2344 ///
2345 /// **Note**: This method is only available on platforms that support atomic
2346 /// operations on [`AtomicPtr`].
2347 ///
2348 /// This API and its claimed semantics are part of the Strict Provenance
2349 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2350 /// details.
2351 ///
2352 /// [`map_addr`]: pointer::map_addr
2353 ///
2354 /// # Examples
2355 ///
2356 /// ```
2357 /// use core::sync::atomic::{AtomicPtr, Ordering};
2358 ///
2359 /// let pointer = &mut 3i64 as *mut i64;
2360 ///
2361 /// let atom = AtomicPtr::<i64>::new(pointer);
2362 /// // Tag the bottom bit of the pointer.
2363 /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 0);
2364 /// // Extract and untag.
2365 /// let tagged = atom.load(Ordering::Relaxed);
2366 /// assert_eq!(tagged.addr() & 1, 1);
2367 /// assert_eq!(tagged.map_addr(|p| p & !1), pointer);
2368 /// ```
2369#[inline]
2370 #[cfg(target_has_atomic = "ptr")]
2371 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2372 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2373#[rustc_should_not_be_called_on_const_items]
2374pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T {
2375// SAFETY: data races are prevented by atomic intrinsics.
2376unsafe { atomic_or(self.as_ptr(), val, order).cast() }
2377 }
23782379/// Performs a bitwise "and" operation on the address of the current
2380 /// pointer, and the argument `val`, and stores a pointer with provenance of
2381 /// the current pointer and the resulting address.
2382 ///
2383 /// This is equivalent to using [`map_addr`] to atomically perform
2384 /// `ptr = ptr.map_addr(|a| a & val)`. This can be used in tagged
2385 /// pointer schemes to atomically unset tag bits.
2386 ///
2387 /// **Caveat**: This operation returns the previous value. To compute the
2388 /// stored value without losing provenance, you may use [`map_addr`]. For
2389 /// example: `a.fetch_and(val).map_addr(|a| a & val)`.
2390 ///
2391 /// `fetch_and` takes an [`Ordering`] argument which describes the memory
2392 /// ordering of this operation. All ordering modes are possible. Note that
2393 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2394 /// and using [`Release`] makes the load part [`Relaxed`].
2395 ///
2396 /// **Note**: This method is only available on platforms that support atomic
2397 /// operations on [`AtomicPtr`].
2398 ///
2399 /// This API and its claimed semantics are part of the Strict Provenance
2400 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2401 /// details.
2402 ///
2403 /// [`map_addr`]: pointer::map_addr
2404 ///
2405 /// # Examples
2406 ///
2407 /// ```
2408 /// use core::sync::atomic::{AtomicPtr, Ordering};
2409 ///
2410 /// let pointer = &mut 3i64 as *mut i64;
2411 /// // A tagged pointer
2412 /// let atom = AtomicPtr::<i64>::new(pointer.map_addr(|a| a | 1));
2413 /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 1);
2414 /// // Untag, and extract the previously tagged pointer.
2415 /// let untagged = atom.fetch_and(!1, Ordering::Relaxed)
2416 /// .map_addr(|a| a & !1);
2417 /// assert_eq!(untagged, pointer);
2418 /// ```
2419#[inline]
2420 #[cfg(target_has_atomic = "ptr")]
2421 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2422 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2423#[rustc_should_not_be_called_on_const_items]
2424pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T {
2425// SAFETY: data races are prevented by atomic intrinsics.
2426unsafe { atomic_and(self.as_ptr(), val, order).cast() }
2427 }
24282429/// Performs a bitwise "xor" operation on the address of the current
2430 /// pointer, and the argument `val`, and stores a pointer with provenance of
2431 /// the current pointer and the resulting address.
2432 ///
2433 /// This is equivalent to using [`map_addr`] to atomically perform
2434 /// `ptr = ptr.map_addr(|a| a ^ val)`. This can be used in tagged
2435 /// pointer schemes to atomically toggle tag bits.
2436 ///
2437 /// **Caveat**: This operation returns the previous value. To compute the
2438 /// stored value without losing provenance, you may use [`map_addr`]. For
2439 /// example: `a.fetch_xor(val).map_addr(|a| a ^ val)`.
2440 ///
2441 /// `fetch_xor` takes an [`Ordering`] argument which describes the memory
2442 /// ordering of this operation. All ordering modes are possible. Note that
2443 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2444 /// and using [`Release`] makes the load part [`Relaxed`].
2445 ///
2446 /// **Note**: This method is only available on platforms that support atomic
2447 /// operations on [`AtomicPtr`].
2448 ///
2449 /// This API and its claimed semantics are part of the Strict Provenance
2450 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2451 /// details.
2452 ///
2453 /// [`map_addr`]: pointer::map_addr
2454 ///
2455 /// # Examples
2456 ///
2457 /// ```
2458 /// use core::sync::atomic::{AtomicPtr, Ordering};
2459 ///
2460 /// let pointer = &mut 3i64 as *mut i64;
2461 /// let atom = AtomicPtr::<i64>::new(pointer);
2462 ///
2463 /// // Toggle a tag bit on the pointer.
2464 /// atom.fetch_xor(1, Ordering::Relaxed);
2465 /// assert_eq!(atom.load(Ordering::Relaxed).addr() & 1, 1);
2466 /// ```
2467#[inline]
2468 #[cfg(target_has_atomic = "ptr")]
2469 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2470 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2471#[rustc_should_not_be_called_on_const_items]
2472pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T {
2473// SAFETY: data races are prevented by atomic intrinsics.
2474unsafe { atomic_xor(self.as_ptr(), val, order).cast() }
2475 }
24762477/// Returns a mutable pointer to the underlying pointer.
2478 ///
2479 /// Doing non-atomic reads and writes on the resulting pointer can be a data race.
2480 /// This method is mostly useful for FFI, where the function signature may use
2481 /// `*mut *mut T` instead of `&AtomicPtr<T>`.
2482 ///
2483 /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
2484 /// atomic types work with interior mutability. All modifications of an atomic change the value
2485 /// through a shared reference, and can do so safely as long as they use atomic operations. Any
2486 /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
2487 /// requirements of the [memory model].
2488 ///
2489 /// # Examples
2490 ///
2491 /// ```ignore (extern-declaration)
2492 /// use std::sync::atomic::AtomicPtr;
2493 ///
2494 /// extern "C" {
2495 /// fn my_atomic_op(arg: *mut *mut u32);
2496 /// }
2497 ///
2498 /// let mut value = 17;
2499 /// let atomic = AtomicPtr::new(&mut value);
2500 ///
2501 /// // SAFETY: Safe as long as `my_atomic_op` is atomic.
2502 /// unsafe {
2503 /// my_atomic_op(atomic.as_ptr());
2504 /// }
2505 /// ```
2506 ///
2507 /// [memory model]: self#memory-model-for-atomic-accesses
2508#[inline]
2509 #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
2510 #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
2511 #[rustc_never_returns_null_ptr]
2512pub const fn as_ptr(&self) -> *mut *mut T {
2513self.v.get().cast()
2514 }
2515}
25162517#[cfg(target_has_atomic_load_store = "8")]
2518#[stable(feature = "atomic_bool_from", since = "1.24.0")]
2519#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2520const impl From<bool> for AtomicBool {
2521/// Converts a `bool` into an `AtomicBool`.
2522 ///
2523 /// # Examples
2524 ///
2525 /// ```
2526 /// use std::sync::atomic::AtomicBool;
2527 /// let atomic_bool = AtomicBool::from(true);
2528 /// assert_eq!(format!("{atomic_bool:?}"), "true")
2529 /// ```
2530#[inline]
2531fn from(b: bool) -> Self {
2532Self::new(b)
2533 }
2534}
25352536#[cfg(target_has_atomic_load_store = "ptr")]
2537#[stable(feature = "atomic_from", since = "1.23.0")]
2538#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2539const impl<T> From<*mut T> for AtomicPtr<T> {
2540/// Converts a `*mut T` into an `AtomicPtr<T>`.
2541#[inline]
2542fn from(p: *mut T) -> Self {
2543Self::new(p)
2544 }
2545}
25462547#[allow(unused_macros)] // This macro ends up being unused on some architectures.
2548macro_rules!if_8_bit {
2549 (u8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) };
2550 (i8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) };
2551 ($_:ident, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($no)*)?) };
2552}
25532554#[cfg(target_has_atomic_load_store)]
2555macro_rules!atomic_int {
2556 ($cfg_base:meta,
2557$cfg_cas:meta,
2558$cfg_align:meta,
2559$stable:meta,
2560$stable_cxchg:meta,
2561$stable_debug:meta,
2562$stable_access:meta,
2563$stable_from:meta,
2564$stable_nand:meta,
2565$const_stable_new:meta,
2566$const_stable_into_inner:meta,
2567$s_int_type:literal,
2568$extra_feature:expr,
2569$min_fn:ident, $max_fn:ident,
2570$align:expr,
2571$int_type:ident $atomic_type:ident) => {
2572/// An integer type which can be safely shared between threads.
2573 ///
2574 /// This type has the same
2575#[doc = if_8_bit!(
2576$int_type,
2577 yes = ["size, alignment, and bit validity"],
2578 no = ["size and bit validity"],
2579 )]
2580/// as the underlying integer type, [`
2581#[doc = $s_int_type]
2582/// `].
2583#[doc = if_8_bit! {
2584$int_type,
2585 no = [
2586"However, the alignment of this type is always equal to its ",
2587"size, even on targets where [`", $s_int_type, "`] has a ",
2588"lesser alignment."
2589],
2590 }]
2591///
2592 /// For more about the differences between atomic types and
2593 /// non-atomic types as well as information about the portability of
2594 /// this type, please see the [module-level documentation].
2595 ///
2596 /// **Note:** This type is only available on platforms that support
2597 /// atomic loads and stores of [`
2598#[doc = $s_int_type]
2599/// `].
2600 ///
2601 /// [module-level documentation]: crate::sync::atomic
2602#[$stable]
2603pub type $atomic_type = Atomic<$int_type>;
26042605#[$stable]
2606impl Default for $atomic_type {
2607#[inline]
2608fn default() -> Self {
2609Self::new(Default::default())
2610 }
2611 }
26122613#[$stable_from]
2614 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2615const impl From<$int_type> for $atomic_type {
2616#[doc = concat!("Converts an `", stringify!($int_type), "` into an `", stringify!($atomic_type), "`.")]
2617 #[inline]
2618fn from(v: $int_type) -> Self { Self::new(v) }
2619 }
26202621#[$stable_debug]
2622impl fmt::Debug for $atomic_type {
2623fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2624 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
2625 }
2626 }
26272628impl $atomic_type {
2629/// Creates a new atomic integer.
2630 ///
2631 /// # Examples
2632 ///
2633#[cfg_attr($cfg_base, doc = "```")]
2634 #[cfg_attr(not($cfg_base), doc = "```compile_fail")]
2635 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2636///
2637#[doc = concat!("let atomic_forty_two = ", stringify!($atomic_type), "::new(42);")]
2638/// ```
2639#[inline]
2640 #[$stable]
2641 #[$const_stable_new]
2642 #[must_use]
2643pub const fn new(v: $int_type) -> Self {
2644// SAFETY:
2645 // `Atomic<T>` is essentially a transparent wrapper around `T`.
2646unsafe { transmute(v) }
2647 }
26482649/// Creates a new reference to an atomic integer from a pointer.
2650 ///
2651 /// # Examples
2652 ///
2653#[cfg_attr($cfg_base, doc = "```rust")]
2654 #[cfg_attr(not($cfg_base), doc = "```rust,compile_fail")]
2655 #[doc = concat!($extra_feature, "use std::sync::atomic::{self, ", stringify!($atomic_type), "};")]
2656///
2657 /// // Get a pointer to an allocated value
2658#[doc = concat!("let ptr: *mut ", stringify!($int_type), " = Box::into_raw(Box::new(0));")]
2659///
2660#[doc = concat!("assert!(ptr.cast::<", stringify!($atomic_type), ">().is_aligned());")]
2661///
2662 /// {
2663 /// // Create an atomic view of the allocated value
2664// SAFETY: this is a doc comment, tidy, it can't hurt you (also guaranteed by the construction of `ptr` and the assert above)
2665#[doc = concat!(" let atomic = unsafe {", stringify!($atomic_type), "::from_ptr(ptr) };")]
2666///
2667 /// // Use `atomic` for atomic operations, possibly share it with other threads
2668 /// atomic.store(1, atomic::Ordering::Relaxed);
2669 /// }
2670 ///
2671 /// // It's ok to non-atomically access the value behind `ptr`,
2672 /// // since the reference to the atomic ended its lifetime in the block above
2673 /// assert_eq!(unsafe { *ptr }, 1);
2674 ///
2675 /// // Deallocate the value
2676 /// unsafe { drop(Box::from_raw(ptr)) }
2677 /// ```
2678 ///
2679 /// # Safety
2680 ///
2681 /// * `ptr` must be aligned to
2682#[doc = concat!(" `align_of::<", stringify!($atomic_type), ">()`")]
2683 #[doc = if_8_bit!{
2684$int_type,
2685 yes = [
2686" (note that this is always true, since `align_of::<",
2687stringify!($atomic_type), ">() == 1`)."
2688],
2689 no = [
2690" (note that on some platforms this can be bigger than `align_of::<",
2691stringify!($int_type), ">()`)."
2692],
2693 }]
2694/// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
2695 /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
2696 /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
2697 /// sizes, without synchronization.
2698 ///
2699 /// [valid]: crate::ptr#safety
2700 /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
2701#[inline]
2702 #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
2703 #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
2704pub const unsafe fn from_ptr<'a>(ptr: *mut $int_type) -> &'a $atomic_type {
2705// SAFETY: guaranteed by the caller
2706unsafe { &*ptr.cast() }
2707 }
27082709/// Returns a mutable reference to the underlying integer.
2710 ///
2711 /// This is safe because the mutable reference guarantees that no other threads are
2712 /// concurrently accessing the atomic data.
2713 ///
2714 /// # Examples
2715 ///
2716#[cfg_attr($cfg_base, doc = "```")]
2717 #[cfg_attr(not($cfg_base), doc = "```compile_fail")]
2718 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2719///
2720#[doc = concat!("let mut some_var = ", stringify!($atomic_type), "::new(10);")]
2721/// assert_eq!(*some_var.get_mut(), 10);
2722 /// *some_var.get_mut() = 5;
2723 /// assert_eq!(some_var.load(Ordering::SeqCst), 5);
2724 /// ```
2725#[inline]
2726 #[$stable_access]
2727pub fn get_mut(&mut self) -> &mut $int_type {
2728// SAFETY:
2729 // `Atomic<T>` is essentially a transparent wrapper around `T`.
2730unsafe { &mut *self.as_ptr() }
2731 }
27322733#[doc = concat!("Get atomic access to a `&mut ", stringify!($int_type), "`.")]
2734///
2735#[doc = if_8_bit! {
2736$int_type,
2737 no = [
2738"**Note:** This function is only available on targets where `",
2739stringify!($atomic_type), "` has the same alignment as `", stringify!($int_type), "`."
2740],
2741 }]
2742///
2743 /// # Examples
2744 ///
2745#[cfg_attr($cfg_align, doc = "```rust")]
2746 #[cfg_attr(not($cfg_align), doc = "```rust,compile_fail")]
2747 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2748///
2749 /// let mut some_int = 123;
2750#[doc = concat!("let a = ", stringify!($atomic_type), "::from_mut(&mut some_int);")]
2751/// a.store(100, Ordering::Relaxed);
2752 /// assert_eq!(some_int, 100);
2753 /// ```
2754 ///
2755#[inline]
2756 #[cfg(any($cfg_align, doc))]
2757 #[stable(feature = "atomic_from_mut", since = "1.98.0")]
2758pub fn from_mut(v: &mut $int_type) -> &mut Self {
2759let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
2760// SAFETY:
2761 // - the mutable reference guarantees unique ownership.
2762 // - the alignment of `$int_type` and `Self` is the
2763 // same, as promised by $cfg_align and verified above.
2764unsafe { &mut *(v as *mut $int_type as *mut Self) }
2765 }
27662767#[doc = concat!("Get non-atomic access to a `&mut [", stringify!($atomic_type), "]` slice")]
2768///
2769 /// This is safe because the mutable reference guarantees that no other threads are
2770 /// concurrently accessing the atomic data.
2771 ///
2772 /// # Examples
2773 ///
2774#[cfg_attr($cfg_base, doc = "```ignore-wasm")]
2775 #[cfg_attr(not($cfg_base), doc = "```ignore-wasm,compile_fail")]
2776 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2777///
2778#[doc = concat!("let mut some_ints = [const { ", stringify!($atomic_type), "::new(0) }; 10];")]
2779///
2780#[doc = concat!("let view: &mut [", stringify!($int_type), "] = ", stringify!($atomic_type), "::get_mut_slice(&mut some_ints);")]
2781/// assert_eq!(view, [0; 10]);
2782 /// view
2783 /// .iter_mut()
2784 /// .enumerate()
2785 /// .for_each(|(idx, int)| *int = idx as _);
2786 ///
2787 /// std::thread::scope(|s| {
2788 /// some_ints
2789 /// .iter()
2790 /// .enumerate()
2791 /// .for_each(|(idx, int)| {
2792 /// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
2793 /// })
2794 /// });
2795 /// ```
2796#[inline]
2797 #[stable(feature = "atomic_from_mut", since = "1.98.0")]
2798pub fn get_mut_slice(this: &mut [Self]) -> &mut [$int_type] {
2799// SAFETY: the mutable reference guarantees unique ownership.
2800unsafe { &mut *(this as *mut [Self] as *mut [$int_type]) }
2801 }
28022803#[doc = concat!("Get atomic access to a `&mut [", stringify!($int_type), "]` slice.")]
2804///
2805#[doc = if_8_bit! {
2806$int_type,
2807 no = [
2808"**Note:** This function is only available on targets where `",
2809stringify!($atomic_type), "` has the same alignment as `", stringify!($int_type), "`."
2810],
2811 }]
2812///
2813 /// # Examples
2814 ///
2815#[cfg_attr($cfg_align, doc = "```ignore-wasm")]
2816 #[cfg_attr(not($cfg_align), doc = "```ignore-wasm,compile_fail")]
2817 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2818///
2819 /// let mut some_ints = [0; 10];
2820#[doc = concat!("let a = &*", stringify!($atomic_type), "::from_mut_slice(&mut some_ints);")]
2821/// std::thread::scope(|s| {
2822 /// for i in 0..a.len() {
2823 /// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
2824 /// }
2825 /// });
2826 /// for (i, n) in some_ints.into_iter().enumerate() {
2827 /// assert_eq!(i, n as usize);
2828 /// }
2829 /// ```
2830#[inline]
2831 #[cfg(any($cfg_align, doc))]
2832 #[stable(feature = "atomic_from_mut", since = "1.98.0")]
2833pub fn from_mut_slice(v: &mut [$int_type]) -> &mut [Self] {
2834let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
2835// SAFETY:
2836 // - the mutable reference guarantees unique ownership.
2837 // - the alignment of `$int_type` and `Self` is the
2838 // same, as promised by $cfg_align and verified above.
2839unsafe { &mut *(v as *mut [$int_type] as *mut [Self]) }
2840 }
28412842/// Consumes the atomic and returns the contained value.
2843 ///
2844 /// This is safe because passing `self` by value guarantees that no other threads are
2845 /// concurrently accessing the atomic data.
2846 ///
2847 /// # Examples
2848 ///
2849#[cfg_attr($cfg_base, doc = "```")]
2850 #[cfg_attr(not($cfg_base), doc = "```compile_fail")]
2851 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2852///
2853#[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2854/// assert_eq!(some_var.into_inner(), 5);
2855 /// ```
2856#[inline]
2857 #[$stable_access]
2858 #[$const_stable_into_inner]
2859pub const fn into_inner(self) -> $int_type {
2860// SAFETY:
2861 // `Atomic<T>` is essentially a transparent wrapper around `T`.
2862unsafe { transmute(self) }
2863 }
28642865/// Loads a value from the atomic integer.
2866 ///
2867 /// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2868 /// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
2869 ///
2870 /// # Panics
2871 ///
2872 /// Panics if `order` is [`Release`] or [`AcqRel`].
2873 ///
2874 /// # Examples
2875 ///
2876#[cfg_attr($cfg_base, doc = "```")]
2877 #[cfg_attr(not($cfg_base), doc = "```compile_fail")]
2878 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2879///
2880#[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2881///
2882 /// assert_eq!(some_var.load(Ordering::Relaxed), 5);
2883 /// ```
2884#[inline]
2885 #[$stable]
2886 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2887pub fn load(&self, order: Ordering) -> $int_type {
2888// SAFETY: data races are prevented by atomic intrinsics.
2889unsafe { atomic_load(self.as_ptr(), order) }
2890 }
28912892/// Stores a value into the atomic integer.
2893 ///
2894 /// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2895 /// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
2896 ///
2897 /// # Panics
2898 ///
2899 /// Panics if `order` is [`Acquire`] or [`AcqRel`].
2900 ///
2901 /// # Examples
2902 ///
2903#[cfg_attr($cfg_base, doc = "```")]
2904 #[cfg_attr(not($cfg_base), doc = "```compile_fail")]
2905 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2906///
2907#[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2908///
2909 /// some_var.store(10, Ordering::Relaxed);
2910 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2911 /// ```
2912#[inline]
2913 #[$stable]
2914 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2915#[rustc_should_not_be_called_on_const_items]
2916pub fn store(&self, val: $int_type, order: Ordering) {
2917// SAFETY: data races are prevented by atomic intrinsics.
2918unsafe { atomic_store(self.as_ptr(), val, order); }
2919 }
29202921/// Stores a value into the atomic integer, returning the previous value.
2922 ///
2923 /// `swap` takes an [`Ordering`] argument which describes the memory ordering
2924 /// of this operation. All ordering modes are possible. Note that using
2925 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2926 /// using [`Release`] makes the load part [`Relaxed`].
2927 ///
2928 /// **Note**: This method is only available on platforms that support atomic operations on
2929#[doc = concat!("[`", $s_int_type, "`].")]
2930///
2931 /// # Examples
2932 ///
2933#[cfg_attr($cfg_cas, doc = "```")]
2934 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
2935 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2936///
2937#[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2938///
2939 /// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
2940 /// ```
2941#[inline]
2942 #[$stable]
2943 #[cfg(any($cfg_cas, doc))]
2944 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2945#[rustc_should_not_be_called_on_const_items]
2946pub fn swap(&self, val: $int_type, order: Ordering) -> $int_type {
2947// SAFETY: data races are prevented by atomic intrinsics.
2948unsafe { atomic_swap(self.as_ptr(), val, order) }
2949 }
29502951/// Stores a value into the atomic integer if the current value is the same as
2952 /// the `current` value.
2953 ///
2954 /// The return value is always the previous value. If it is equal to `current`, then the
2955 /// value was updated.
2956 ///
2957 /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
2958 /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
2959 /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
2960 /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
2961 /// happens, and using [`Release`] makes the load part [`Relaxed`].
2962 ///
2963 /// **Note**: This method is only available on platforms that support atomic operations on
2964#[doc = concat!("[`", $s_int_type, "`].")]
2965///
2966 /// # Migrating to `compare_exchange` and `compare_exchange_weak`
2967 ///
2968 /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
2969 /// memory orderings:
2970 ///
2971 /// Original | Success | Failure
2972 /// -------- | ------- | -------
2973 /// Relaxed | Relaxed | Relaxed
2974 /// Acquire | Acquire | Acquire
2975 /// Release | Release | Relaxed
2976 /// AcqRel | AcqRel | Acquire
2977 /// SeqCst | SeqCst | SeqCst
2978 ///
2979 /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
2980 /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
2981 /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
2982 /// rather than to infer success vs failure based on the value that was read.
2983 ///
2984 /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
2985 /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
2986 /// which allows the compiler to generate better assembly code when the compare and swap
2987 /// is used in a loop.
2988 ///
2989 /// # Examples
2990 ///
2991#[cfg_attr($cfg_cas, doc = "```")]
2992 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
2993 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2994///
2995#[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2996///
2997 /// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
2998 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2999 ///
3000 /// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
3001 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3002 /// ```
3003#[inline]
3004 #[$stable]
3005 #[deprecated(
3006 since = "1.50.0",
3007 note = "Use `compare_exchange` or `compare_exchange_weak` instead")
3008 ]
3009 #[cfg(any($cfg_cas, doc))]
3010 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3011#[rustc_should_not_be_called_on_const_items]
3012pub fn compare_and_swap(&self,
3013 current: $int_type,
3014 new: $int_type,
3015 order: Ordering) -> $int_type {
3016match self.compare_exchange(current,
3017 new,
3018 order,
3019 strongest_failure_ordering(order)) {
3020Ok(x) => x,
3021Err(x) => x,
3022 }
3023 }
30243025/// Stores a value into the atomic integer if the current value is the same as
3026 /// the `current` value.
3027 ///
3028 /// The return value is a result indicating whether the new value was written and
3029 /// containing the previous value. On success this value is guaranteed to be equal to
3030 /// `current`.
3031 ///
3032 /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
3033 /// ordering of this operation. `success` describes the required ordering for the
3034 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
3035 /// `failure` describes the required ordering for the load operation that takes place when
3036 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
3037 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
3038 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3039 ///
3040 /// **Note**: This method is only available on platforms that support atomic operations on
3041#[doc = concat!("[`", $s_int_type, "`].")]
3042///
3043 /// # Examples
3044 ///
3045#[cfg_attr($cfg_cas, doc = "```")]
3046 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
3047 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3048///
3049#[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
3050///
3051 /// assert_eq!(some_var.compare_exchange(5, 10,
3052 /// Ordering::Acquire,
3053 /// Ordering::Relaxed),
3054 /// Ok(5));
3055 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3056 ///
3057 /// assert_eq!(some_var.compare_exchange(6, 12,
3058 /// Ordering::SeqCst,
3059 /// Ordering::Acquire),
3060 /// Err(10));
3061 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3062 /// ```
3063 ///
3064 /// # Considerations
3065 ///
3066 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
3067 /// of CAS operations. In particular, a load of the value followed by a successful
3068 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
3069 /// changed the value in the interim! This is usually important when the *equality* check in
3070 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
3071 /// does not necessarily imply identity. This is a particularly common case for pointers, as
3072 /// a pointer holding the same address does not imply that the same object exists at that
3073 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
3074 ///
3075 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3076 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3077#[inline]
3078 #[$stable_cxchg]
3079 #[cfg(any($cfg_cas, doc))]
3080 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3081#[rustc_should_not_be_called_on_const_items]
3082pub fn compare_exchange(&self,
3083 current: $int_type,
3084 new: $int_type,
3085 success: Ordering,
3086 failure: Ordering) -> Result<$int_type, $int_type> {
3087// SAFETY: data races are prevented by atomic intrinsics.
3088unsafe { atomic_compare_exchange(self.as_ptr(), current, new, success, failure) }
3089 }
30903091/// Stores a value into the atomic integer if the current value is the same as
3092 /// the `current` value.
3093 ///
3094#[doc = concat!("Unlike [`", stringify!($atomic_type), "::compare_exchange`],")]
3095/// this function is allowed to spuriously fail even
3096 /// when the comparison succeeds, which can result in more efficient code on some
3097 /// platforms. The return value is a result indicating whether the new value was
3098 /// written and containing the previous value.
3099 ///
3100 /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
3101 /// ordering of this operation. `success` describes the required ordering for the
3102 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
3103 /// `failure` describes the required ordering for the load operation that takes place when
3104 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
3105 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
3106 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3107 ///
3108 /// **Note**: This method is only available on platforms that support atomic operations on
3109#[doc = concat!("[`", $s_int_type, "`].")]
3110///
3111 /// # Examples
3112 ///
3113#[cfg_attr($cfg_cas, doc = "```")]
3114 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
3115 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3116///
3117#[doc = concat!("let val = ", stringify!($atomic_type), "::new(4);")]
3118///
3119 /// let mut old = val.load(Ordering::Relaxed);
3120 /// loop {
3121 /// let new = old * 2;
3122 /// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
3123 /// Ok(_) => break,
3124 /// Err(x) => old = x,
3125 /// }
3126 /// }
3127 /// ```
3128 ///
3129 /// # Considerations
3130 ///
3131 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
3132 /// of CAS operations. In particular, a load of the value followed by a successful
3133 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
3134 /// changed the value in the interim. This is usually important when the *equality* check in
3135 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
3136 /// does not necessarily imply identity. This is a particularly common case for pointers, as
3137 /// a pointer holding the same address does not imply that the same object exists at that
3138 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
3139 ///
3140 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3141 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3142#[inline]
3143 #[$stable_cxchg]
3144 #[cfg(any($cfg_cas, doc))]
3145 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3146#[rustc_should_not_be_called_on_const_items]
3147pub fn compare_exchange_weak(&self,
3148 current: $int_type,
3149 new: $int_type,
3150 success: Ordering,
3151 failure: Ordering) -> Result<$int_type, $int_type> {
3152// SAFETY: data races are prevented by atomic intrinsics.
3153unsafe {
3154 atomic_compare_exchange_weak(self.as_ptr(), current, new, success, failure)
3155 }
3156 }
31573158/// Adds to the current value, returning the previous value.
3159 ///
3160 /// This operation wraps around on overflow.
3161 ///
3162 /// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
3163 /// of this operation. All ordering modes are possible. Note that using
3164 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3165 /// using [`Release`] makes the load part [`Relaxed`].
3166 ///
3167 /// **Note**: This method is only available on platforms that support atomic operations on
3168#[doc = concat!("[`", $s_int_type, "`].")]
3169///
3170 /// # Examples
3171 ///
3172#[cfg_attr($cfg_cas, doc = "```")]
3173 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
3174 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3175///
3176#[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0);")]
3177/// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
3178 /// assert_eq!(foo.load(Ordering::SeqCst), 10);
3179 /// ```
3180#[inline]
3181 #[$stable]
3182 #[cfg(any($cfg_cas, doc))]
3183 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3184#[rustc_should_not_be_called_on_const_items]
3185pub fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type {
3186// SAFETY: data races are prevented by atomic intrinsics.
3187unsafe { atomic_add(self.as_ptr(), val, order) }
3188 }
31893190/// Subtracts from the current value, returning the previous value.
3191 ///
3192 /// This operation wraps around on overflow.
3193 ///
3194 /// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
3195 /// of this operation. All ordering modes are possible. Note that using
3196 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3197 /// using [`Release`] makes the load part [`Relaxed`].
3198 ///
3199 /// **Note**: This method is only available on platforms that support atomic operations on
3200#[doc = concat!("[`", $s_int_type, "`].")]
3201///
3202 /// # Examples
3203 ///
3204#[cfg_attr($cfg_cas, doc = "```")]
3205 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
3206 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3207///
3208#[doc = concat!("let foo = ", stringify!($atomic_type), "::new(20);")]
3209/// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
3210 /// assert_eq!(foo.load(Ordering::SeqCst), 10);
3211 /// ```
3212#[inline]
3213 #[$stable]
3214 #[cfg(any($cfg_cas, doc))]
3215 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3216#[rustc_should_not_be_called_on_const_items]
3217pub fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type {
3218// SAFETY: data races are prevented by atomic intrinsics.
3219unsafe { atomic_sub(self.as_ptr(), val, order) }
3220 }
32213222/// Bitwise "and" with the current value.
3223 ///
3224 /// Performs a bitwise "and" operation on the current value and the argument `val`, and
3225 /// sets the new value to the result.
3226 ///
3227 /// Returns the previous value.
3228 ///
3229 /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
3230 /// of this operation. All ordering modes are possible. Note that using
3231 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3232 /// using [`Release`] makes the load part [`Relaxed`].
3233 ///
3234 /// **Note**: This method is only available on platforms that support atomic operations on
3235#[doc = concat!("[`", $s_int_type, "`].")]
3236///
3237 /// # Examples
3238 ///
3239#[cfg_attr($cfg_cas, doc = "```")]
3240 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
3241 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3242///
3243#[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3244/// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
3245 /// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
3246 /// ```
3247#[inline]
3248 #[$stable]
3249 #[cfg(any($cfg_cas, doc))]
3250 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3251#[rustc_should_not_be_called_on_const_items]
3252pub fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type {
3253// SAFETY: data races are prevented by atomic intrinsics.
3254unsafe { atomic_and(self.as_ptr(), val, order) }
3255 }
32563257/// Bitwise "nand" with the current value.
3258 ///
3259 /// Performs a bitwise "nand" operation on the current value and the argument `val`, and
3260 /// sets the new value to the result.
3261 ///
3262 /// Returns the previous value.
3263 ///
3264 /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
3265 /// of this operation. All ordering modes are possible. Note that using
3266 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3267 /// using [`Release`] makes the load part [`Relaxed`].
3268 ///
3269 /// **Note**: This method is only available on platforms that support atomic operations on
3270#[doc = concat!("[`", $s_int_type, "`].")]
3271///
3272 /// # Examples
3273 ///
3274#[cfg_attr($cfg_cas, doc = "```")]
3275 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
3276 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3277///
3278#[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0x13);")]
3279/// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
3280 /// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
3281 /// ```
3282#[inline]
3283 #[$stable_nand]
3284 #[cfg(any($cfg_cas, doc))]
3285 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3286#[rustc_should_not_be_called_on_const_items]
3287pub fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type {
3288// SAFETY: data races are prevented by atomic intrinsics.
3289unsafe { atomic_nand(self.as_ptr(), val, order) }
3290 }
32913292/// Bitwise "or" with the current value.
3293 ///
3294 /// Performs a bitwise "or" operation on the current value and the argument `val`, and
3295 /// sets the new value to the result.
3296 ///
3297 /// Returns the previous value.
3298 ///
3299 /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
3300 /// of this operation. All ordering modes are possible. Note that using
3301 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3302 /// using [`Release`] makes the load part [`Relaxed`].
3303 ///
3304 /// **Note**: This method is only available on platforms that support atomic operations on
3305#[doc = concat!("[`", $s_int_type, "`].")]
3306///
3307 /// # Examples
3308 ///
3309#[cfg_attr($cfg_cas, doc = "```")]
3310 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
3311 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3312///
3313#[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3314/// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
3315 /// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
3316 /// ```
3317#[inline]
3318 #[$stable]
3319 #[cfg(any($cfg_cas, doc))]
3320 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3321#[rustc_should_not_be_called_on_const_items]
3322pub fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type {
3323// SAFETY: data races are prevented by atomic intrinsics.
3324unsafe { atomic_or(self.as_ptr(), val, order) }
3325 }
33263327/// Bitwise "xor" with the current value.
3328 ///
3329 /// Performs a bitwise "xor" operation on the current value and the argument `val`, and
3330 /// sets the new value to the result.
3331 ///
3332 /// Returns the previous value.
3333 ///
3334 /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
3335 /// of this operation. All ordering modes are possible. Note that using
3336 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3337 /// using [`Release`] makes the load part [`Relaxed`].
3338 ///
3339 /// **Note**: This method is only available on platforms that support atomic operations on
3340#[doc = concat!("[`", $s_int_type, "`].")]
3341///
3342 /// # Examples
3343 ///
3344#[cfg_attr($cfg_cas, doc = "```")]
3345 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
3346 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3347///
3348#[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3349/// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
3350 /// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
3351 /// ```
3352#[inline]
3353 #[$stable]
3354 #[cfg(any($cfg_cas, doc))]
3355 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3356#[rustc_should_not_be_called_on_const_items]
3357pub fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type {
3358// SAFETY: data races are prevented by atomic intrinsics.
3359unsafe { atomic_xor(self.as_ptr(), val, order) }
3360 }
33613362/// An alias for
3363#[doc = concat!("[`", stringify!($atomic_type), "::try_update`]")]
3364/// .
3365#[inline]
3366 #[stable(feature = "no_more_cas", since = "1.45.0")]
3367 #[cfg(any($cfg_cas, doc))]
3368 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3369#[rustc_should_not_be_called_on_const_items]
3370 #[deprecated(
3371 since = "1.99.0",
3372 note = "renamed to `try_update` for consistency",
3373 suggestion = "try_update"
3374)]
3375pub fn fetch_update<F>(&self,
3376 set_order: Ordering,
3377 fetch_order: Ordering,
3378 f: F) -> Result<$int_type, $int_type>
3379where F: FnMut($int_type) -> Option<$int_type> {
3380self.try_update(set_order, fetch_order, f)
3381 }
33823383/// Fetches the value, and applies a function to it that returns an optional
3384 /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
3385 /// `Err(previous_value)`.
3386 ///
3387#[doc = concat!("See also: [`update`](`", stringify!($atomic_type), "::update`).")]
3388///
3389 /// Note: This may call the function multiple times if the value has been changed from other threads in
3390 /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
3391 /// only once to the stored value.
3392 ///
3393 /// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3394 /// The first describes the required ordering for when the operation finally succeeds while the second
3395 /// describes the required ordering for loads. These correspond to the success and failure orderings of
3396#[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3397/// respectively.
3398 ///
3399 /// Using [`Acquire`] as success ordering makes the store part
3400 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3401 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3402 ///
3403 /// **Note**: This method is only available on platforms that support atomic operations on
3404#[doc = concat!("[`", $s_int_type, "`].")]
3405///
3406 /// # Considerations
3407 ///
3408 /// This method is not magic; it is not provided by the hardware, and does not act like a
3409 /// critical section or mutex.
3410 ///
3411 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3412 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3413 /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3414 /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3415 ///
3416 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3417 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3418 ///
3419 /// # Examples
3420 ///
3421#[cfg_attr($cfg_cas, doc = "```rust")]
3422 #[cfg_attr(not($cfg_cas), doc = "```rust,compile_fail")]
3423 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3424///
3425#[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3426/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
3427 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
3428 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
3429 /// assert_eq!(x.load(Ordering::SeqCst), 9);
3430 /// ```
3431#[inline]
3432 #[stable(feature = "atomic_try_update", since = "1.95.0")]
3433 #[cfg(any($cfg_cas, doc))]
3434 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3435#[rustc_should_not_be_called_on_const_items]
3436pub fn try_update(
3437&self,
3438 set_order: Ordering,
3439 fetch_order: Ordering,
3440mut f: impl FnMut($int_type) -> Option<$int_type>,
3441 ) -> Result<$int_type, $int_type> {
3442let mut prev = self.load(fetch_order);
3443while let Some(next) = f(prev) {
3444match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
3445 x @ Ok(_) => return x,
3446Err(next_prev) => prev = next_prev
3447 }
3448 }
3449Err(prev)
3450 }
34513452/// Fetches the value, applies a function to it that it return a new value.
3453 /// The new value is stored and the old value is returned.
3454 ///
3455#[doc = concat!("See also: [`try_update`](`", stringify!($atomic_type), "::try_update`).")]
3456///
3457 /// Note: This may call the function multiple times if the value has been changed from other threads in
3458 /// the meantime, but the function will have been applied only once to the stored value.
3459 ///
3460 /// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3461 /// The first describes the required ordering for when the operation finally succeeds while the second
3462 /// describes the required ordering for loads. These correspond to the success and failure orderings of
3463#[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3464/// respectively.
3465 ///
3466 /// Using [`Acquire`] as success ordering makes the store part
3467 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3468 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3469 ///
3470 /// **Note**: This method is only available on platforms that support atomic operations on
3471#[doc = concat!("[`", $s_int_type, "`].")]
3472///
3473 /// # Considerations
3474 ///
3475 /// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3476 /// This method is not magic; it is not provided by the hardware, and does not act like a
3477 /// critical section or mutex.
3478 ///
3479 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3480 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3481 /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3482 /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3483 ///
3484 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3485 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3486 ///
3487 /// # Examples
3488 ///
3489#[cfg_attr($cfg_cas, doc = "```rust")]
3490 #[cfg_attr(not($cfg_cas), doc = "```rust,compile_fail")]
3491 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3492///
3493#[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3494/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
3495 /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
3496 /// assert_eq!(x.load(Ordering::SeqCst), 9);
3497 /// ```
3498#[inline]
3499 #[stable(feature = "atomic_try_update", since = "1.95.0")]
3500 #[cfg(any($cfg_cas, doc))]
3501 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3502#[rustc_should_not_be_called_on_const_items]
3503pub fn update(
3504&self,
3505 set_order: Ordering,
3506 fetch_order: Ordering,
3507mut f: impl FnMut($int_type) -> $int_type,
3508 ) -> $int_type {
3509let mut prev = self.load(fetch_order);
3510loop {
3511match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
3512Ok(x) => break x,
3513Err(next_prev) => prev = next_prev,
3514 }
3515 }
3516 }
35173518/// Maximum with the current value.
3519 ///
3520 /// Finds the maximum of the current value and the argument `val`, and
3521 /// sets the new value to the result.
3522 ///
3523 /// Returns the previous value.
3524 ///
3525 /// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
3526 /// of this operation. All ordering modes are possible. Note that using
3527 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3528 /// using [`Release`] makes the load part [`Relaxed`].
3529 ///
3530 /// **Note**: This method is only available on platforms that support atomic operations on
3531#[doc = concat!("[`", $s_int_type, "`].")]
3532///
3533 /// # Examples
3534 ///
3535#[cfg_attr($cfg_cas, doc = "```")]
3536 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
3537 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3538///
3539#[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3540/// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
3541 /// assert_eq!(foo.load(Ordering::SeqCst), 42);
3542 /// ```
3543 ///
3544 /// If you want to obtain the maximum value in one step, you can use the following:
3545 ///
3546#[cfg_attr($cfg_cas, doc = "```")]
3547 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
3548 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3549///
3550#[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3551/// let bar = 42;
3552 /// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
3553 /// assert!(max_foo == 42);
3554 /// ```
3555#[inline]
3556 #[stable(feature = "atomic_min_max", since = "1.45.0")]
3557 #[cfg(any($cfg_cas, doc))]
3558 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3559#[rustc_should_not_be_called_on_const_items]
3560pub fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type {
3561// SAFETY: data races are prevented by atomic intrinsics.
3562unsafe { $max_fn(self.as_ptr(), val, order) }
3563 }
35643565/// Minimum with the current value.
3566 ///
3567 /// Finds the minimum of the current value and the argument `val`, and
3568 /// sets the new value to the result.
3569 ///
3570 /// Returns the previous value.
3571 ///
3572 /// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
3573 /// of this operation. All ordering modes are possible. Note that using
3574 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3575 /// using [`Release`] makes the load part [`Relaxed`].
3576 ///
3577 /// **Note**: This method is only available on platforms that support atomic operations on
3578#[doc = concat!("[`", $s_int_type, "`].")]
3579///
3580 /// # Examples
3581 ///
3582#[cfg_attr($cfg_cas, doc = "```")]
3583 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
3584 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3585///
3586#[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3587/// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
3588 /// assert_eq!(foo.load(Ordering::Relaxed), 23);
3589 /// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
3590 /// assert_eq!(foo.load(Ordering::Relaxed), 22);
3591 /// ```
3592 ///
3593 /// If you want to obtain the minimum value in one step, you can use the following:
3594 ///
3595#[cfg_attr($cfg_cas, doc = "```")]
3596 #[cfg_attr(not($cfg_cas), doc = "```compile_fail")]
3597 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3598///
3599#[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3600/// let bar = 12;
3601 /// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
3602 /// assert_eq!(min_foo, 12);
3603 /// ```
3604#[inline]
3605 #[stable(feature = "atomic_min_max", since = "1.45.0")]
3606 #[cfg(any($cfg_cas, doc))]
3607 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3608#[rustc_should_not_be_called_on_const_items]
3609pub fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type {
3610// SAFETY: data races are prevented by atomic intrinsics.
3611unsafe { $min_fn(self.as_ptr(), val, order) }
3612 }
36133614/// Returns a mutable pointer to the underlying integer.
3615 ///
3616 /// Doing non-atomic reads and writes on the resulting integer can be a data race.
3617 /// This method is mostly useful for FFI, where the function signature may use
3618#[doc = concat!("`*mut ", stringify!($int_type), "` instead of `&", stringify!($atomic_type), "`.")]
3619///
3620 /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
3621 /// atomic types work with interior mutability. All modifications of an atomic change the value
3622 /// through a shared reference, and can do so safely as long as they use atomic operations. Any
3623 /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
3624 /// requirements of the [memory model].
3625 ///
3626 /// # Examples
3627 ///
3628 /// ```ignore (extern-declaration)
3629 /// # fn main() {
3630#[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
3631///
3632 /// extern "C" {
3633#[doc = concat!(" fn my_atomic_op(arg: *mut ", stringify!($int_type), ");")]
3634/// }
3635 ///
3636#[doc = concat!("let atomic = ", stringify!($atomic_type), "::new(1);")]
3637///
3638 /// // SAFETY: Safe as long as `my_atomic_op` is atomic.
3639 /// unsafe {
3640 /// my_atomic_op(atomic.as_ptr());
3641 /// }
3642 /// # }
3643 /// ```
3644 ///
3645 /// [memory model]: self#memory-model-for-atomic-accesses
3646#[inline]
3647 #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
3648 #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
3649 #[rustc_never_returns_null_ptr]
3650pub const fn as_ptr(&self) -> *mut $int_type {
3651self.v.get().cast()
3652 }
3653 }
3654 }
3655}
36563657#[cfg(target_has_atomic_load_store = "8")]
3658/// An integer type which can be safely shared between threads.
///
/// This type has the same
#[doc = "size, alignment, and bit validity"]
/// as the underlying integer type, [`
#[doc = "i8"]
/// `].
#[doc = ""]
///
/// For more about the differences between atomic types and
/// non-atomic types as well as information about the portability of
/// this type, please see the [module-level documentation].
///
/// **Note:** This type is only available on platforms that support
/// atomic loads and stores of [`
#[doc = "i8"]
/// `].
///
/// [module-level documentation]: crate::sync::atomic
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub type AtomicI8 = Atomic<i8>;
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl Default for AtomicI8 {
#[inline]
fn default() -> Self { Self::new(Default::default()) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl From<i8> for AtomicI8 {
#[doc = "Converts an `i8` into an `AtomicI8`."]
#[inline]
fn from(v: i8) -> Self { Self::new(v) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl fmt::Debug for AtomicI8 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
}
}
impl AtomicI8 {
/// Creates a new atomic integer.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicI8;"]
///
#[doc = "let atomic_forty_two = AtomicI8::new(42);"]
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0")]
#[must_use]
pub const fn new(v: i8) -> Self { unsafe { transmute(v) } }
/// Creates a new reference to an atomic integer from a pointer.
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{self, AtomicI8};"]
///
/// // Get a pointer to an allocated value
#[doc = "let ptr: *mut i8 = Box::into_raw(Box::new(0));"]
///
#[doc = "assert!(ptr.cast::<AtomicI8>().is_aligned());"]
///
/// {
/// // Create an atomic view of the allocated value
#[doc = " let atomic = unsafe {AtomicI8::from_ptr(ptr) };"]
///
/// // Use `atomic` for atomic operations, possibly share it with other threads
/// atomic.store(1, atomic::Ordering::Relaxed);
/// }
///
/// // It's ok to non-atomically access the value behind `ptr`,
/// // since the reference to the atomic ended its lifetime in the block above
/// assert_eq!(unsafe { *ptr }, 1);
///
/// // Deallocate the value
/// unsafe { drop(Box::from_raw(ptr)) }
/// ```
///
/// # Safety
///
/// * `ptr` must be aligned to
#[doc = " `align_of::<AtomicI8>()`"]
#[doc =
" (note that this is always true, since `align_of::<AtomicI8>() == 1`)."]
/// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
/// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
/// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
/// sizes, without synchronization.
///
/// [valid]: crate::ptr#safety
/// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_from_ptr", since = "1.75.0")]
#[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
pub const unsafe fn from_ptr<'a>(ptr: *mut i8) -> &'a AtomicI8 {
unsafe { &*ptr.cast() }
}
/// Returns a mutable reference to the underlying integer.
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let mut some_var = AtomicI8::new(10);"]
/// assert_eq!(*some_var.get_mut(), 10);
/// *some_var.get_mut() = 5;
/// assert_eq!(some_var.load(Ordering::SeqCst), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn get_mut(&mut self) -> &mut i8 { unsafe { &mut *self.as_ptr() } }
#[doc = "Get atomic access to a `&mut i8`."]
///
#[doc = ""]
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
/// let mut some_int = 123;
#[doc = "let a = AtomicI8::from_mut(&mut some_int);"]
/// a.store(100, Ordering::Relaxed);
/// assert_eq!(some_int, 100);
/// ```
///
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut(v: &mut i8) -> &mut Self {
let [] = [(); align_of::<Self>() - align_of::<i8>()];
unsafe { &mut *(v as *mut i8 as *mut Self) }
}
#[doc = "Get non-atomic access to a `&mut [AtomicI8]` slice"]
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let mut some_ints = [const { AtomicI8::new(0) }; 10];"]
///
#[doc = "let view: &mut [i8] = AtomicI8::get_mut_slice(&mut some_ints);"]
/// assert_eq!(view, [0; 10]);
/// view
/// .iter_mut()
/// .enumerate()
/// .for_each(|(idx, int)| *int = idx as _);
///
/// std::thread::scope(|s| {
/// some_ints
/// .iter()
/// .enumerate()
/// .for_each(|(idx, int)| {
/// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
/// })
/// });
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn get_mut_slice(this: &mut [Self]) -> &mut [i8] {
unsafe { &mut *(this as *mut [Self] as *mut [i8]) }
}
#[doc = "Get atomic access to a `&mut [i8]` slice."]
///
#[doc = ""]
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
/// let mut some_ints = [0; 10];
#[doc = "let a = &*AtomicI8::from_mut_slice(&mut some_ints);"]
/// std::thread::scope(|s| {
/// for i in 0..a.len() {
/// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
/// }
/// });
/// for (i, n) in some_ints.into_iter().enumerate() {
/// assert_eq!(i, n as usize);
/// }
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut_slice(v: &mut [i8]) -> &mut [Self] {
let [] = [(); align_of::<Self>() - align_of::<i8>()];
unsafe { &mut *(v as *mut [i8] as *mut [Self]) }
}
/// Consumes the atomic and returns the contained value.
///
/// This is safe because passing `self` by value guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicI8;"]
///
#[doc = "let some_var = AtomicI8::new(5);"]
/// assert_eq!(some_var.into_inner(), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_atomic_into_inner", since =
"1.79.0")]
pub const fn into_inner(self) -> i8 { unsafe { transmute(self) } }
/// Loads a value from the atomic integer.
///
/// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Release`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let some_var = AtomicI8::new(5);"]
///
/// assert_eq!(some_var.load(Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn load(&self, order: Ordering) -> i8 {
unsafe { atomic_load(self.as_ptr(), order) }
}
/// Stores a value into the atomic integer.
///
/// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Acquire`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let some_var = AtomicI8::new(5);"]
///
/// some_var.store(10, Ordering::Relaxed);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn store(&self, val: i8, order: Ordering) {
unsafe { atomic_store(self.as_ptr(), val, order); }
}
/// Stores a value into the atomic integer, returning the previous value.
///
/// `swap` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let some_var = AtomicI8::new(5);"]
///
/// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn swap(&self, val: i8, order: Ordering) -> i8 {
unsafe { atomic_swap(self.as_ptr(), val, order) }
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is always the previous value. If it is equal to `current`, then the
/// value was updated.
///
/// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
/// ordering of this operation. Notice that even when using [`AcqRel`], the operation
/// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
/// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
/// happens, and using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Migrating to `compare_exchange` and `compare_exchange_weak`
///
/// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
/// memory orderings:
///
/// Original | Success | Failure
/// -------- | ------- | -------
/// Relaxed | Relaxed | Relaxed
/// Acquire | Acquire | Acquire
/// Release | Release | Relaxed
/// AcqRel | AcqRel | Acquire
/// SeqCst | SeqCst | SeqCst
///
/// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
/// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
/// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
/// rather than to infer success vs failure based on the value that was read.
///
/// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
/// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
/// which allows the compiler to generate better assembly code when the compare and swap
/// is used in a loop.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let some_var = AtomicI8::new(5);"]
///
/// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[deprecated(since = "1.50.0", note =
"Use `compare_exchange` or `compare_exchange_weak` instead")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_and_swap(&self, current: i8, new: i8, order: Ordering)
-> i8 {
match self.compare_exchange(current, new, order,
strongest_failure_ordering(order)) {
Ok(x) => x,
Err(x) => x,
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is a result indicating whether the new value was written and
/// containing the previous value. On success this value is guaranteed to be equal to
/// `current`.
///
/// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let some_var = AtomicI8::new(5);"]
///
/// assert_eq!(some_var.compare_exchange(5, 10,
/// Ordering::Acquire,
/// Ordering::Relaxed),
/// Ok(5));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_exchange(6, 12,
/// Ordering::SeqCst,
/// Ordering::Acquire),
/// Err(10));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim! This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange(&self, current: i8, new: i8, success: Ordering,
failure: Ordering) -> Result<i8, i8> {
unsafe {
atomic_compare_exchange(self.as_ptr(), current, new, success,
failure)
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
#[doc = "Unlike [`AtomicI8::compare_exchange`],"]
/// this function is allowed to spuriously fail even
/// when the comparison succeeds, which can result in more efficient code on some
/// platforms. The return value is a result indicating whether the new value was
/// written and containing the previous value.
///
/// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let val = AtomicI8::new(4);"]
///
/// let mut old = val.load(Ordering::Relaxed);
/// loop {
/// let new = old * 2;
/// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
/// Ok(_) => break,
/// Err(x) => old = x,
/// }
/// }
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim. This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange_weak(&self, current: i8, new: i8,
success: Ordering, failure: Ordering) -> Result<i8, i8> {
unsafe {
atomic_compare_exchange_weak(self.as_ptr(), current, new, success,
failure)
}
}
/// Adds to the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let foo = AtomicI8::new(0);"]
/// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_add(&self, val: i8, order: Ordering) -> i8 {
unsafe { atomic_add(self.as_ptr(), val, order) }
}
/// Subtracts from the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let foo = AtomicI8::new(20);"]
/// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_sub(&self, val: i8, order: Ordering) -> i8 {
unsafe { atomic_sub(self.as_ptr(), val, order) }
}
/// Bitwise "and" with the current value.
///
/// Performs a bitwise "and" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let foo = AtomicI8::new(0b101101);"]
/// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_and(&self, val: i8, order: Ordering) -> i8 {
unsafe { atomic_and(self.as_ptr(), val, order) }
}
/// Bitwise "nand" with the current value.
///
/// Performs a bitwise "nand" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let foo = AtomicI8::new(0x13);"]
/// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
/// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_nand(&self, val: i8, order: Ordering) -> i8 {
unsafe { atomic_nand(self.as_ptr(), val, order) }
}
/// Bitwise "or" with the current value.
///
/// Performs a bitwise "or" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let foo = AtomicI8::new(0b101101);"]
/// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_or(&self, val: i8, order: Ordering) -> i8 {
unsafe { atomic_or(self.as_ptr(), val, order) }
}
/// Bitwise "xor" with the current value.
///
/// Performs a bitwise "xor" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let foo = AtomicI8::new(0b101101);"]
/// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_xor(&self, val: i8, order: Ordering) -> i8 {
unsafe { atomic_xor(self.as_ptr(), val, order) }
}
/// An alias for
#[doc = "[`AtomicI8::try_update`]"]
/// .
#[inline]
#[stable(feature = "no_more_cas", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
#[deprecated(since = "1.99.0", note =
"renamed to `try_update` for consistency", suggestion = "try_update")]
pub fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering,
f: F) -> Result<i8, i8> where F: FnMut(i8) -> Option<i8> {
self.try_update(set_order, fetch_order, f)
}
/// Fetches the value, and applies a function to it that returns an optional
/// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
/// `Err(previous_value)`.
///
#[doc = "See also: [`update`](`AtomicI8::update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
/// only once to the stored value.
///
/// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicI8::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Considerations
///
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let x = AtomicI8::new(7);"]
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn try_update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(i8) -> Option<i8>) -> Result<i8, i8> {
let mut prev = self.load(fetch_order);
while let Some(next) = f(prev) {
match self.compare_exchange_weak(prev, next, set_order,
fetch_order) {
x @ Ok(_) => return x,
Err(next_prev) => prev = next_prev,
}
}
Err(prev)
}
/// Fetches the value, applies a function to it that it return a new value.
/// The new value is stored and the old value is returned.
///
#[doc = "See also: [`try_update`](`AtomicI8::try_update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, but the function will have been applied only once to the stored value.
///
/// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicI8::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Considerations
///
/// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let x = AtomicI8::new(7);"]
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(i8) -> i8) -> i8 {
let mut prev = self.load(fetch_order);
loop {
match self.compare_exchange_weak(prev, f(prev), set_order,
fetch_order) {
Ok(x) => break x,
Err(next_prev) => prev = next_prev,
}
}
}
/// Maximum with the current value.
///
/// Finds the maximum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let foo = AtomicI8::new(23);"]
/// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
/// assert_eq!(foo.load(Ordering::SeqCst), 42);
/// ```
///
/// If you want to obtain the maximum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let foo = AtomicI8::new(23);"]
/// let bar = 42;
/// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
/// assert!(max_foo == 42);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_max(&self, val: i8, order: Ordering) -> i8 {
unsafe { atomic_max(self.as_ptr(), val, order) }
}
/// Minimum with the current value.
///
/// Finds the minimum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let foo = AtomicI8::new(23);"]
/// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 23);
/// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 22);
/// ```
///
/// If you want to obtain the minimum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI8, Ordering};"]
///
#[doc = "let foo = AtomicI8::new(23);"]
/// let bar = 12;
/// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
/// assert_eq!(min_foo, 12);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_min(&self, val: i8, order: Ordering) -> i8 {
unsafe { atomic_min(self.as_ptr(), val, order) }
}
/// Returns a mutable pointer to the underlying integer.
///
/// Doing non-atomic reads and writes on the resulting integer can be a data race.
/// This method is mostly useful for FFI, where the function signature may use
#[doc = "`*mut i8` instead of `&AtomicI8`."]
///
/// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
/// atomic types work with interior mutability. All modifications of an atomic change the value
/// through a shared reference, and can do so safely as long as they use atomic operations. Any
/// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
/// requirements of the [memory model].
///
/// # Examples
///
/// ```ignore (extern-declaration)
/// # fn main() {
#[doc = "use std::sync::atomic::AtomicI8;"]
///
/// extern "C" {
#[doc = " fn my_atomic_op(arg: *mut i8);"]
/// }
///
#[doc = "let atomic = AtomicI8::new(1);"]
///
/// // SAFETY: Safe as long as `my_atomic_op` is atomic.
/// unsafe {
/// my_atomic_op(atomic.as_ptr());
/// }
/// # }
/// ```
///
/// [memory model]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_never_returns_null_ptr]
pub const fn as_ptr(&self) -> *mut i8 { self.v.get().cast() }
}atomic_int! {
3659 target_has_atomic_load_store = "8",
3660 target_has_atomic = "8",
3661 target_has_atomic_primitive_alignment = "8",
3662 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3663 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3664 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3665 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3666 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3667 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3668 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3669 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3670"i8",
3671"",
3672 atomic_min, atomic_max,
36731,
3674 i8 AtomicI83675}3676#[cfg(target_has_atomic_load_store = "8")]
3677/// An integer type which can be safely shared between threads.
///
/// This type has the same
#[doc = "size, alignment, and bit validity"]
/// as the underlying integer type, [`
#[doc = "u8"]
/// `].
#[doc = ""]
///
/// For more about the differences between atomic types and
/// non-atomic types as well as information about the portability of
/// this type, please see the [module-level documentation].
///
/// **Note:** This type is only available on platforms that support
/// atomic loads and stores of [`
#[doc = "u8"]
/// `].
///
/// [module-level documentation]: crate::sync::atomic
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub type AtomicU8 = Atomic<u8>;
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl Default for AtomicU8 {
#[inline]
fn default() -> Self { Self::new(Default::default()) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl From<u8> for AtomicU8 {
#[doc = "Converts an `u8` into an `AtomicU8`."]
#[inline]
fn from(v: u8) -> Self { Self::new(v) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl fmt::Debug for AtomicU8 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
}
}
impl AtomicU8 {
/// Creates a new atomic integer.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicU8;"]
///
#[doc = "let atomic_forty_two = AtomicU8::new(42);"]
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0")]
#[must_use]
pub const fn new(v: u8) -> Self { unsafe { transmute(v) } }
/// Creates a new reference to an atomic integer from a pointer.
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{self, AtomicU8};"]
///
/// // Get a pointer to an allocated value
#[doc = "let ptr: *mut u8 = Box::into_raw(Box::new(0));"]
///
#[doc = "assert!(ptr.cast::<AtomicU8>().is_aligned());"]
///
/// {
/// // Create an atomic view of the allocated value
#[doc = " let atomic = unsafe {AtomicU8::from_ptr(ptr) };"]
///
/// // Use `atomic` for atomic operations, possibly share it with other threads
/// atomic.store(1, atomic::Ordering::Relaxed);
/// }
///
/// // It's ok to non-atomically access the value behind `ptr`,
/// // since the reference to the atomic ended its lifetime in the block above
/// assert_eq!(unsafe { *ptr }, 1);
///
/// // Deallocate the value
/// unsafe { drop(Box::from_raw(ptr)) }
/// ```
///
/// # Safety
///
/// * `ptr` must be aligned to
#[doc = " `align_of::<AtomicU8>()`"]
#[doc =
" (note that this is always true, since `align_of::<AtomicU8>() == 1`)."]
/// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
/// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
/// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
/// sizes, without synchronization.
///
/// [valid]: crate::ptr#safety
/// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_from_ptr", since = "1.75.0")]
#[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
pub const unsafe fn from_ptr<'a>(ptr: *mut u8) -> &'a AtomicU8 {
unsafe { &*ptr.cast() }
}
/// Returns a mutable reference to the underlying integer.
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let mut some_var = AtomicU8::new(10);"]
/// assert_eq!(*some_var.get_mut(), 10);
/// *some_var.get_mut() = 5;
/// assert_eq!(some_var.load(Ordering::SeqCst), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn get_mut(&mut self) -> &mut u8 { unsafe { &mut *self.as_ptr() } }
#[doc = "Get atomic access to a `&mut u8`."]
///
#[doc = ""]
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
/// let mut some_int = 123;
#[doc = "let a = AtomicU8::from_mut(&mut some_int);"]
/// a.store(100, Ordering::Relaxed);
/// assert_eq!(some_int, 100);
/// ```
///
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut(v: &mut u8) -> &mut Self {
let [] = [(); align_of::<Self>() - align_of::<u8>()];
unsafe { &mut *(v as *mut u8 as *mut Self) }
}
#[doc = "Get non-atomic access to a `&mut [AtomicU8]` slice"]
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let mut some_ints = [const { AtomicU8::new(0) }; 10];"]
///
#[doc = "let view: &mut [u8] = AtomicU8::get_mut_slice(&mut some_ints);"]
/// assert_eq!(view, [0; 10]);
/// view
/// .iter_mut()
/// .enumerate()
/// .for_each(|(idx, int)| *int = idx as _);
///
/// std::thread::scope(|s| {
/// some_ints
/// .iter()
/// .enumerate()
/// .for_each(|(idx, int)| {
/// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
/// })
/// });
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn get_mut_slice(this: &mut [Self]) -> &mut [u8] {
unsafe { &mut *(this as *mut [Self] as *mut [u8]) }
}
#[doc = "Get atomic access to a `&mut [u8]` slice."]
///
#[doc = ""]
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
/// let mut some_ints = [0; 10];
#[doc = "let a = &*AtomicU8::from_mut_slice(&mut some_ints);"]
/// std::thread::scope(|s| {
/// for i in 0..a.len() {
/// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
/// }
/// });
/// for (i, n) in some_ints.into_iter().enumerate() {
/// assert_eq!(i, n as usize);
/// }
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut_slice(v: &mut [u8]) -> &mut [Self] {
let [] = [(); align_of::<Self>() - align_of::<u8>()];
unsafe { &mut *(v as *mut [u8] as *mut [Self]) }
}
/// Consumes the atomic and returns the contained value.
///
/// This is safe because passing `self` by value guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicU8;"]
///
#[doc = "let some_var = AtomicU8::new(5);"]
/// assert_eq!(some_var.into_inner(), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_atomic_into_inner", since =
"1.79.0")]
pub const fn into_inner(self) -> u8 { unsafe { transmute(self) } }
/// Loads a value from the atomic integer.
///
/// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Release`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let some_var = AtomicU8::new(5);"]
///
/// assert_eq!(some_var.load(Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn load(&self, order: Ordering) -> u8 {
unsafe { atomic_load(self.as_ptr(), order) }
}
/// Stores a value into the atomic integer.
///
/// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Acquire`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let some_var = AtomicU8::new(5);"]
///
/// some_var.store(10, Ordering::Relaxed);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn store(&self, val: u8, order: Ordering) {
unsafe { atomic_store(self.as_ptr(), val, order); }
}
/// Stores a value into the atomic integer, returning the previous value.
///
/// `swap` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let some_var = AtomicU8::new(5);"]
///
/// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn swap(&self, val: u8, order: Ordering) -> u8 {
unsafe { atomic_swap(self.as_ptr(), val, order) }
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is always the previous value. If it is equal to `current`, then the
/// value was updated.
///
/// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
/// ordering of this operation. Notice that even when using [`AcqRel`], the operation
/// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
/// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
/// happens, and using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Migrating to `compare_exchange` and `compare_exchange_weak`
///
/// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
/// memory orderings:
///
/// Original | Success | Failure
/// -------- | ------- | -------
/// Relaxed | Relaxed | Relaxed
/// Acquire | Acquire | Acquire
/// Release | Release | Relaxed
/// AcqRel | AcqRel | Acquire
/// SeqCst | SeqCst | SeqCst
///
/// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
/// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
/// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
/// rather than to infer success vs failure based on the value that was read.
///
/// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
/// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
/// which allows the compiler to generate better assembly code when the compare and swap
/// is used in a loop.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let some_var = AtomicU8::new(5);"]
///
/// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[deprecated(since = "1.50.0", note =
"Use `compare_exchange` or `compare_exchange_weak` instead")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_and_swap(&self, current: u8, new: u8, order: Ordering)
-> u8 {
match self.compare_exchange(current, new, order,
strongest_failure_ordering(order)) {
Ok(x) => x,
Err(x) => x,
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is a result indicating whether the new value was written and
/// containing the previous value. On success this value is guaranteed to be equal to
/// `current`.
///
/// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let some_var = AtomicU8::new(5);"]
///
/// assert_eq!(some_var.compare_exchange(5, 10,
/// Ordering::Acquire,
/// Ordering::Relaxed),
/// Ok(5));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_exchange(6, 12,
/// Ordering::SeqCst,
/// Ordering::Acquire),
/// Err(10));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim! This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange(&self, current: u8, new: u8, success: Ordering,
failure: Ordering) -> Result<u8, u8> {
unsafe {
atomic_compare_exchange(self.as_ptr(), current, new, success,
failure)
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
#[doc = "Unlike [`AtomicU8::compare_exchange`],"]
/// this function is allowed to spuriously fail even
/// when the comparison succeeds, which can result in more efficient code on some
/// platforms. The return value is a result indicating whether the new value was
/// written and containing the previous value.
///
/// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let val = AtomicU8::new(4);"]
///
/// let mut old = val.load(Ordering::Relaxed);
/// loop {
/// let new = old * 2;
/// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
/// Ok(_) => break,
/// Err(x) => old = x,
/// }
/// }
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim. This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange_weak(&self, current: u8, new: u8,
success: Ordering, failure: Ordering) -> Result<u8, u8> {
unsafe {
atomic_compare_exchange_weak(self.as_ptr(), current, new, success,
failure)
}
}
/// Adds to the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let foo = AtomicU8::new(0);"]
/// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_add(&self, val: u8, order: Ordering) -> u8 {
unsafe { atomic_add(self.as_ptr(), val, order) }
}
/// Subtracts from the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let foo = AtomicU8::new(20);"]
/// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_sub(&self, val: u8, order: Ordering) -> u8 {
unsafe { atomic_sub(self.as_ptr(), val, order) }
}
/// Bitwise "and" with the current value.
///
/// Performs a bitwise "and" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let foo = AtomicU8::new(0b101101);"]
/// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_and(&self, val: u8, order: Ordering) -> u8 {
unsafe { atomic_and(self.as_ptr(), val, order) }
}
/// Bitwise "nand" with the current value.
///
/// Performs a bitwise "nand" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let foo = AtomicU8::new(0x13);"]
/// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
/// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_nand(&self, val: u8, order: Ordering) -> u8 {
unsafe { atomic_nand(self.as_ptr(), val, order) }
}
/// Bitwise "or" with the current value.
///
/// Performs a bitwise "or" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let foo = AtomicU8::new(0b101101);"]
/// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_or(&self, val: u8, order: Ordering) -> u8 {
unsafe { atomic_or(self.as_ptr(), val, order) }
}
/// Bitwise "xor" with the current value.
///
/// Performs a bitwise "xor" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let foo = AtomicU8::new(0b101101);"]
/// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_xor(&self, val: u8, order: Ordering) -> u8 {
unsafe { atomic_xor(self.as_ptr(), val, order) }
}
/// An alias for
#[doc = "[`AtomicU8::try_update`]"]
/// .
#[inline]
#[stable(feature = "no_more_cas", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
#[deprecated(since = "1.99.0", note =
"renamed to `try_update` for consistency", suggestion = "try_update")]
pub fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering,
f: F) -> Result<u8, u8> where F: FnMut(u8) -> Option<u8> {
self.try_update(set_order, fetch_order, f)
}
/// Fetches the value, and applies a function to it that returns an optional
/// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
/// `Err(previous_value)`.
///
#[doc = "See also: [`update`](`AtomicU8::update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
/// only once to the stored value.
///
/// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicU8::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Considerations
///
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let x = AtomicU8::new(7);"]
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn try_update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(u8) -> Option<u8>) -> Result<u8, u8> {
let mut prev = self.load(fetch_order);
while let Some(next) = f(prev) {
match self.compare_exchange_weak(prev, next, set_order,
fetch_order) {
x @ Ok(_) => return x,
Err(next_prev) => prev = next_prev,
}
}
Err(prev)
}
/// Fetches the value, applies a function to it that it return a new value.
/// The new value is stored and the old value is returned.
///
#[doc = "See also: [`try_update`](`AtomicU8::try_update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, but the function will have been applied only once to the stored value.
///
/// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicU8::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Considerations
///
/// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let x = AtomicU8::new(7);"]
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(u8) -> u8) -> u8 {
let mut prev = self.load(fetch_order);
loop {
match self.compare_exchange_weak(prev, f(prev), set_order,
fetch_order) {
Ok(x) => break x,
Err(next_prev) => prev = next_prev,
}
}
}
/// Maximum with the current value.
///
/// Finds the maximum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let foo = AtomicU8::new(23);"]
/// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
/// assert_eq!(foo.load(Ordering::SeqCst), 42);
/// ```
///
/// If you want to obtain the maximum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let foo = AtomicU8::new(23);"]
/// let bar = 42;
/// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
/// assert!(max_foo == 42);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_max(&self, val: u8, order: Ordering) -> u8 {
unsafe { atomic_umax(self.as_ptr(), val, order) }
}
/// Minimum with the current value.
///
/// Finds the minimum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u8`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let foo = AtomicU8::new(23);"]
/// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 23);
/// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 22);
/// ```
///
/// If you want to obtain the minimum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU8, Ordering};"]
///
#[doc = "let foo = AtomicU8::new(23);"]
/// let bar = 12;
/// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
/// assert_eq!(min_foo, 12);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_min(&self, val: u8, order: Ordering) -> u8 {
unsafe { atomic_umin(self.as_ptr(), val, order) }
}
/// Returns a mutable pointer to the underlying integer.
///
/// Doing non-atomic reads and writes on the resulting integer can be a data race.
/// This method is mostly useful for FFI, where the function signature may use
#[doc = "`*mut u8` instead of `&AtomicU8`."]
///
/// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
/// atomic types work with interior mutability. All modifications of an atomic change the value
/// through a shared reference, and can do so safely as long as they use atomic operations. Any
/// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
/// requirements of the [memory model].
///
/// # Examples
///
/// ```ignore (extern-declaration)
/// # fn main() {
#[doc = "use std::sync::atomic::AtomicU8;"]
///
/// extern "C" {
#[doc = " fn my_atomic_op(arg: *mut u8);"]
/// }
///
#[doc = "let atomic = AtomicU8::new(1);"]
///
/// // SAFETY: Safe as long as `my_atomic_op` is atomic.
/// unsafe {
/// my_atomic_op(atomic.as_ptr());
/// }
/// # }
/// ```
///
/// [memory model]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_never_returns_null_ptr]
pub const fn as_ptr(&self) -> *mut u8 { self.v.get().cast() }
}atomic_int! {
3678 target_has_atomic_load_store = "8",
3679 target_has_atomic = "8",
3680 target_has_atomic_primitive_alignment = "8",
3681 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3682 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3683 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3684 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3685 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3686 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3687 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3688 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3689"u8",
3690"",
3691 atomic_umin, atomic_umax,
36921,
3693 u8 AtomicU83694}3695#[cfg(target_has_atomic_load_store = "16")]
3696/// An integer type which can be safely shared between threads.
///
/// This type has the same
#[doc = "size and bit validity"]
/// as the underlying integer type, [`
#[doc = "i16"]
/// `].
#[doc =
"However, the alignment of this type is always equal to its size, even on targets where [`i16`] has a lesser alignment."]
///
/// For more about the differences between atomic types and
/// non-atomic types as well as information about the portability of
/// this type, please see the [module-level documentation].
///
/// **Note:** This type is only available on platforms that support
/// atomic loads and stores of [`
#[doc = "i16"]
/// `].
///
/// [module-level documentation]: crate::sync::atomic
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub type AtomicI16 = Atomic<i16>;
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl Default for AtomicI16 {
#[inline]
fn default() -> Self { Self::new(Default::default()) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl From<i16> for AtomicI16 {
#[doc = "Converts an `i16` into an `AtomicI16`."]
#[inline]
fn from(v: i16) -> Self { Self::new(v) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl fmt::Debug for AtomicI16 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
}
}
impl AtomicI16 {
/// Creates a new atomic integer.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicI16;"]
///
#[doc = "let atomic_forty_two = AtomicI16::new(42);"]
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0")]
#[must_use]
pub const fn new(v: i16) -> Self { unsafe { transmute(v) } }
/// Creates a new reference to an atomic integer from a pointer.
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{self, AtomicI16};"]
///
/// // Get a pointer to an allocated value
#[doc = "let ptr: *mut i16 = Box::into_raw(Box::new(0));"]
///
#[doc = "assert!(ptr.cast::<AtomicI16>().is_aligned());"]
///
/// {
/// // Create an atomic view of the allocated value
#[doc = " let atomic = unsafe {AtomicI16::from_ptr(ptr) };"]
///
/// // Use `atomic` for atomic operations, possibly share it with other threads
/// atomic.store(1, atomic::Ordering::Relaxed);
/// }
///
/// // It's ok to non-atomically access the value behind `ptr`,
/// // since the reference to the atomic ended its lifetime in the block above
/// assert_eq!(unsafe { *ptr }, 1);
///
/// // Deallocate the value
/// unsafe { drop(Box::from_raw(ptr)) }
/// ```
///
/// # Safety
///
/// * `ptr` must be aligned to
#[doc = " `align_of::<AtomicI16>()`"]
#[doc =
" (note that on some platforms this can be bigger than `align_of::<i16>()`)."]
/// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
/// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
/// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
/// sizes, without synchronization.
///
/// [valid]: crate::ptr#safety
/// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_from_ptr", since = "1.75.0")]
#[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
pub const unsafe fn from_ptr<'a>(ptr: *mut i16) -> &'a AtomicI16 {
unsafe { &*ptr.cast() }
}
/// Returns a mutable reference to the underlying integer.
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let mut some_var = AtomicI16::new(10);"]
/// assert_eq!(*some_var.get_mut(), 10);
/// *some_var.get_mut() = 5;
/// assert_eq!(some_var.load(Ordering::SeqCst), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn get_mut(&mut self) -> &mut i16 { unsafe { &mut *self.as_ptr() } }
#[doc = "Get atomic access to a `&mut i16`."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicI16` has the same alignment as `i16`."]
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
/// let mut some_int = 123;
#[doc = "let a = AtomicI16::from_mut(&mut some_int);"]
/// a.store(100, Ordering::Relaxed);
/// assert_eq!(some_int, 100);
/// ```
///
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut(v: &mut i16) -> &mut Self {
let [] = [(); align_of::<Self>() - align_of::<i16>()];
unsafe { &mut *(v as *mut i16 as *mut Self) }
}
#[doc = "Get non-atomic access to a `&mut [AtomicI16]` slice"]
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let mut some_ints = [const { AtomicI16::new(0) }; 10];"]
///
#[doc =
"let view: &mut [i16] = AtomicI16::get_mut_slice(&mut some_ints);"]
/// assert_eq!(view, [0; 10]);
/// view
/// .iter_mut()
/// .enumerate()
/// .for_each(|(idx, int)| *int = idx as _);
///
/// std::thread::scope(|s| {
/// some_ints
/// .iter()
/// .enumerate()
/// .for_each(|(idx, int)| {
/// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
/// })
/// });
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn get_mut_slice(this: &mut [Self]) -> &mut [i16] {
unsafe { &mut *(this as *mut [Self] as *mut [i16]) }
}
#[doc = "Get atomic access to a `&mut [i16]` slice."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicI16` has the same alignment as `i16`."]
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
/// let mut some_ints = [0; 10];
#[doc = "let a = &*AtomicI16::from_mut_slice(&mut some_ints);"]
/// std::thread::scope(|s| {
/// for i in 0..a.len() {
/// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
/// }
/// });
/// for (i, n) in some_ints.into_iter().enumerate() {
/// assert_eq!(i, n as usize);
/// }
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut_slice(v: &mut [i16]) -> &mut [Self] {
let [] = [(); align_of::<Self>() - align_of::<i16>()];
unsafe { &mut *(v as *mut [i16] as *mut [Self]) }
}
/// Consumes the atomic and returns the contained value.
///
/// This is safe because passing `self` by value guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicI16;"]
///
#[doc = "let some_var = AtomicI16::new(5);"]
/// assert_eq!(some_var.into_inner(), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_atomic_into_inner", since =
"1.79.0")]
pub const fn into_inner(self) -> i16 { unsafe { transmute(self) } }
/// Loads a value from the atomic integer.
///
/// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Release`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let some_var = AtomicI16::new(5);"]
///
/// assert_eq!(some_var.load(Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn load(&self, order: Ordering) -> i16 {
unsafe { atomic_load(self.as_ptr(), order) }
}
/// Stores a value into the atomic integer.
///
/// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Acquire`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let some_var = AtomicI16::new(5);"]
///
/// some_var.store(10, Ordering::Relaxed);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn store(&self, val: i16, order: Ordering) {
unsafe { atomic_store(self.as_ptr(), val, order); }
}
/// Stores a value into the atomic integer, returning the previous value.
///
/// `swap` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let some_var = AtomicI16::new(5);"]
///
/// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn swap(&self, val: i16, order: Ordering) -> i16 {
unsafe { atomic_swap(self.as_ptr(), val, order) }
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is always the previous value. If it is equal to `current`, then the
/// value was updated.
///
/// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
/// ordering of this operation. Notice that even when using [`AcqRel`], the operation
/// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
/// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
/// happens, and using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Migrating to `compare_exchange` and `compare_exchange_weak`
///
/// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
/// memory orderings:
///
/// Original | Success | Failure
/// -------- | ------- | -------
/// Relaxed | Relaxed | Relaxed
/// Acquire | Acquire | Acquire
/// Release | Release | Relaxed
/// AcqRel | AcqRel | Acquire
/// SeqCst | SeqCst | SeqCst
///
/// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
/// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
/// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
/// rather than to infer success vs failure based on the value that was read.
///
/// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
/// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
/// which allows the compiler to generate better assembly code when the compare and swap
/// is used in a loop.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let some_var = AtomicI16::new(5);"]
///
/// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[deprecated(since = "1.50.0", note =
"Use `compare_exchange` or `compare_exchange_weak` instead")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_and_swap(&self, current: i16, new: i16, order: Ordering)
-> i16 {
match self.compare_exchange(current, new, order,
strongest_failure_ordering(order)) {
Ok(x) => x,
Err(x) => x,
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is a result indicating whether the new value was written and
/// containing the previous value. On success this value is guaranteed to be equal to
/// `current`.
///
/// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let some_var = AtomicI16::new(5);"]
///
/// assert_eq!(some_var.compare_exchange(5, 10,
/// Ordering::Acquire,
/// Ordering::Relaxed),
/// Ok(5));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_exchange(6, 12,
/// Ordering::SeqCst,
/// Ordering::Acquire),
/// Err(10));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim! This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange(&self, current: i16, new: i16, success: Ordering,
failure: Ordering) -> Result<i16, i16> {
unsafe {
atomic_compare_exchange(self.as_ptr(), current, new, success,
failure)
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
#[doc = "Unlike [`AtomicI16::compare_exchange`],"]
/// this function is allowed to spuriously fail even
/// when the comparison succeeds, which can result in more efficient code on some
/// platforms. The return value is a result indicating whether the new value was
/// written and containing the previous value.
///
/// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let val = AtomicI16::new(4);"]
///
/// let mut old = val.load(Ordering::Relaxed);
/// loop {
/// let new = old * 2;
/// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
/// Ok(_) => break,
/// Err(x) => old = x,
/// }
/// }
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim. This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange_weak(&self, current: i16, new: i16,
success: Ordering, failure: Ordering) -> Result<i16, i16> {
unsafe {
atomic_compare_exchange_weak(self.as_ptr(), current, new, success,
failure)
}
}
/// Adds to the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let foo = AtomicI16::new(0);"]
/// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_add(&self, val: i16, order: Ordering) -> i16 {
unsafe { atomic_add(self.as_ptr(), val, order) }
}
/// Subtracts from the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let foo = AtomicI16::new(20);"]
/// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_sub(&self, val: i16, order: Ordering) -> i16 {
unsafe { atomic_sub(self.as_ptr(), val, order) }
}
/// Bitwise "and" with the current value.
///
/// Performs a bitwise "and" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let foo = AtomicI16::new(0b101101);"]
/// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_and(&self, val: i16, order: Ordering) -> i16 {
unsafe { atomic_and(self.as_ptr(), val, order) }
}
/// Bitwise "nand" with the current value.
///
/// Performs a bitwise "nand" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let foo = AtomicI16::new(0x13);"]
/// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
/// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_nand(&self, val: i16, order: Ordering) -> i16 {
unsafe { atomic_nand(self.as_ptr(), val, order) }
}
/// Bitwise "or" with the current value.
///
/// Performs a bitwise "or" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let foo = AtomicI16::new(0b101101);"]
/// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_or(&self, val: i16, order: Ordering) -> i16 {
unsafe { atomic_or(self.as_ptr(), val, order) }
}
/// Bitwise "xor" with the current value.
///
/// Performs a bitwise "xor" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let foo = AtomicI16::new(0b101101);"]
/// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_xor(&self, val: i16, order: Ordering) -> i16 {
unsafe { atomic_xor(self.as_ptr(), val, order) }
}
/// An alias for
#[doc = "[`AtomicI16::try_update`]"]
/// .
#[inline]
#[stable(feature = "no_more_cas", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
#[deprecated(since = "1.99.0", note =
"renamed to `try_update` for consistency", suggestion = "try_update")]
pub fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering,
f: F) -> Result<i16, i16> where F: FnMut(i16) -> Option<i16> {
self.try_update(set_order, fetch_order, f)
}
/// Fetches the value, and applies a function to it that returns an optional
/// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
/// `Err(previous_value)`.
///
#[doc = "See also: [`update`](`AtomicI16::update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
/// only once to the stored value.
///
/// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicI16::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Considerations
///
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let x = AtomicI16::new(7);"]
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn try_update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(i16) -> Option<i16>) -> Result<i16, i16> {
let mut prev = self.load(fetch_order);
while let Some(next) = f(prev) {
match self.compare_exchange_weak(prev, next, set_order,
fetch_order) {
x @ Ok(_) => return x,
Err(next_prev) => prev = next_prev,
}
}
Err(prev)
}
/// Fetches the value, applies a function to it that it return a new value.
/// The new value is stored and the old value is returned.
///
#[doc = "See also: [`try_update`](`AtomicI16::try_update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, but the function will have been applied only once to the stored value.
///
/// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicI16::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Considerations
///
/// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let x = AtomicI16::new(7);"]
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(i16) -> i16) -> i16 {
let mut prev = self.load(fetch_order);
loop {
match self.compare_exchange_weak(prev, f(prev), set_order,
fetch_order) {
Ok(x) => break x,
Err(next_prev) => prev = next_prev,
}
}
}
/// Maximum with the current value.
///
/// Finds the maximum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let foo = AtomicI16::new(23);"]
/// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
/// assert_eq!(foo.load(Ordering::SeqCst), 42);
/// ```
///
/// If you want to obtain the maximum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let foo = AtomicI16::new(23);"]
/// let bar = 42;
/// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
/// assert!(max_foo == 42);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_max(&self, val: i16, order: Ordering) -> i16 {
unsafe { atomic_max(self.as_ptr(), val, order) }
}
/// Minimum with the current value.
///
/// Finds the minimum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let foo = AtomicI16::new(23);"]
/// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 23);
/// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 22);
/// ```
///
/// If you want to obtain the minimum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI16, Ordering};"]
///
#[doc = "let foo = AtomicI16::new(23);"]
/// let bar = 12;
/// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
/// assert_eq!(min_foo, 12);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_min(&self, val: i16, order: Ordering) -> i16 {
unsafe { atomic_min(self.as_ptr(), val, order) }
}
/// Returns a mutable pointer to the underlying integer.
///
/// Doing non-atomic reads and writes on the resulting integer can be a data race.
/// This method is mostly useful for FFI, where the function signature may use
#[doc = "`*mut i16` instead of `&AtomicI16`."]
///
/// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
/// atomic types work with interior mutability. All modifications of an atomic change the value
/// through a shared reference, and can do so safely as long as they use atomic operations. Any
/// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
/// requirements of the [memory model].
///
/// # Examples
///
/// ```ignore (extern-declaration)
/// # fn main() {
#[doc = "use std::sync::atomic::AtomicI16;"]
///
/// extern "C" {
#[doc = " fn my_atomic_op(arg: *mut i16);"]
/// }
///
#[doc = "let atomic = AtomicI16::new(1);"]
///
/// // SAFETY: Safe as long as `my_atomic_op` is atomic.
/// unsafe {
/// my_atomic_op(atomic.as_ptr());
/// }
/// # }
/// ```
///
/// [memory model]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_never_returns_null_ptr]
pub const fn as_ptr(&self) -> *mut i16 { self.v.get().cast() }
}atomic_int! {
3697 target_has_atomic_load_store = "16",
3698 target_has_atomic = "16",
3699 target_has_atomic_primitive_alignment = "16",
3700 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3701 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3702 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3703 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3704 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3705 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3706 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3707 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3708"i16",
3709"",
3710 atomic_min, atomic_max,
37112,
3712 i16 AtomicI163713}3714#[cfg(target_has_atomic_load_store = "16")]
3715/// An integer type which can be safely shared between threads.
///
/// This type has the same
#[doc = "size and bit validity"]
/// as the underlying integer type, [`
#[doc = "u16"]
/// `].
#[doc =
"However, the alignment of this type is always equal to its size, even on targets where [`u16`] has a lesser alignment."]
///
/// For more about the differences between atomic types and
/// non-atomic types as well as information about the portability of
/// this type, please see the [module-level documentation].
///
/// **Note:** This type is only available on platforms that support
/// atomic loads and stores of [`
#[doc = "u16"]
/// `].
///
/// [module-level documentation]: crate::sync::atomic
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub type AtomicU16 = Atomic<u16>;
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl Default for AtomicU16 {
#[inline]
fn default() -> Self { Self::new(Default::default()) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl From<u16> for AtomicU16 {
#[doc = "Converts an `u16` into an `AtomicU16`."]
#[inline]
fn from(v: u16) -> Self { Self::new(v) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl fmt::Debug for AtomicU16 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
}
}
impl AtomicU16 {
/// Creates a new atomic integer.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicU16;"]
///
#[doc = "let atomic_forty_two = AtomicU16::new(42);"]
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0")]
#[must_use]
pub const fn new(v: u16) -> Self { unsafe { transmute(v) } }
/// Creates a new reference to an atomic integer from a pointer.
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{self, AtomicU16};"]
///
/// // Get a pointer to an allocated value
#[doc = "let ptr: *mut u16 = Box::into_raw(Box::new(0));"]
///
#[doc = "assert!(ptr.cast::<AtomicU16>().is_aligned());"]
///
/// {
/// // Create an atomic view of the allocated value
#[doc = " let atomic = unsafe {AtomicU16::from_ptr(ptr) };"]
///
/// // Use `atomic` for atomic operations, possibly share it with other threads
/// atomic.store(1, atomic::Ordering::Relaxed);
/// }
///
/// // It's ok to non-atomically access the value behind `ptr`,
/// // since the reference to the atomic ended its lifetime in the block above
/// assert_eq!(unsafe { *ptr }, 1);
///
/// // Deallocate the value
/// unsafe { drop(Box::from_raw(ptr)) }
/// ```
///
/// # Safety
///
/// * `ptr` must be aligned to
#[doc = " `align_of::<AtomicU16>()`"]
#[doc =
" (note that on some platforms this can be bigger than `align_of::<u16>()`)."]
/// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
/// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
/// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
/// sizes, without synchronization.
///
/// [valid]: crate::ptr#safety
/// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_from_ptr", since = "1.75.0")]
#[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
pub const unsafe fn from_ptr<'a>(ptr: *mut u16) -> &'a AtomicU16 {
unsafe { &*ptr.cast() }
}
/// Returns a mutable reference to the underlying integer.
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let mut some_var = AtomicU16::new(10);"]
/// assert_eq!(*some_var.get_mut(), 10);
/// *some_var.get_mut() = 5;
/// assert_eq!(some_var.load(Ordering::SeqCst), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn get_mut(&mut self) -> &mut u16 { unsafe { &mut *self.as_ptr() } }
#[doc = "Get atomic access to a `&mut u16`."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicU16` has the same alignment as `u16`."]
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
/// let mut some_int = 123;
#[doc = "let a = AtomicU16::from_mut(&mut some_int);"]
/// a.store(100, Ordering::Relaxed);
/// assert_eq!(some_int, 100);
/// ```
///
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut(v: &mut u16) -> &mut Self {
let [] = [(); align_of::<Self>() - align_of::<u16>()];
unsafe { &mut *(v as *mut u16 as *mut Self) }
}
#[doc = "Get non-atomic access to a `&mut [AtomicU16]` slice"]
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let mut some_ints = [const { AtomicU16::new(0) }; 10];"]
///
#[doc =
"let view: &mut [u16] = AtomicU16::get_mut_slice(&mut some_ints);"]
/// assert_eq!(view, [0; 10]);
/// view
/// .iter_mut()
/// .enumerate()
/// .for_each(|(idx, int)| *int = idx as _);
///
/// std::thread::scope(|s| {
/// some_ints
/// .iter()
/// .enumerate()
/// .for_each(|(idx, int)| {
/// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
/// })
/// });
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn get_mut_slice(this: &mut [Self]) -> &mut [u16] {
unsafe { &mut *(this as *mut [Self] as *mut [u16]) }
}
#[doc = "Get atomic access to a `&mut [u16]` slice."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicU16` has the same alignment as `u16`."]
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
/// let mut some_ints = [0; 10];
#[doc = "let a = &*AtomicU16::from_mut_slice(&mut some_ints);"]
/// std::thread::scope(|s| {
/// for i in 0..a.len() {
/// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
/// }
/// });
/// for (i, n) in some_ints.into_iter().enumerate() {
/// assert_eq!(i, n as usize);
/// }
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut_slice(v: &mut [u16]) -> &mut [Self] {
let [] = [(); align_of::<Self>() - align_of::<u16>()];
unsafe { &mut *(v as *mut [u16] as *mut [Self]) }
}
/// Consumes the atomic and returns the contained value.
///
/// This is safe because passing `self` by value guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicU16;"]
///
#[doc = "let some_var = AtomicU16::new(5);"]
/// assert_eq!(some_var.into_inner(), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_atomic_into_inner", since =
"1.79.0")]
pub const fn into_inner(self) -> u16 { unsafe { transmute(self) } }
/// Loads a value from the atomic integer.
///
/// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Release`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let some_var = AtomicU16::new(5);"]
///
/// assert_eq!(some_var.load(Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn load(&self, order: Ordering) -> u16 {
unsafe { atomic_load(self.as_ptr(), order) }
}
/// Stores a value into the atomic integer.
///
/// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Acquire`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let some_var = AtomicU16::new(5);"]
///
/// some_var.store(10, Ordering::Relaxed);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn store(&self, val: u16, order: Ordering) {
unsafe { atomic_store(self.as_ptr(), val, order); }
}
/// Stores a value into the atomic integer, returning the previous value.
///
/// `swap` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let some_var = AtomicU16::new(5);"]
///
/// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn swap(&self, val: u16, order: Ordering) -> u16 {
unsafe { atomic_swap(self.as_ptr(), val, order) }
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is always the previous value. If it is equal to `current`, then the
/// value was updated.
///
/// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
/// ordering of this operation. Notice that even when using [`AcqRel`], the operation
/// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
/// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
/// happens, and using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Migrating to `compare_exchange` and `compare_exchange_weak`
///
/// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
/// memory orderings:
///
/// Original | Success | Failure
/// -------- | ------- | -------
/// Relaxed | Relaxed | Relaxed
/// Acquire | Acquire | Acquire
/// Release | Release | Relaxed
/// AcqRel | AcqRel | Acquire
/// SeqCst | SeqCst | SeqCst
///
/// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
/// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
/// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
/// rather than to infer success vs failure based on the value that was read.
///
/// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
/// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
/// which allows the compiler to generate better assembly code when the compare and swap
/// is used in a loop.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let some_var = AtomicU16::new(5);"]
///
/// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[deprecated(since = "1.50.0", note =
"Use `compare_exchange` or `compare_exchange_weak` instead")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_and_swap(&self, current: u16, new: u16, order: Ordering)
-> u16 {
match self.compare_exchange(current, new, order,
strongest_failure_ordering(order)) {
Ok(x) => x,
Err(x) => x,
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is a result indicating whether the new value was written and
/// containing the previous value. On success this value is guaranteed to be equal to
/// `current`.
///
/// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let some_var = AtomicU16::new(5);"]
///
/// assert_eq!(some_var.compare_exchange(5, 10,
/// Ordering::Acquire,
/// Ordering::Relaxed),
/// Ok(5));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_exchange(6, 12,
/// Ordering::SeqCst,
/// Ordering::Acquire),
/// Err(10));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim! This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange(&self, current: u16, new: u16, success: Ordering,
failure: Ordering) -> Result<u16, u16> {
unsafe {
atomic_compare_exchange(self.as_ptr(), current, new, success,
failure)
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
#[doc = "Unlike [`AtomicU16::compare_exchange`],"]
/// this function is allowed to spuriously fail even
/// when the comparison succeeds, which can result in more efficient code on some
/// platforms. The return value is a result indicating whether the new value was
/// written and containing the previous value.
///
/// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let val = AtomicU16::new(4);"]
///
/// let mut old = val.load(Ordering::Relaxed);
/// loop {
/// let new = old * 2;
/// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
/// Ok(_) => break,
/// Err(x) => old = x,
/// }
/// }
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim. This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange_weak(&self, current: u16, new: u16,
success: Ordering, failure: Ordering) -> Result<u16, u16> {
unsafe {
atomic_compare_exchange_weak(self.as_ptr(), current, new, success,
failure)
}
}
/// Adds to the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let foo = AtomicU16::new(0);"]
/// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_add(&self, val: u16, order: Ordering) -> u16 {
unsafe { atomic_add(self.as_ptr(), val, order) }
}
/// Subtracts from the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let foo = AtomicU16::new(20);"]
/// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_sub(&self, val: u16, order: Ordering) -> u16 {
unsafe { atomic_sub(self.as_ptr(), val, order) }
}
/// Bitwise "and" with the current value.
///
/// Performs a bitwise "and" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let foo = AtomicU16::new(0b101101);"]
/// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_and(&self, val: u16, order: Ordering) -> u16 {
unsafe { atomic_and(self.as_ptr(), val, order) }
}
/// Bitwise "nand" with the current value.
///
/// Performs a bitwise "nand" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let foo = AtomicU16::new(0x13);"]
/// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
/// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_nand(&self, val: u16, order: Ordering) -> u16 {
unsafe { atomic_nand(self.as_ptr(), val, order) }
}
/// Bitwise "or" with the current value.
///
/// Performs a bitwise "or" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let foo = AtomicU16::new(0b101101);"]
/// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_or(&self, val: u16, order: Ordering) -> u16 {
unsafe { atomic_or(self.as_ptr(), val, order) }
}
/// Bitwise "xor" with the current value.
///
/// Performs a bitwise "xor" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let foo = AtomicU16::new(0b101101);"]
/// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_xor(&self, val: u16, order: Ordering) -> u16 {
unsafe { atomic_xor(self.as_ptr(), val, order) }
}
/// An alias for
#[doc = "[`AtomicU16::try_update`]"]
/// .
#[inline]
#[stable(feature = "no_more_cas", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
#[deprecated(since = "1.99.0", note =
"renamed to `try_update` for consistency", suggestion = "try_update")]
pub fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering,
f: F) -> Result<u16, u16> where F: FnMut(u16) -> Option<u16> {
self.try_update(set_order, fetch_order, f)
}
/// Fetches the value, and applies a function to it that returns an optional
/// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
/// `Err(previous_value)`.
///
#[doc = "See also: [`update`](`AtomicU16::update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
/// only once to the stored value.
///
/// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicU16::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Considerations
///
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let x = AtomicU16::new(7);"]
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn try_update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(u16) -> Option<u16>) -> Result<u16, u16> {
let mut prev = self.load(fetch_order);
while let Some(next) = f(prev) {
match self.compare_exchange_weak(prev, next, set_order,
fetch_order) {
x @ Ok(_) => return x,
Err(next_prev) => prev = next_prev,
}
}
Err(prev)
}
/// Fetches the value, applies a function to it that it return a new value.
/// The new value is stored and the old value is returned.
///
#[doc = "See also: [`try_update`](`AtomicU16::try_update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, but the function will have been applied only once to the stored value.
///
/// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicU16::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Considerations
///
/// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let x = AtomicU16::new(7);"]
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(u16) -> u16) -> u16 {
let mut prev = self.load(fetch_order);
loop {
match self.compare_exchange_weak(prev, f(prev), set_order,
fetch_order) {
Ok(x) => break x,
Err(next_prev) => prev = next_prev,
}
}
}
/// Maximum with the current value.
///
/// Finds the maximum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let foo = AtomicU16::new(23);"]
/// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
/// assert_eq!(foo.load(Ordering::SeqCst), 42);
/// ```
///
/// If you want to obtain the maximum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let foo = AtomicU16::new(23);"]
/// let bar = 42;
/// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
/// assert!(max_foo == 42);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_max(&self, val: u16, order: Ordering) -> u16 {
unsafe { atomic_umax(self.as_ptr(), val, order) }
}
/// Minimum with the current value.
///
/// Finds the minimum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u16`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let foo = AtomicU16::new(23);"]
/// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 23);
/// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 22);
/// ```
///
/// If you want to obtain the minimum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU16, Ordering};"]
///
#[doc = "let foo = AtomicU16::new(23);"]
/// let bar = 12;
/// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
/// assert_eq!(min_foo, 12);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_min(&self, val: u16, order: Ordering) -> u16 {
unsafe { atomic_umin(self.as_ptr(), val, order) }
}
/// Returns a mutable pointer to the underlying integer.
///
/// Doing non-atomic reads and writes on the resulting integer can be a data race.
/// This method is mostly useful for FFI, where the function signature may use
#[doc = "`*mut u16` instead of `&AtomicU16`."]
///
/// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
/// atomic types work with interior mutability. All modifications of an atomic change the value
/// through a shared reference, and can do so safely as long as they use atomic operations. Any
/// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
/// requirements of the [memory model].
///
/// # Examples
///
/// ```ignore (extern-declaration)
/// # fn main() {
#[doc = "use std::sync::atomic::AtomicU16;"]
///
/// extern "C" {
#[doc = " fn my_atomic_op(arg: *mut u16);"]
/// }
///
#[doc = "let atomic = AtomicU16::new(1);"]
///
/// // SAFETY: Safe as long as `my_atomic_op` is atomic.
/// unsafe {
/// my_atomic_op(atomic.as_ptr());
/// }
/// # }
/// ```
///
/// [memory model]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_never_returns_null_ptr]
pub const fn as_ptr(&self) -> *mut u16 { self.v.get().cast() }
}atomic_int! {
3716 target_has_atomic_load_store = "16",
3717 target_has_atomic = "16",
3718 target_has_atomic_primitive_alignment = "16",
3719 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3720 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3721 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3722 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3723 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3724 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3725 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3726 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3727"u16",
3728"",
3729 atomic_umin, atomic_umax,
37302,
3731 u16 AtomicU163732}3733#[cfg(target_has_atomic_load_store = "32")]
3734/// An integer type which can be safely shared between threads.
///
/// This type has the same
#[doc = "size and bit validity"]
/// as the underlying integer type, [`
#[doc = "i32"]
/// `].
#[doc =
"However, the alignment of this type is always equal to its size, even on targets where [`i32`] has a lesser alignment."]
///
/// For more about the differences between atomic types and
/// non-atomic types as well as information about the portability of
/// this type, please see the [module-level documentation].
///
/// **Note:** This type is only available on platforms that support
/// atomic loads and stores of [`
#[doc = "i32"]
/// `].
///
/// [module-level documentation]: crate::sync::atomic
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub type AtomicI32 = Atomic<i32>;
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl Default for AtomicI32 {
#[inline]
fn default() -> Self { Self::new(Default::default()) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl From<i32> for AtomicI32 {
#[doc = "Converts an `i32` into an `AtomicI32`."]
#[inline]
fn from(v: i32) -> Self { Self::new(v) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl fmt::Debug for AtomicI32 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
}
}
impl AtomicI32 {
/// Creates a new atomic integer.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicI32;"]
///
#[doc = "let atomic_forty_two = AtomicI32::new(42);"]
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0")]
#[must_use]
pub const fn new(v: i32) -> Self { unsafe { transmute(v) } }
/// Creates a new reference to an atomic integer from a pointer.
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{self, AtomicI32};"]
///
/// // Get a pointer to an allocated value
#[doc = "let ptr: *mut i32 = Box::into_raw(Box::new(0));"]
///
#[doc = "assert!(ptr.cast::<AtomicI32>().is_aligned());"]
///
/// {
/// // Create an atomic view of the allocated value
#[doc = " let atomic = unsafe {AtomicI32::from_ptr(ptr) };"]
///
/// // Use `atomic` for atomic operations, possibly share it with other threads
/// atomic.store(1, atomic::Ordering::Relaxed);
/// }
///
/// // It's ok to non-atomically access the value behind `ptr`,
/// // since the reference to the atomic ended its lifetime in the block above
/// assert_eq!(unsafe { *ptr }, 1);
///
/// // Deallocate the value
/// unsafe { drop(Box::from_raw(ptr)) }
/// ```
///
/// # Safety
///
/// * `ptr` must be aligned to
#[doc = " `align_of::<AtomicI32>()`"]
#[doc =
" (note that on some platforms this can be bigger than `align_of::<i32>()`)."]
/// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
/// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
/// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
/// sizes, without synchronization.
///
/// [valid]: crate::ptr#safety
/// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_from_ptr", since = "1.75.0")]
#[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
pub const unsafe fn from_ptr<'a>(ptr: *mut i32) -> &'a AtomicI32 {
unsafe { &*ptr.cast() }
}
/// Returns a mutable reference to the underlying integer.
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let mut some_var = AtomicI32::new(10);"]
/// assert_eq!(*some_var.get_mut(), 10);
/// *some_var.get_mut() = 5;
/// assert_eq!(some_var.load(Ordering::SeqCst), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn get_mut(&mut self) -> &mut i32 { unsafe { &mut *self.as_ptr() } }
#[doc = "Get atomic access to a `&mut i32`."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicI32` has the same alignment as `i32`."]
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
/// let mut some_int = 123;
#[doc = "let a = AtomicI32::from_mut(&mut some_int);"]
/// a.store(100, Ordering::Relaxed);
/// assert_eq!(some_int, 100);
/// ```
///
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut(v: &mut i32) -> &mut Self {
let [] = [(); align_of::<Self>() - align_of::<i32>()];
unsafe { &mut *(v as *mut i32 as *mut Self) }
}
#[doc = "Get non-atomic access to a `&mut [AtomicI32]` slice"]
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let mut some_ints = [const { AtomicI32::new(0) }; 10];"]
///
#[doc =
"let view: &mut [i32] = AtomicI32::get_mut_slice(&mut some_ints);"]
/// assert_eq!(view, [0; 10]);
/// view
/// .iter_mut()
/// .enumerate()
/// .for_each(|(idx, int)| *int = idx as _);
///
/// std::thread::scope(|s| {
/// some_ints
/// .iter()
/// .enumerate()
/// .for_each(|(idx, int)| {
/// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
/// })
/// });
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn get_mut_slice(this: &mut [Self]) -> &mut [i32] {
unsafe { &mut *(this as *mut [Self] as *mut [i32]) }
}
#[doc = "Get atomic access to a `&mut [i32]` slice."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicI32` has the same alignment as `i32`."]
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
/// let mut some_ints = [0; 10];
#[doc = "let a = &*AtomicI32::from_mut_slice(&mut some_ints);"]
/// std::thread::scope(|s| {
/// for i in 0..a.len() {
/// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
/// }
/// });
/// for (i, n) in some_ints.into_iter().enumerate() {
/// assert_eq!(i, n as usize);
/// }
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut_slice(v: &mut [i32]) -> &mut [Self] {
let [] = [(); align_of::<Self>() - align_of::<i32>()];
unsafe { &mut *(v as *mut [i32] as *mut [Self]) }
}
/// Consumes the atomic and returns the contained value.
///
/// This is safe because passing `self` by value guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicI32;"]
///
#[doc = "let some_var = AtomicI32::new(5);"]
/// assert_eq!(some_var.into_inner(), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_atomic_into_inner", since =
"1.79.0")]
pub const fn into_inner(self) -> i32 { unsafe { transmute(self) } }
/// Loads a value from the atomic integer.
///
/// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Release`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let some_var = AtomicI32::new(5);"]
///
/// assert_eq!(some_var.load(Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn load(&self, order: Ordering) -> i32 {
unsafe { atomic_load(self.as_ptr(), order) }
}
/// Stores a value into the atomic integer.
///
/// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Acquire`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let some_var = AtomicI32::new(5);"]
///
/// some_var.store(10, Ordering::Relaxed);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn store(&self, val: i32, order: Ordering) {
unsafe { atomic_store(self.as_ptr(), val, order); }
}
/// Stores a value into the atomic integer, returning the previous value.
///
/// `swap` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let some_var = AtomicI32::new(5);"]
///
/// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn swap(&self, val: i32, order: Ordering) -> i32 {
unsafe { atomic_swap(self.as_ptr(), val, order) }
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is always the previous value. If it is equal to `current`, then the
/// value was updated.
///
/// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
/// ordering of this operation. Notice that even when using [`AcqRel`], the operation
/// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
/// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
/// happens, and using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Migrating to `compare_exchange` and `compare_exchange_weak`
///
/// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
/// memory orderings:
///
/// Original | Success | Failure
/// -------- | ------- | -------
/// Relaxed | Relaxed | Relaxed
/// Acquire | Acquire | Acquire
/// Release | Release | Relaxed
/// AcqRel | AcqRel | Acquire
/// SeqCst | SeqCst | SeqCst
///
/// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
/// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
/// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
/// rather than to infer success vs failure based on the value that was read.
///
/// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
/// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
/// which allows the compiler to generate better assembly code when the compare and swap
/// is used in a loop.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let some_var = AtomicI32::new(5);"]
///
/// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[deprecated(since = "1.50.0", note =
"Use `compare_exchange` or `compare_exchange_weak` instead")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_and_swap(&self, current: i32, new: i32, order: Ordering)
-> i32 {
match self.compare_exchange(current, new, order,
strongest_failure_ordering(order)) {
Ok(x) => x,
Err(x) => x,
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is a result indicating whether the new value was written and
/// containing the previous value. On success this value is guaranteed to be equal to
/// `current`.
///
/// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let some_var = AtomicI32::new(5);"]
///
/// assert_eq!(some_var.compare_exchange(5, 10,
/// Ordering::Acquire,
/// Ordering::Relaxed),
/// Ok(5));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_exchange(6, 12,
/// Ordering::SeqCst,
/// Ordering::Acquire),
/// Err(10));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim! This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange(&self, current: i32, new: i32, success: Ordering,
failure: Ordering) -> Result<i32, i32> {
unsafe {
atomic_compare_exchange(self.as_ptr(), current, new, success,
failure)
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
#[doc = "Unlike [`AtomicI32::compare_exchange`],"]
/// this function is allowed to spuriously fail even
/// when the comparison succeeds, which can result in more efficient code on some
/// platforms. The return value is a result indicating whether the new value was
/// written and containing the previous value.
///
/// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let val = AtomicI32::new(4);"]
///
/// let mut old = val.load(Ordering::Relaxed);
/// loop {
/// let new = old * 2;
/// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
/// Ok(_) => break,
/// Err(x) => old = x,
/// }
/// }
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim. This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange_weak(&self, current: i32, new: i32,
success: Ordering, failure: Ordering) -> Result<i32, i32> {
unsafe {
atomic_compare_exchange_weak(self.as_ptr(), current, new, success,
failure)
}
}
/// Adds to the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let foo = AtomicI32::new(0);"]
/// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_add(&self, val: i32, order: Ordering) -> i32 {
unsafe { atomic_add(self.as_ptr(), val, order) }
}
/// Subtracts from the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let foo = AtomicI32::new(20);"]
/// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_sub(&self, val: i32, order: Ordering) -> i32 {
unsafe { atomic_sub(self.as_ptr(), val, order) }
}
/// Bitwise "and" with the current value.
///
/// Performs a bitwise "and" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let foo = AtomicI32::new(0b101101);"]
/// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_and(&self, val: i32, order: Ordering) -> i32 {
unsafe { atomic_and(self.as_ptr(), val, order) }
}
/// Bitwise "nand" with the current value.
///
/// Performs a bitwise "nand" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let foo = AtomicI32::new(0x13);"]
/// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
/// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_nand(&self, val: i32, order: Ordering) -> i32 {
unsafe { atomic_nand(self.as_ptr(), val, order) }
}
/// Bitwise "or" with the current value.
///
/// Performs a bitwise "or" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let foo = AtomicI32::new(0b101101);"]
/// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_or(&self, val: i32, order: Ordering) -> i32 {
unsafe { atomic_or(self.as_ptr(), val, order) }
}
/// Bitwise "xor" with the current value.
///
/// Performs a bitwise "xor" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let foo = AtomicI32::new(0b101101);"]
/// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_xor(&self, val: i32, order: Ordering) -> i32 {
unsafe { atomic_xor(self.as_ptr(), val, order) }
}
/// An alias for
#[doc = "[`AtomicI32::try_update`]"]
/// .
#[inline]
#[stable(feature = "no_more_cas", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
#[deprecated(since = "1.99.0", note =
"renamed to `try_update` for consistency", suggestion = "try_update")]
pub fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering,
f: F) -> Result<i32, i32> where F: FnMut(i32) -> Option<i32> {
self.try_update(set_order, fetch_order, f)
}
/// Fetches the value, and applies a function to it that returns an optional
/// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
/// `Err(previous_value)`.
///
#[doc = "See also: [`update`](`AtomicI32::update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
/// only once to the stored value.
///
/// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicI32::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Considerations
///
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let x = AtomicI32::new(7);"]
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn try_update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(i32) -> Option<i32>) -> Result<i32, i32> {
let mut prev = self.load(fetch_order);
while let Some(next) = f(prev) {
match self.compare_exchange_weak(prev, next, set_order,
fetch_order) {
x @ Ok(_) => return x,
Err(next_prev) => prev = next_prev,
}
}
Err(prev)
}
/// Fetches the value, applies a function to it that it return a new value.
/// The new value is stored and the old value is returned.
///
#[doc = "See also: [`try_update`](`AtomicI32::try_update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, but the function will have been applied only once to the stored value.
///
/// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicI32::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Considerations
///
/// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let x = AtomicI32::new(7);"]
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(i32) -> i32) -> i32 {
let mut prev = self.load(fetch_order);
loop {
match self.compare_exchange_weak(prev, f(prev), set_order,
fetch_order) {
Ok(x) => break x,
Err(next_prev) => prev = next_prev,
}
}
}
/// Maximum with the current value.
///
/// Finds the maximum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let foo = AtomicI32::new(23);"]
/// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
/// assert_eq!(foo.load(Ordering::SeqCst), 42);
/// ```
///
/// If you want to obtain the maximum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let foo = AtomicI32::new(23);"]
/// let bar = 42;
/// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
/// assert!(max_foo == 42);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_max(&self, val: i32, order: Ordering) -> i32 {
unsafe { atomic_max(self.as_ptr(), val, order) }
}
/// Minimum with the current value.
///
/// Finds the minimum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let foo = AtomicI32::new(23);"]
/// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 23);
/// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 22);
/// ```
///
/// If you want to obtain the minimum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI32, Ordering};"]
///
#[doc = "let foo = AtomicI32::new(23);"]
/// let bar = 12;
/// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
/// assert_eq!(min_foo, 12);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_min(&self, val: i32, order: Ordering) -> i32 {
unsafe { atomic_min(self.as_ptr(), val, order) }
}
/// Returns a mutable pointer to the underlying integer.
///
/// Doing non-atomic reads and writes on the resulting integer can be a data race.
/// This method is mostly useful for FFI, where the function signature may use
#[doc = "`*mut i32` instead of `&AtomicI32`."]
///
/// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
/// atomic types work with interior mutability. All modifications of an atomic change the value
/// through a shared reference, and can do so safely as long as they use atomic operations. Any
/// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
/// requirements of the [memory model].
///
/// # Examples
///
/// ```ignore (extern-declaration)
/// # fn main() {
#[doc = "use std::sync::atomic::AtomicI32;"]
///
/// extern "C" {
#[doc = " fn my_atomic_op(arg: *mut i32);"]
/// }
///
#[doc = "let atomic = AtomicI32::new(1);"]
///
/// // SAFETY: Safe as long as `my_atomic_op` is atomic.
/// unsafe {
/// my_atomic_op(atomic.as_ptr());
/// }
/// # }
/// ```
///
/// [memory model]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_never_returns_null_ptr]
pub const fn as_ptr(&self) -> *mut i32 { self.v.get().cast() }
}atomic_int! {
3735 target_has_atomic_load_store = "32",
3736 target_has_atomic = "32",
3737 target_has_atomic_primitive_alignment = "32",
3738 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3739 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3740 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3741 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3742 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3743 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3744 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3745 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3746"i32",
3747"",
3748 atomic_min, atomic_max,
37494,
3750 i32 AtomicI323751}3752#[cfg(target_has_atomic_load_store = "32")]
3753/// An integer type which can be safely shared between threads.
///
/// This type has the same
#[doc = "size and bit validity"]
/// as the underlying integer type, [`
#[doc = "u32"]
/// `].
#[doc =
"However, the alignment of this type is always equal to its size, even on targets where [`u32`] has a lesser alignment."]
///
/// For more about the differences between atomic types and
/// non-atomic types as well as information about the portability of
/// this type, please see the [module-level documentation].
///
/// **Note:** This type is only available on platforms that support
/// atomic loads and stores of [`
#[doc = "u32"]
/// `].
///
/// [module-level documentation]: crate::sync::atomic
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub type AtomicU32 = Atomic<u32>;
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl Default for AtomicU32 {
#[inline]
fn default() -> Self { Self::new(Default::default()) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl From<u32> for AtomicU32 {
#[doc = "Converts an `u32` into an `AtomicU32`."]
#[inline]
fn from(v: u32) -> Self { Self::new(v) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl fmt::Debug for AtomicU32 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
}
}
impl AtomicU32 {
/// Creates a new atomic integer.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicU32;"]
///
#[doc = "let atomic_forty_two = AtomicU32::new(42);"]
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0")]
#[must_use]
pub const fn new(v: u32) -> Self { unsafe { transmute(v) } }
/// Creates a new reference to an atomic integer from a pointer.
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{self, AtomicU32};"]
///
/// // Get a pointer to an allocated value
#[doc = "let ptr: *mut u32 = Box::into_raw(Box::new(0));"]
///
#[doc = "assert!(ptr.cast::<AtomicU32>().is_aligned());"]
///
/// {
/// // Create an atomic view of the allocated value
#[doc = " let atomic = unsafe {AtomicU32::from_ptr(ptr) };"]
///
/// // Use `atomic` for atomic operations, possibly share it with other threads
/// atomic.store(1, atomic::Ordering::Relaxed);
/// }
///
/// // It's ok to non-atomically access the value behind `ptr`,
/// // since the reference to the atomic ended its lifetime in the block above
/// assert_eq!(unsafe { *ptr }, 1);
///
/// // Deallocate the value
/// unsafe { drop(Box::from_raw(ptr)) }
/// ```
///
/// # Safety
///
/// * `ptr` must be aligned to
#[doc = " `align_of::<AtomicU32>()`"]
#[doc =
" (note that on some platforms this can be bigger than `align_of::<u32>()`)."]
/// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
/// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
/// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
/// sizes, without synchronization.
///
/// [valid]: crate::ptr#safety
/// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_from_ptr", since = "1.75.0")]
#[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
pub const unsafe fn from_ptr<'a>(ptr: *mut u32) -> &'a AtomicU32 {
unsafe { &*ptr.cast() }
}
/// Returns a mutable reference to the underlying integer.
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let mut some_var = AtomicU32::new(10);"]
/// assert_eq!(*some_var.get_mut(), 10);
/// *some_var.get_mut() = 5;
/// assert_eq!(some_var.load(Ordering::SeqCst), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn get_mut(&mut self) -> &mut u32 { unsafe { &mut *self.as_ptr() } }
#[doc = "Get atomic access to a `&mut u32`."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicU32` has the same alignment as `u32`."]
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
/// let mut some_int = 123;
#[doc = "let a = AtomicU32::from_mut(&mut some_int);"]
/// a.store(100, Ordering::Relaxed);
/// assert_eq!(some_int, 100);
/// ```
///
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut(v: &mut u32) -> &mut Self {
let [] = [(); align_of::<Self>() - align_of::<u32>()];
unsafe { &mut *(v as *mut u32 as *mut Self) }
}
#[doc = "Get non-atomic access to a `&mut [AtomicU32]` slice"]
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let mut some_ints = [const { AtomicU32::new(0) }; 10];"]
///
#[doc =
"let view: &mut [u32] = AtomicU32::get_mut_slice(&mut some_ints);"]
/// assert_eq!(view, [0; 10]);
/// view
/// .iter_mut()
/// .enumerate()
/// .for_each(|(idx, int)| *int = idx as _);
///
/// std::thread::scope(|s| {
/// some_ints
/// .iter()
/// .enumerate()
/// .for_each(|(idx, int)| {
/// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
/// })
/// });
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn get_mut_slice(this: &mut [Self]) -> &mut [u32] {
unsafe { &mut *(this as *mut [Self] as *mut [u32]) }
}
#[doc = "Get atomic access to a `&mut [u32]` slice."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicU32` has the same alignment as `u32`."]
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
/// let mut some_ints = [0; 10];
#[doc = "let a = &*AtomicU32::from_mut_slice(&mut some_ints);"]
/// std::thread::scope(|s| {
/// for i in 0..a.len() {
/// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
/// }
/// });
/// for (i, n) in some_ints.into_iter().enumerate() {
/// assert_eq!(i, n as usize);
/// }
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut_slice(v: &mut [u32]) -> &mut [Self] {
let [] = [(); align_of::<Self>() - align_of::<u32>()];
unsafe { &mut *(v as *mut [u32] as *mut [Self]) }
}
/// Consumes the atomic and returns the contained value.
///
/// This is safe because passing `self` by value guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicU32;"]
///
#[doc = "let some_var = AtomicU32::new(5);"]
/// assert_eq!(some_var.into_inner(), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_atomic_into_inner", since =
"1.79.0")]
pub const fn into_inner(self) -> u32 { unsafe { transmute(self) } }
/// Loads a value from the atomic integer.
///
/// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Release`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let some_var = AtomicU32::new(5);"]
///
/// assert_eq!(some_var.load(Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn load(&self, order: Ordering) -> u32 {
unsafe { atomic_load(self.as_ptr(), order) }
}
/// Stores a value into the atomic integer.
///
/// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Acquire`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let some_var = AtomicU32::new(5);"]
///
/// some_var.store(10, Ordering::Relaxed);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn store(&self, val: u32, order: Ordering) {
unsafe { atomic_store(self.as_ptr(), val, order); }
}
/// Stores a value into the atomic integer, returning the previous value.
///
/// `swap` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let some_var = AtomicU32::new(5);"]
///
/// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn swap(&self, val: u32, order: Ordering) -> u32 {
unsafe { atomic_swap(self.as_ptr(), val, order) }
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is always the previous value. If it is equal to `current`, then the
/// value was updated.
///
/// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
/// ordering of this operation. Notice that even when using [`AcqRel`], the operation
/// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
/// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
/// happens, and using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Migrating to `compare_exchange` and `compare_exchange_weak`
///
/// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
/// memory orderings:
///
/// Original | Success | Failure
/// -------- | ------- | -------
/// Relaxed | Relaxed | Relaxed
/// Acquire | Acquire | Acquire
/// Release | Release | Relaxed
/// AcqRel | AcqRel | Acquire
/// SeqCst | SeqCst | SeqCst
///
/// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
/// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
/// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
/// rather than to infer success vs failure based on the value that was read.
///
/// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
/// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
/// which allows the compiler to generate better assembly code when the compare and swap
/// is used in a loop.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let some_var = AtomicU32::new(5);"]
///
/// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[deprecated(since = "1.50.0", note =
"Use `compare_exchange` or `compare_exchange_weak` instead")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_and_swap(&self, current: u32, new: u32, order: Ordering)
-> u32 {
match self.compare_exchange(current, new, order,
strongest_failure_ordering(order)) {
Ok(x) => x,
Err(x) => x,
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is a result indicating whether the new value was written and
/// containing the previous value. On success this value is guaranteed to be equal to
/// `current`.
///
/// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let some_var = AtomicU32::new(5);"]
///
/// assert_eq!(some_var.compare_exchange(5, 10,
/// Ordering::Acquire,
/// Ordering::Relaxed),
/// Ok(5));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_exchange(6, 12,
/// Ordering::SeqCst,
/// Ordering::Acquire),
/// Err(10));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim! This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange(&self, current: u32, new: u32, success: Ordering,
failure: Ordering) -> Result<u32, u32> {
unsafe {
atomic_compare_exchange(self.as_ptr(), current, new, success,
failure)
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
#[doc = "Unlike [`AtomicU32::compare_exchange`],"]
/// this function is allowed to spuriously fail even
/// when the comparison succeeds, which can result in more efficient code on some
/// platforms. The return value is a result indicating whether the new value was
/// written and containing the previous value.
///
/// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let val = AtomicU32::new(4);"]
///
/// let mut old = val.load(Ordering::Relaxed);
/// loop {
/// let new = old * 2;
/// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
/// Ok(_) => break,
/// Err(x) => old = x,
/// }
/// }
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim. This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange_weak(&self, current: u32, new: u32,
success: Ordering, failure: Ordering) -> Result<u32, u32> {
unsafe {
atomic_compare_exchange_weak(self.as_ptr(), current, new, success,
failure)
}
}
/// Adds to the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let foo = AtomicU32::new(0);"]
/// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_add(&self, val: u32, order: Ordering) -> u32 {
unsafe { atomic_add(self.as_ptr(), val, order) }
}
/// Subtracts from the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let foo = AtomicU32::new(20);"]
/// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_sub(&self, val: u32, order: Ordering) -> u32 {
unsafe { atomic_sub(self.as_ptr(), val, order) }
}
/// Bitwise "and" with the current value.
///
/// Performs a bitwise "and" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let foo = AtomicU32::new(0b101101);"]
/// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_and(&self, val: u32, order: Ordering) -> u32 {
unsafe { atomic_and(self.as_ptr(), val, order) }
}
/// Bitwise "nand" with the current value.
///
/// Performs a bitwise "nand" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let foo = AtomicU32::new(0x13);"]
/// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
/// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_nand(&self, val: u32, order: Ordering) -> u32 {
unsafe { atomic_nand(self.as_ptr(), val, order) }
}
/// Bitwise "or" with the current value.
///
/// Performs a bitwise "or" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let foo = AtomicU32::new(0b101101);"]
/// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_or(&self, val: u32, order: Ordering) -> u32 {
unsafe { atomic_or(self.as_ptr(), val, order) }
}
/// Bitwise "xor" with the current value.
///
/// Performs a bitwise "xor" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let foo = AtomicU32::new(0b101101);"]
/// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_xor(&self, val: u32, order: Ordering) -> u32 {
unsafe { atomic_xor(self.as_ptr(), val, order) }
}
/// An alias for
#[doc = "[`AtomicU32::try_update`]"]
/// .
#[inline]
#[stable(feature = "no_more_cas", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
#[deprecated(since = "1.99.0", note =
"renamed to `try_update` for consistency", suggestion = "try_update")]
pub fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering,
f: F) -> Result<u32, u32> where F: FnMut(u32) -> Option<u32> {
self.try_update(set_order, fetch_order, f)
}
/// Fetches the value, and applies a function to it that returns an optional
/// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
/// `Err(previous_value)`.
///
#[doc = "See also: [`update`](`AtomicU32::update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
/// only once to the stored value.
///
/// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicU32::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Considerations
///
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let x = AtomicU32::new(7);"]
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn try_update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(u32) -> Option<u32>) -> Result<u32, u32> {
let mut prev = self.load(fetch_order);
while let Some(next) = f(prev) {
match self.compare_exchange_weak(prev, next, set_order,
fetch_order) {
x @ Ok(_) => return x,
Err(next_prev) => prev = next_prev,
}
}
Err(prev)
}
/// Fetches the value, applies a function to it that it return a new value.
/// The new value is stored and the old value is returned.
///
#[doc = "See also: [`try_update`](`AtomicU32::try_update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, but the function will have been applied only once to the stored value.
///
/// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicU32::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Considerations
///
/// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let x = AtomicU32::new(7);"]
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(u32) -> u32) -> u32 {
let mut prev = self.load(fetch_order);
loop {
match self.compare_exchange_weak(prev, f(prev), set_order,
fetch_order) {
Ok(x) => break x,
Err(next_prev) => prev = next_prev,
}
}
}
/// Maximum with the current value.
///
/// Finds the maximum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let foo = AtomicU32::new(23);"]
/// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
/// assert_eq!(foo.load(Ordering::SeqCst), 42);
/// ```
///
/// If you want to obtain the maximum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let foo = AtomicU32::new(23);"]
/// let bar = 42;
/// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
/// assert!(max_foo == 42);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_max(&self, val: u32, order: Ordering) -> u32 {
unsafe { atomic_umax(self.as_ptr(), val, order) }
}
/// Minimum with the current value.
///
/// Finds the minimum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u32`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let foo = AtomicU32::new(23);"]
/// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 23);
/// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 22);
/// ```
///
/// If you want to obtain the minimum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU32, Ordering};"]
///
#[doc = "let foo = AtomicU32::new(23);"]
/// let bar = 12;
/// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
/// assert_eq!(min_foo, 12);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_min(&self, val: u32, order: Ordering) -> u32 {
unsafe { atomic_umin(self.as_ptr(), val, order) }
}
/// Returns a mutable pointer to the underlying integer.
///
/// Doing non-atomic reads and writes on the resulting integer can be a data race.
/// This method is mostly useful for FFI, where the function signature may use
#[doc = "`*mut u32` instead of `&AtomicU32`."]
///
/// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
/// atomic types work with interior mutability. All modifications of an atomic change the value
/// through a shared reference, and can do so safely as long as they use atomic operations. Any
/// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
/// requirements of the [memory model].
///
/// # Examples
///
/// ```ignore (extern-declaration)
/// # fn main() {
#[doc = "use std::sync::atomic::AtomicU32;"]
///
/// extern "C" {
#[doc = " fn my_atomic_op(arg: *mut u32);"]
/// }
///
#[doc = "let atomic = AtomicU32::new(1);"]
///
/// // SAFETY: Safe as long as `my_atomic_op` is atomic.
/// unsafe {
/// my_atomic_op(atomic.as_ptr());
/// }
/// # }
/// ```
///
/// [memory model]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_never_returns_null_ptr]
pub const fn as_ptr(&self) -> *mut u32 { self.v.get().cast() }
}atomic_int! {
3754 target_has_atomic_load_store = "32",
3755 target_has_atomic = "32",
3756 target_has_atomic_primitive_alignment = "32",
3757 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3758 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3759 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3760 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3761 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3762 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3763 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3764 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3765"u32",
3766"",
3767 atomic_umin, atomic_umax,
37684,
3769 u32 AtomicU323770}3771#[cfg(target_has_atomic_load_store = "64")]
3772/// An integer type which can be safely shared between threads.
///
/// This type has the same
#[doc = "size and bit validity"]
/// as the underlying integer type, [`
#[doc = "i64"]
/// `].
#[doc =
"However, the alignment of this type is always equal to its size, even on targets where [`i64`] has a lesser alignment."]
///
/// For more about the differences between atomic types and
/// non-atomic types as well as information about the portability of
/// this type, please see the [module-level documentation].
///
/// **Note:** This type is only available on platforms that support
/// atomic loads and stores of [`
#[doc = "i64"]
/// `].
///
/// [module-level documentation]: crate::sync::atomic
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub type AtomicI64 = Atomic<i64>;
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl Default for AtomicI64 {
#[inline]
fn default() -> Self { Self::new(Default::default()) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl From<i64> for AtomicI64 {
#[doc = "Converts an `i64` into an `AtomicI64`."]
#[inline]
fn from(v: i64) -> Self { Self::new(v) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl fmt::Debug for AtomicI64 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
}
}
impl AtomicI64 {
/// Creates a new atomic integer.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicI64;"]
///
#[doc = "let atomic_forty_two = AtomicI64::new(42);"]
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0")]
#[must_use]
pub const fn new(v: i64) -> Self { unsafe { transmute(v) } }
/// Creates a new reference to an atomic integer from a pointer.
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{self, AtomicI64};"]
///
/// // Get a pointer to an allocated value
#[doc = "let ptr: *mut i64 = Box::into_raw(Box::new(0));"]
///
#[doc = "assert!(ptr.cast::<AtomicI64>().is_aligned());"]
///
/// {
/// // Create an atomic view of the allocated value
#[doc = " let atomic = unsafe {AtomicI64::from_ptr(ptr) };"]
///
/// // Use `atomic` for atomic operations, possibly share it with other threads
/// atomic.store(1, atomic::Ordering::Relaxed);
/// }
///
/// // It's ok to non-atomically access the value behind `ptr`,
/// // since the reference to the atomic ended its lifetime in the block above
/// assert_eq!(unsafe { *ptr }, 1);
///
/// // Deallocate the value
/// unsafe { drop(Box::from_raw(ptr)) }
/// ```
///
/// # Safety
///
/// * `ptr` must be aligned to
#[doc = " `align_of::<AtomicI64>()`"]
#[doc =
" (note that on some platforms this can be bigger than `align_of::<i64>()`)."]
/// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
/// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
/// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
/// sizes, without synchronization.
///
/// [valid]: crate::ptr#safety
/// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_from_ptr", since = "1.75.0")]
#[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
pub const unsafe fn from_ptr<'a>(ptr: *mut i64) -> &'a AtomicI64 {
unsafe { &*ptr.cast() }
}
/// Returns a mutable reference to the underlying integer.
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let mut some_var = AtomicI64::new(10);"]
/// assert_eq!(*some_var.get_mut(), 10);
/// *some_var.get_mut() = 5;
/// assert_eq!(some_var.load(Ordering::SeqCst), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn get_mut(&mut self) -> &mut i64 { unsafe { &mut *self.as_ptr() } }
#[doc = "Get atomic access to a `&mut i64`."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicI64` has the same alignment as `i64`."]
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
/// let mut some_int = 123;
#[doc = "let a = AtomicI64::from_mut(&mut some_int);"]
/// a.store(100, Ordering::Relaxed);
/// assert_eq!(some_int, 100);
/// ```
///
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut(v: &mut i64) -> &mut Self {
let [] = [(); align_of::<Self>() - align_of::<i64>()];
unsafe { &mut *(v as *mut i64 as *mut Self) }
}
#[doc = "Get non-atomic access to a `&mut [AtomicI64]` slice"]
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let mut some_ints = [const { AtomicI64::new(0) }; 10];"]
///
#[doc =
"let view: &mut [i64] = AtomicI64::get_mut_slice(&mut some_ints);"]
/// assert_eq!(view, [0; 10]);
/// view
/// .iter_mut()
/// .enumerate()
/// .for_each(|(idx, int)| *int = idx as _);
///
/// std::thread::scope(|s| {
/// some_ints
/// .iter()
/// .enumerate()
/// .for_each(|(idx, int)| {
/// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
/// })
/// });
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn get_mut_slice(this: &mut [Self]) -> &mut [i64] {
unsafe { &mut *(this as *mut [Self] as *mut [i64]) }
}
#[doc = "Get atomic access to a `&mut [i64]` slice."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicI64` has the same alignment as `i64`."]
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
/// let mut some_ints = [0; 10];
#[doc = "let a = &*AtomicI64::from_mut_slice(&mut some_ints);"]
/// std::thread::scope(|s| {
/// for i in 0..a.len() {
/// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
/// }
/// });
/// for (i, n) in some_ints.into_iter().enumerate() {
/// assert_eq!(i, n as usize);
/// }
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut_slice(v: &mut [i64]) -> &mut [Self] {
let [] = [(); align_of::<Self>() - align_of::<i64>()];
unsafe { &mut *(v as *mut [i64] as *mut [Self]) }
}
/// Consumes the atomic and returns the contained value.
///
/// This is safe because passing `self` by value guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicI64;"]
///
#[doc = "let some_var = AtomicI64::new(5);"]
/// assert_eq!(some_var.into_inner(), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_atomic_into_inner", since =
"1.79.0")]
pub const fn into_inner(self) -> i64 { unsafe { transmute(self) } }
/// Loads a value from the atomic integer.
///
/// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Release`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let some_var = AtomicI64::new(5);"]
///
/// assert_eq!(some_var.load(Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn load(&self, order: Ordering) -> i64 {
unsafe { atomic_load(self.as_ptr(), order) }
}
/// Stores a value into the atomic integer.
///
/// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Acquire`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let some_var = AtomicI64::new(5);"]
///
/// some_var.store(10, Ordering::Relaxed);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn store(&self, val: i64, order: Ordering) {
unsafe { atomic_store(self.as_ptr(), val, order); }
}
/// Stores a value into the atomic integer, returning the previous value.
///
/// `swap` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let some_var = AtomicI64::new(5);"]
///
/// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn swap(&self, val: i64, order: Ordering) -> i64 {
unsafe { atomic_swap(self.as_ptr(), val, order) }
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is always the previous value. If it is equal to `current`, then the
/// value was updated.
///
/// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
/// ordering of this operation. Notice that even when using [`AcqRel`], the operation
/// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
/// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
/// happens, and using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Migrating to `compare_exchange` and `compare_exchange_weak`
///
/// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
/// memory orderings:
///
/// Original | Success | Failure
/// -------- | ------- | -------
/// Relaxed | Relaxed | Relaxed
/// Acquire | Acquire | Acquire
/// Release | Release | Relaxed
/// AcqRel | AcqRel | Acquire
/// SeqCst | SeqCst | SeqCst
///
/// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
/// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
/// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
/// rather than to infer success vs failure based on the value that was read.
///
/// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
/// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
/// which allows the compiler to generate better assembly code when the compare and swap
/// is used in a loop.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let some_var = AtomicI64::new(5);"]
///
/// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[deprecated(since = "1.50.0", note =
"Use `compare_exchange` or `compare_exchange_weak` instead")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_and_swap(&self, current: i64, new: i64, order: Ordering)
-> i64 {
match self.compare_exchange(current, new, order,
strongest_failure_ordering(order)) {
Ok(x) => x,
Err(x) => x,
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is a result indicating whether the new value was written and
/// containing the previous value. On success this value is guaranteed to be equal to
/// `current`.
///
/// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let some_var = AtomicI64::new(5);"]
///
/// assert_eq!(some_var.compare_exchange(5, 10,
/// Ordering::Acquire,
/// Ordering::Relaxed),
/// Ok(5));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_exchange(6, 12,
/// Ordering::SeqCst,
/// Ordering::Acquire),
/// Err(10));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim! This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange(&self, current: i64, new: i64, success: Ordering,
failure: Ordering) -> Result<i64, i64> {
unsafe {
atomic_compare_exchange(self.as_ptr(), current, new, success,
failure)
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
#[doc = "Unlike [`AtomicI64::compare_exchange`],"]
/// this function is allowed to spuriously fail even
/// when the comparison succeeds, which can result in more efficient code on some
/// platforms. The return value is a result indicating whether the new value was
/// written and containing the previous value.
///
/// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let val = AtomicI64::new(4);"]
///
/// let mut old = val.load(Ordering::Relaxed);
/// loop {
/// let new = old * 2;
/// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
/// Ok(_) => break,
/// Err(x) => old = x,
/// }
/// }
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim. This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange_weak(&self, current: i64, new: i64,
success: Ordering, failure: Ordering) -> Result<i64, i64> {
unsafe {
atomic_compare_exchange_weak(self.as_ptr(), current, new, success,
failure)
}
}
/// Adds to the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let foo = AtomicI64::new(0);"]
/// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_add(&self, val: i64, order: Ordering) -> i64 {
unsafe { atomic_add(self.as_ptr(), val, order) }
}
/// Subtracts from the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let foo = AtomicI64::new(20);"]
/// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_sub(&self, val: i64, order: Ordering) -> i64 {
unsafe { atomic_sub(self.as_ptr(), val, order) }
}
/// Bitwise "and" with the current value.
///
/// Performs a bitwise "and" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let foo = AtomicI64::new(0b101101);"]
/// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_and(&self, val: i64, order: Ordering) -> i64 {
unsafe { atomic_and(self.as_ptr(), val, order) }
}
/// Bitwise "nand" with the current value.
///
/// Performs a bitwise "nand" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let foo = AtomicI64::new(0x13);"]
/// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
/// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_nand(&self, val: i64, order: Ordering) -> i64 {
unsafe { atomic_nand(self.as_ptr(), val, order) }
}
/// Bitwise "or" with the current value.
///
/// Performs a bitwise "or" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let foo = AtomicI64::new(0b101101);"]
/// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_or(&self, val: i64, order: Ordering) -> i64 {
unsafe { atomic_or(self.as_ptr(), val, order) }
}
/// Bitwise "xor" with the current value.
///
/// Performs a bitwise "xor" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let foo = AtomicI64::new(0b101101);"]
/// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_xor(&self, val: i64, order: Ordering) -> i64 {
unsafe { atomic_xor(self.as_ptr(), val, order) }
}
/// An alias for
#[doc = "[`AtomicI64::try_update`]"]
/// .
#[inline]
#[stable(feature = "no_more_cas", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
#[deprecated(since = "1.99.0", note =
"renamed to `try_update` for consistency", suggestion = "try_update")]
pub fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering,
f: F) -> Result<i64, i64> where F: FnMut(i64) -> Option<i64> {
self.try_update(set_order, fetch_order, f)
}
/// Fetches the value, and applies a function to it that returns an optional
/// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
/// `Err(previous_value)`.
///
#[doc = "See also: [`update`](`AtomicI64::update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
/// only once to the stored value.
///
/// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicI64::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Considerations
///
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let x = AtomicI64::new(7);"]
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn try_update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(i64) -> Option<i64>) -> Result<i64, i64> {
let mut prev = self.load(fetch_order);
while let Some(next) = f(prev) {
match self.compare_exchange_weak(prev, next, set_order,
fetch_order) {
x @ Ok(_) => return x,
Err(next_prev) => prev = next_prev,
}
}
Err(prev)
}
/// Fetches the value, applies a function to it that it return a new value.
/// The new value is stored and the old value is returned.
///
#[doc = "See also: [`try_update`](`AtomicI64::try_update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, but the function will have been applied only once to the stored value.
///
/// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicI64::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Considerations
///
/// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let x = AtomicI64::new(7);"]
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(i64) -> i64) -> i64 {
let mut prev = self.load(fetch_order);
loop {
match self.compare_exchange_weak(prev, f(prev), set_order,
fetch_order) {
Ok(x) => break x,
Err(next_prev) => prev = next_prev,
}
}
}
/// Maximum with the current value.
///
/// Finds the maximum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let foo = AtomicI64::new(23);"]
/// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
/// assert_eq!(foo.load(Ordering::SeqCst), 42);
/// ```
///
/// If you want to obtain the maximum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let foo = AtomicI64::new(23);"]
/// let bar = 42;
/// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
/// assert!(max_foo == 42);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_max(&self, val: i64, order: Ordering) -> i64 {
unsafe { atomic_max(self.as_ptr(), val, order) }
}
/// Minimum with the current value.
///
/// Finds the minimum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`i64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let foo = AtomicI64::new(23);"]
/// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 23);
/// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 22);
/// ```
///
/// If you want to obtain the minimum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicI64, Ordering};"]
///
#[doc = "let foo = AtomicI64::new(23);"]
/// let bar = 12;
/// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
/// assert_eq!(min_foo, 12);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_min(&self, val: i64, order: Ordering) -> i64 {
unsafe { atomic_min(self.as_ptr(), val, order) }
}
/// Returns a mutable pointer to the underlying integer.
///
/// Doing non-atomic reads and writes on the resulting integer can be a data race.
/// This method is mostly useful for FFI, where the function signature may use
#[doc = "`*mut i64` instead of `&AtomicI64`."]
///
/// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
/// atomic types work with interior mutability. All modifications of an atomic change the value
/// through a shared reference, and can do so safely as long as they use atomic operations. Any
/// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
/// requirements of the [memory model].
///
/// # Examples
///
/// ```ignore (extern-declaration)
/// # fn main() {
#[doc = "use std::sync::atomic::AtomicI64;"]
///
/// extern "C" {
#[doc = " fn my_atomic_op(arg: *mut i64);"]
/// }
///
#[doc = "let atomic = AtomicI64::new(1);"]
///
/// // SAFETY: Safe as long as `my_atomic_op` is atomic.
/// unsafe {
/// my_atomic_op(atomic.as_ptr());
/// }
/// # }
/// ```
///
/// [memory model]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_never_returns_null_ptr]
pub const fn as_ptr(&self) -> *mut i64 { self.v.get().cast() }
}atomic_int! {
3773 target_has_atomic_load_store = "64",
3774 target_has_atomic = "64",
3775 target_has_atomic_primitive_alignment = "64",
3776 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3777 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3778 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3779 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3780 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3781 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3782 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3783 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3784"i64",
3785"",
3786 atomic_min, atomic_max,
37878,
3788 i64 AtomicI643789}3790#[cfg(target_has_atomic_load_store = "64")]
3791/// An integer type which can be safely shared between threads.
///
/// This type has the same
#[doc = "size and bit validity"]
/// as the underlying integer type, [`
#[doc = "u64"]
/// `].
#[doc =
"However, the alignment of this type is always equal to its size, even on targets where [`u64`] has a lesser alignment."]
///
/// For more about the differences between atomic types and
/// non-atomic types as well as information about the portability of
/// this type, please see the [module-level documentation].
///
/// **Note:** This type is only available on platforms that support
/// atomic loads and stores of [`
#[doc = "u64"]
/// `].
///
/// [module-level documentation]: crate::sync::atomic
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub type AtomicU64 = Atomic<u64>;
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl Default for AtomicU64 {
#[inline]
fn default() -> Self { Self::new(Default::default()) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl From<u64> for AtomicU64 {
#[doc = "Converts an `u64` into an `AtomicU64`."]
#[inline]
fn from(v: u64) -> Self { Self::new(v) }
}
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
impl fmt::Debug for AtomicU64 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
}
}
impl AtomicU64 {
/// Creates a new atomic integer.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicU64;"]
///
#[doc = "let atomic_forty_two = AtomicU64::new(42);"]
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0")]
#[must_use]
pub const fn new(v: u64) -> Self { unsafe { transmute(v) } }
/// Creates a new reference to an atomic integer from a pointer.
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{self, AtomicU64};"]
///
/// // Get a pointer to an allocated value
#[doc = "let ptr: *mut u64 = Box::into_raw(Box::new(0));"]
///
#[doc = "assert!(ptr.cast::<AtomicU64>().is_aligned());"]
///
/// {
/// // Create an atomic view of the allocated value
#[doc = " let atomic = unsafe {AtomicU64::from_ptr(ptr) };"]
///
/// // Use `atomic` for atomic operations, possibly share it with other threads
/// atomic.store(1, atomic::Ordering::Relaxed);
/// }
///
/// // It's ok to non-atomically access the value behind `ptr`,
/// // since the reference to the atomic ended its lifetime in the block above
/// assert_eq!(unsafe { *ptr }, 1);
///
/// // Deallocate the value
/// unsafe { drop(Box::from_raw(ptr)) }
/// ```
///
/// # Safety
///
/// * `ptr` must be aligned to
#[doc = " `align_of::<AtomicU64>()`"]
#[doc =
" (note that on some platforms this can be bigger than `align_of::<u64>()`)."]
/// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
/// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
/// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
/// sizes, without synchronization.
///
/// [valid]: crate::ptr#safety
/// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_from_ptr", since = "1.75.0")]
#[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
pub const unsafe fn from_ptr<'a>(ptr: *mut u64) -> &'a AtomicU64 {
unsafe { &*ptr.cast() }
}
/// Returns a mutable reference to the underlying integer.
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let mut some_var = AtomicU64::new(10);"]
/// assert_eq!(*some_var.get_mut(), 10);
/// *some_var.get_mut() = 5;
/// assert_eq!(some_var.load(Ordering::SeqCst), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn get_mut(&mut self) -> &mut u64 { unsafe { &mut *self.as_ptr() } }
#[doc = "Get atomic access to a `&mut u64`."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicU64` has the same alignment as `u64`."]
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
/// let mut some_int = 123;
#[doc = "let a = AtomicU64::from_mut(&mut some_int);"]
/// a.store(100, Ordering::Relaxed);
/// assert_eq!(some_int, 100);
/// ```
///
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut(v: &mut u64) -> &mut Self {
let [] = [(); align_of::<Self>() - align_of::<u64>()];
unsafe { &mut *(v as *mut u64 as *mut Self) }
}
#[doc = "Get non-atomic access to a `&mut [AtomicU64]` slice"]
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let mut some_ints = [const { AtomicU64::new(0) }; 10];"]
///
#[doc =
"let view: &mut [u64] = AtomicU64::get_mut_slice(&mut some_ints);"]
/// assert_eq!(view, [0; 10]);
/// view
/// .iter_mut()
/// .enumerate()
/// .for_each(|(idx, int)| *int = idx as _);
///
/// std::thread::scope(|s| {
/// some_ints
/// .iter()
/// .enumerate()
/// .for_each(|(idx, int)| {
/// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
/// })
/// });
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn get_mut_slice(this: &mut [Self]) -> &mut [u64] {
unsafe { &mut *(this as *mut [Self] as *mut [u64]) }
}
#[doc = "Get atomic access to a `&mut [u64]` slice."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicU64` has the same alignment as `u64`."]
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
/// let mut some_ints = [0; 10];
#[doc = "let a = &*AtomicU64::from_mut_slice(&mut some_ints);"]
/// std::thread::scope(|s| {
/// for i in 0..a.len() {
/// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
/// }
/// });
/// for (i, n) in some_ints.into_iter().enumerate() {
/// assert_eq!(i, n as usize);
/// }
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut_slice(v: &mut [u64]) -> &mut [Self] {
let [] = [(); align_of::<Self>() - align_of::<u64>()];
unsafe { &mut *(v as *mut [u64] as *mut [Self]) }
}
/// Consumes the atomic and returns the contained value.
///
/// This is safe because passing `self` by value guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicU64;"]
///
#[doc = "let some_var = AtomicU64::new(5);"]
/// assert_eq!(some_var.into_inner(), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_const_stable(feature = "const_atomic_into_inner", since =
"1.79.0")]
pub const fn into_inner(self) -> u64 { unsafe { transmute(self) } }
/// Loads a value from the atomic integer.
///
/// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Release`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let some_var = AtomicU64::new(5);"]
///
/// assert_eq!(some_var.load(Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
pub fn load(&self, order: Ordering) -> u64 {
unsafe { atomic_load(self.as_ptr(), order) }
}
/// Stores a value into the atomic integer.
///
/// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Acquire`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let some_var = AtomicU64::new(5);"]
///
/// some_var.store(10, Ordering::Relaxed);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn store(&self, val: u64, order: Ordering) {
unsafe { atomic_store(self.as_ptr(), val, order); }
}
/// Stores a value into the atomic integer, returning the previous value.
///
/// `swap` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let some_var = AtomicU64::new(5);"]
///
/// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn swap(&self, val: u64, order: Ordering) -> u64 {
unsafe { atomic_swap(self.as_ptr(), val, order) }
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is always the previous value. If it is equal to `current`, then the
/// value was updated.
///
/// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
/// ordering of this operation. Notice that even when using [`AcqRel`], the operation
/// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
/// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
/// happens, and using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Migrating to `compare_exchange` and `compare_exchange_weak`
///
/// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
/// memory orderings:
///
/// Original | Success | Failure
/// -------- | ------- | -------
/// Relaxed | Relaxed | Relaxed
/// Acquire | Acquire | Acquire
/// Release | Release | Relaxed
/// AcqRel | AcqRel | Acquire
/// SeqCst | SeqCst | SeqCst
///
/// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
/// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
/// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
/// rather than to infer success vs failure based on the value that was read.
///
/// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
/// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
/// which allows the compiler to generate better assembly code when the compare and swap
/// is used in a loop.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let some_var = AtomicU64::new(5);"]
///
/// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[deprecated(since = "1.50.0", note =
"Use `compare_exchange` or `compare_exchange_weak` instead")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_and_swap(&self, current: u64, new: u64, order: Ordering)
-> u64 {
match self.compare_exchange(current, new, order,
strongest_failure_ordering(order)) {
Ok(x) => x,
Err(x) => x,
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is a result indicating whether the new value was written and
/// containing the previous value. On success this value is guaranteed to be equal to
/// `current`.
///
/// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let some_var = AtomicU64::new(5);"]
///
/// assert_eq!(some_var.compare_exchange(5, 10,
/// Ordering::Acquire,
/// Ordering::Relaxed),
/// Ok(5));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_exchange(6, 12,
/// Ordering::SeqCst,
/// Ordering::Acquire),
/// Err(10));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim! This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange(&self, current: u64, new: u64, success: Ordering,
failure: Ordering) -> Result<u64, u64> {
unsafe {
atomic_compare_exchange(self.as_ptr(), current, new, success,
failure)
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
#[doc = "Unlike [`AtomicU64::compare_exchange`],"]
/// this function is allowed to spuriously fail even
/// when the comparison succeeds, which can result in more efficient code on some
/// platforms. The return value is a result indicating whether the new value was
/// written and containing the previous value.
///
/// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let val = AtomicU64::new(4);"]
///
/// let mut old = val.load(Ordering::Relaxed);
/// loop {
/// let new = old * 2;
/// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
/// Ok(_) => break,
/// Err(x) => old = x,
/// }
/// }
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim. This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange_weak(&self, current: u64, new: u64,
success: Ordering, failure: Ordering) -> Result<u64, u64> {
unsafe {
atomic_compare_exchange_weak(self.as_ptr(), current, new, success,
failure)
}
}
/// Adds to the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let foo = AtomicU64::new(0);"]
/// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_add(&self, val: u64, order: Ordering) -> u64 {
unsafe { atomic_add(self.as_ptr(), val, order) }
}
/// Subtracts from the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let foo = AtomicU64::new(20);"]
/// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_sub(&self, val: u64, order: Ordering) -> u64 {
unsafe { atomic_sub(self.as_ptr(), val, order) }
}
/// Bitwise "and" with the current value.
///
/// Performs a bitwise "and" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let foo = AtomicU64::new(0b101101);"]
/// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_and(&self, val: u64, order: Ordering) -> u64 {
unsafe { atomic_and(self.as_ptr(), val, order) }
}
/// Bitwise "nand" with the current value.
///
/// Performs a bitwise "nand" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let foo = AtomicU64::new(0x13);"]
/// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
/// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_nand(&self, val: u64, order: Ordering) -> u64 {
unsafe { atomic_nand(self.as_ptr(), val, order) }
}
/// Bitwise "or" with the current value.
///
/// Performs a bitwise "or" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let foo = AtomicU64::new(0b101101);"]
/// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_or(&self, val: u64, order: Ordering) -> u64 {
unsafe { atomic_or(self.as_ptr(), val, order) }
}
/// Bitwise "xor" with the current value.
///
/// Performs a bitwise "xor" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let foo = AtomicU64::new(0b101101);"]
/// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
/// ```
#[inline]
#[stable(feature = "integer_atomics_stable", since = "1.34.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_xor(&self, val: u64, order: Ordering) -> u64 {
unsafe { atomic_xor(self.as_ptr(), val, order) }
}
/// An alias for
#[doc = "[`AtomicU64::try_update`]"]
/// .
#[inline]
#[stable(feature = "no_more_cas", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
#[deprecated(since = "1.99.0", note =
"renamed to `try_update` for consistency", suggestion = "try_update")]
pub fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering,
f: F) -> Result<u64, u64> where F: FnMut(u64) -> Option<u64> {
self.try_update(set_order, fetch_order, f)
}
/// Fetches the value, and applies a function to it that returns an optional
/// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
/// `Err(previous_value)`.
///
#[doc = "See also: [`update`](`AtomicU64::update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
/// only once to the stored value.
///
/// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicU64::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Considerations
///
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let x = AtomicU64::new(7);"]
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn try_update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(u64) -> Option<u64>) -> Result<u64, u64> {
let mut prev = self.load(fetch_order);
while let Some(next) = f(prev) {
match self.compare_exchange_weak(prev, next, set_order,
fetch_order) {
x @ Ok(_) => return x,
Err(next_prev) => prev = next_prev,
}
}
Err(prev)
}
/// Fetches the value, applies a function to it that it return a new value.
/// The new value is stored and the old value is returned.
///
#[doc = "See also: [`try_update`](`AtomicU64::try_update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, but the function will have been applied only once to the stored value.
///
/// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicU64::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Considerations
///
/// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let x = AtomicU64::new(7);"]
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(u64) -> u64) -> u64 {
let mut prev = self.load(fetch_order);
loop {
match self.compare_exchange_weak(prev, f(prev), set_order,
fetch_order) {
Ok(x) => break x,
Err(next_prev) => prev = next_prev,
}
}
}
/// Maximum with the current value.
///
/// Finds the maximum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let foo = AtomicU64::new(23);"]
/// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
/// assert_eq!(foo.load(Ordering::SeqCst), 42);
/// ```
///
/// If you want to obtain the maximum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let foo = AtomicU64::new(23);"]
/// let bar = 42;
/// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
/// assert!(max_foo == 42);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_max(&self, val: u64, order: Ordering) -> u64 {
unsafe { atomic_umax(self.as_ptr(), val, order) }
}
/// Minimum with the current value.
///
/// Finds the minimum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`u64`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let foo = AtomicU64::new(23);"]
/// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 23);
/// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 22);
/// ```
///
/// If you want to obtain the minimum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicU64, Ordering};"]
///
#[doc = "let foo = AtomicU64::new(23);"]
/// let bar = 12;
/// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
/// assert_eq!(min_foo, 12);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_min(&self, val: u64, order: Ordering) -> u64 {
unsafe { atomic_umin(self.as_ptr(), val, order) }
}
/// Returns a mutable pointer to the underlying integer.
///
/// Doing non-atomic reads and writes on the resulting integer can be a data race.
/// This method is mostly useful for FFI, where the function signature may use
#[doc = "`*mut u64` instead of `&AtomicU64`."]
///
/// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
/// atomic types work with interior mutability. All modifications of an atomic change the value
/// through a shared reference, and can do so safely as long as they use atomic operations. Any
/// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
/// requirements of the [memory model].
///
/// # Examples
///
/// ```ignore (extern-declaration)
/// # fn main() {
#[doc = "use std::sync::atomic::AtomicU64;"]
///
/// extern "C" {
#[doc = " fn my_atomic_op(arg: *mut u64);"]
/// }
///
#[doc = "let atomic = AtomicU64::new(1);"]
///
/// // SAFETY: Safe as long as `my_atomic_op` is atomic.
/// unsafe {
/// my_atomic_op(atomic.as_ptr());
/// }
/// # }
/// ```
///
/// [memory model]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_never_returns_null_ptr]
pub const fn as_ptr(&self) -> *mut u64 { self.v.get().cast() }
}atomic_int! {
3792 target_has_atomic_load_store = "64",
3793 target_has_atomic = "64",
3794 target_has_atomic_primitive_alignment = "64",
3795 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3796 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3797 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3798 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3799 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3800 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3801 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3802 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3803"u64",
3804"",
3805 atomic_umin, atomic_umax,
38068,
3807 u64 AtomicU643808}3809#[cfg(any(target_has_atomic_load_store = "128", doc))]
3810atomic_int! {
3811 target_has_atomic_load_store = "128",
3812 target_has_atomic = "128",
3813 target_has_atomic_primitive_alignment = "128",
3814 unstable(feature = "integer_atomics", issue = "99069"),
3815 unstable(feature = "integer_atomics", issue = "99069"),
3816 unstable(feature = "integer_atomics", issue = "99069"),
3817 unstable(feature = "integer_atomics", issue = "99069"),
3818 unstable(feature = "integer_atomics", issue = "99069"),
3819 unstable(feature = "integer_atomics", issue = "99069"),
3820 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3821 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3822"i128",
3823"#![feature(integer_atomics)]\n\n",
3824 atomic_min, atomic_max,
382516,
3826 i128 AtomicI128
3827}
3828#[cfg(any(target_has_atomic_load_store = "128", doc))]
3829atomic_int! {
3830 target_has_atomic_load_store = "128",
3831 target_has_atomic = "128",
3832 target_has_atomic_primitive_alignment = "128",
3833 unstable(feature = "integer_atomics", issue = "99069"),
3834 unstable(feature = "integer_atomics", issue = "99069"),
3835 unstable(feature = "integer_atomics", issue = "99069"),
3836 unstable(feature = "integer_atomics", issue = "99069"),
3837 unstable(feature = "integer_atomics", issue = "99069"),
3838 unstable(feature = "integer_atomics", issue = "99069"),
3839 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3840 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3841"u128",
3842"#![feature(integer_atomics)]\n\n",
3843 atomic_umin, atomic_umax,
384416,
3845 u128 AtomicU128
3846}
38473848#[cfg(target_has_atomic_load_store = "ptr")]
3849macro_rules!atomic_int_ptr_sized {
3850 ( $($target_pointer_width:literal $align:literal)* ) => { $(
3851#[cfg(target_pointer_width = $target_pointer_width)]
3852atomic_int! {
3853 target_has_atomic_load_store = "ptr",
3854 target_has_atomic = "ptr",
3855 target_has_atomic_primitive_alignment = "ptr",
3856 stable(feature = "rust1", since = "1.0.0"),
3857 stable(feature = "extended_compare_and_swap", since = "1.10.0"),
3858 stable(feature = "atomic_debug", since = "1.3.0"),
3859 stable(feature = "atomic_access", since = "1.15.0"),
3860 stable(feature = "atomic_from", since = "1.23.0"),
3861 stable(feature = "atomic_nand", since = "1.27.0"),
3862 rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
3863 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3864"isize",
3865"",
3866 atomic_min, atomic_max,
3867$align,
3868 isize AtomicIsize3869 }
3870#[cfg(target_pointer_width = $target_pointer_width)]
3871atomic_int! {
3872 target_has_atomic_load_store = "ptr",
3873 target_has_atomic = "ptr",
3874 target_has_atomic_primitive_alignment = "ptr",
3875 stable(feature = "rust1", since = "1.0.0"),
3876 stable(feature = "extended_compare_and_swap", since = "1.10.0"),
3877 stable(feature = "atomic_debug", since = "1.3.0"),
3878 stable(feature = "atomic_access", since = "1.15.0"),
3879 stable(feature = "atomic_from", since = "1.23.0"),
3880 stable(feature = "atomic_nand", since = "1.27.0"),
3881 rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
3882 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3883"usize",
3884"",
3885 atomic_umin, atomic_umax,
3886$align,
3887 usize AtomicUsize3888 }
38893890/// An [`AtomicIsize`] initialized to `0`.
3891#[cfg(target_pointer_width = $target_pointer_width)]
3892 #[stable(feature = "rust1", since = "1.0.0")]
3893 #[deprecated(
3894 since = "1.34.0",
3895 note = "the `new` function is now preferred",
3896 suggestion = "AtomicIsize::new(0)",
3897 )]
3898pub const ATOMIC_ISIZE_INIT: AtomicIsize = AtomicIsize::new(0);
38993900/// An [`AtomicUsize`] initialized to `0`.
3901#[cfg(target_pointer_width = $target_pointer_width)]
3902 #[stable(feature = "rust1", since = "1.0.0")]
3903 #[deprecated(
3904 since = "1.34.0",
3905 note = "the `new` function is now preferred",
3906 suggestion = "AtomicUsize::new(0)",
3907 )]
3908pub const ATOMIC_USIZE_INIT: AtomicUsize = AtomicUsize::new(0);
3909 )* };
3910}
39113912#[cfg(target_has_atomic_load_store = "ptr")]
3913/// An integer type which can be safely shared between threads.
///
/// This type has the same
#[doc = "size and bit validity"]
/// as the underlying integer type, [`
#[doc = "usize"]
/// `].
#[doc =
"However, the alignment of this type is always equal to its size, even on targets where [`usize`] has a lesser alignment."]
///
/// For more about the differences between atomic types and
/// non-atomic types as well as information about the portability of
/// this type, please see the [module-level documentation].
///
/// **Note:** This type is only available on platforms that support
/// atomic loads and stores of [`
#[doc = "usize"]
/// `].
///
/// [module-level documentation]: crate::sync::atomic
#[stable(feature = "rust1", since = "1.0.0")]
pub type AtomicUsize = Atomic<usize>;
#[stable(feature = "rust1", since = "1.0.0")]
impl Default for AtomicUsize {
#[inline]
fn default() -> Self { Self::new(Default::default()) }
}
#[stable(feature = "atomic_from", since = "1.23.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl From<usize> for AtomicUsize {
#[doc = "Converts an `usize` into an `AtomicUsize`."]
#[inline]
fn from(v: usize) -> Self { Self::new(v) }
}
#[stable(feature = "atomic_debug", since = "1.3.0")]
impl fmt::Debug for AtomicUsize {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
}
}
impl AtomicUsize {
/// Creates a new atomic integer.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicUsize;"]
///
#[doc = "let atomic_forty_two = AtomicUsize::new(42);"]
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_ptr_sized_atomics", since =
"1.24.0")]
#[must_use]
pub const fn new(v: usize) -> Self { unsafe { transmute(v) } }
/// Creates a new reference to an atomic integer from a pointer.
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{self, AtomicUsize};"]
///
/// // Get a pointer to an allocated value
#[doc = "let ptr: *mut usize = Box::into_raw(Box::new(0));"]
///
#[doc = "assert!(ptr.cast::<AtomicUsize>().is_aligned());"]
///
/// {
/// // Create an atomic view of the allocated value
#[doc = " let atomic = unsafe {AtomicUsize::from_ptr(ptr) };"]
///
/// // Use `atomic` for atomic operations, possibly share it with other threads
/// atomic.store(1, atomic::Ordering::Relaxed);
/// }
///
/// // It's ok to non-atomically access the value behind `ptr`,
/// // since the reference to the atomic ended its lifetime in the block above
/// assert_eq!(unsafe { *ptr }, 1);
///
/// // Deallocate the value
/// unsafe { drop(Box::from_raw(ptr)) }
/// ```
///
/// # Safety
///
/// * `ptr` must be aligned to
#[doc = " `align_of::<AtomicUsize>()`"]
#[doc =
" (note that on some platforms this can be bigger than `align_of::<usize>()`)."]
/// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
/// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
/// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
/// sizes, without synchronization.
///
/// [valid]: crate::ptr#safety
/// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_from_ptr", since = "1.75.0")]
#[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
pub const unsafe fn from_ptr<'a>(ptr: *mut usize) -> &'a AtomicUsize {
unsafe { &*ptr.cast() }
}
/// Returns a mutable reference to the underlying integer.
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let mut some_var = AtomicUsize::new(10);"]
/// assert_eq!(*some_var.get_mut(), 10);
/// *some_var.get_mut() = 5;
/// assert_eq!(some_var.load(Ordering::SeqCst), 5);
/// ```
#[inline]
#[stable(feature = "atomic_access", since = "1.15.0")]
pub fn get_mut(&mut self) -> &mut usize { unsafe { &mut *self.as_ptr() } }
#[doc = "Get atomic access to a `&mut usize`."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicUsize` has the same alignment as `usize`."]
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
/// let mut some_int = 123;
#[doc = "let a = AtomicUsize::from_mut(&mut some_int);"]
/// a.store(100, Ordering::Relaxed);
/// assert_eq!(some_int, 100);
/// ```
///
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut(v: &mut usize) -> &mut Self {
let [] = [(); align_of::<Self>() - align_of::<usize>()];
unsafe { &mut *(v as *mut usize as *mut Self) }
}
#[doc = "Get non-atomic access to a `&mut [AtomicUsize]` slice"]
///
/// This is safe because the mutable reference guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let mut some_ints = [const { AtomicUsize::new(0) }; 10];"]
///
#[doc =
"let view: &mut [usize] = AtomicUsize::get_mut_slice(&mut some_ints);"]
/// assert_eq!(view, [0; 10]);
/// view
/// .iter_mut()
/// .enumerate()
/// .for_each(|(idx, int)| *int = idx as _);
///
/// std::thread::scope(|s| {
/// some_ints
/// .iter()
/// .enumerate()
/// .for_each(|(idx, int)| {
/// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
/// })
/// });
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn get_mut_slice(this: &mut [Self]) -> &mut [usize] {
unsafe { &mut *(this as *mut [Self] as *mut [usize]) }
}
#[doc = "Get atomic access to a `&mut [usize]` slice."]
///
#[doc =
"**Note:** This function is only available on targets where `AtomicUsize` has the same alignment as `usize`."]
///
/// # Examples
///
#[doc = "```ignore-wasm"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
/// let mut some_ints = [0; 10];
#[doc = "let a = &*AtomicUsize::from_mut_slice(&mut some_ints);"]
/// std::thread::scope(|s| {
/// for i in 0..a.len() {
/// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
/// }
/// });
/// for (i, n) in some_ints.into_iter().enumerate() {
/// assert_eq!(i, n as usize);
/// }
/// ```
#[inline]
#[stable(feature = "atomic_from_mut", since = "1.98.0")]
pub fn from_mut_slice(v: &mut [usize]) -> &mut [Self] {
let [] = [(); align_of::<Self>() - align_of::<usize>()];
unsafe { &mut *(v as *mut [usize] as *mut [Self]) }
}
/// Consumes the atomic and returns the contained value.
///
/// This is safe because passing `self` by value guarantees that no other threads are
/// concurrently accessing the atomic data.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::AtomicUsize;"]
///
#[doc = "let some_var = AtomicUsize::new(5);"]
/// assert_eq!(some_var.into_inner(), 5);
/// ```
#[inline]
#[stable(feature = "atomic_access", since = "1.15.0")]
#[rustc_const_stable(feature = "const_atomic_into_inner", since =
"1.79.0")]
pub const fn into_inner(self) -> usize { unsafe { transmute(self) } }
/// Loads a value from the atomic integer.
///
/// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Release`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let some_var = AtomicUsize::new(5);"]
///
/// assert_eq!(some_var.load(Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn load(&self, order: Ordering) -> usize {
unsafe { atomic_load(self.as_ptr(), order) }
}
/// Stores a value into the atomic integer.
///
/// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Acquire`] or [`AcqRel`].
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let some_var = AtomicUsize::new(5);"]
///
/// some_var.store(10, Ordering::Relaxed);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn store(&self, val: usize, order: Ordering) {
unsafe { atomic_store(self.as_ptr(), val, order); }
}
/// Stores a value into the atomic integer, returning the previous value.
///
/// `swap` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let some_var = AtomicUsize::new(5);"]
///
/// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn swap(&self, val: usize, order: Ordering) -> usize {
unsafe { atomic_swap(self.as_ptr(), val, order) }
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is always the previous value. If it is equal to `current`, then the
/// value was updated.
///
/// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
/// ordering of this operation. Notice that even when using [`AcqRel`], the operation
/// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
/// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
/// happens, and using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Migrating to `compare_exchange` and `compare_exchange_weak`
///
/// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
/// memory orderings:
///
/// Original | Success | Failure
/// -------- | ------- | -------
/// Relaxed | Relaxed | Relaxed
/// Acquire | Acquire | Acquire
/// Release | Release | Relaxed
/// AcqRel | AcqRel | Acquire
/// SeqCst | SeqCst | SeqCst
///
/// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
/// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
/// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
/// rather than to infer success vs failure based on the value that was read.
///
/// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
/// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
/// which allows the compiler to generate better assembly code when the compare and swap
/// is used in a loop.
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let some_var = AtomicUsize::new(5);"]
///
/// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[deprecated(since = "1.50.0", note =
"Use `compare_exchange` or `compare_exchange_weak` instead")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_and_swap(&self, current: usize, new: usize,
order: Ordering) -> usize {
match self.compare_exchange(current, new, order,
strongest_failure_ordering(order)) {
Ok(x) => x,
Err(x) => x,
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
/// The return value is a result indicating whether the new value was written and
/// containing the previous value. On success this value is guaranteed to be equal to
/// `current`.
///
/// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let some_var = AtomicUsize::new(5);"]
///
/// assert_eq!(some_var.compare_exchange(5, 10,
/// Ordering::Acquire,
/// Ordering::Relaxed),
/// Ok(5));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
///
/// assert_eq!(some_var.compare_exchange(6, 12,
/// Ordering::SeqCst,
/// Ordering::Acquire),
/// Err(10));
/// assert_eq!(some_var.load(Ordering::Relaxed), 10);
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim! This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange(&self, current: usize, new: usize,
success: Ordering, failure: Ordering) -> Result<usize, usize> {
unsafe {
atomic_compare_exchange(self.as_ptr(), current, new, success,
failure)
}
}
/// Stores a value into the atomic integer if the current value is the same as
/// the `current` value.
///
#[doc = "Unlike [`AtomicUsize::compare_exchange`],"]
/// this function is allowed to spuriously fail even
/// when the comparison succeeds, which can result in more efficient code on some
/// platforms. The return value is a result indicating whether the new value was
/// written and containing the previous value.
///
/// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
/// ordering of this operation. `success` describes the required ordering for the
/// read-modify-write operation that takes place if the comparison with `current` succeeds.
/// `failure` describes the required ordering for the load operation that takes place when
/// the comparison fails. Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the successful load
/// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let val = AtomicUsize::new(4);"]
///
/// let mut old = val.load(Ordering::Relaxed);
/// loop {
/// let new = old * 2;
/// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
/// Ok(_) => break,
/// Err(x) => old = x,
/// }
/// }
/// ```
///
/// # Considerations
///
/// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
/// of CAS operations. In particular, a load of the value followed by a successful
/// `compare_exchange` with the previous load *does not ensure* that other threads have not
/// changed the value in the interim. This is usually important when the *equality* check in
/// the `compare_exchange` is being used to check the *identity* of a value, but equality
/// does not necessarily imply identity. This is a particularly common case for pointers, as
/// a pointer holding the same address does not imply that the same object exists at that
/// address! In this case, `compare_exchange` can lead to the [ABA problem].
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
#[inline]
#[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn compare_exchange_weak(&self, current: usize, new: usize,
success: Ordering, failure: Ordering) -> Result<usize, usize> {
unsafe {
atomic_compare_exchange_weak(self.as_ptr(), current, new, success,
failure)
}
}
/// Adds to the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let foo = AtomicUsize::new(0);"]
/// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_add(&self, val: usize, order: Ordering) -> usize {
unsafe { atomic_add(self.as_ptr(), val, order) }
}
/// Subtracts from the current value, returning the previous value.
///
/// This operation wraps around on overflow.
///
/// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let foo = AtomicUsize::new(20);"]
/// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
/// assert_eq!(foo.load(Ordering::SeqCst), 10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_sub(&self, val: usize, order: Ordering) -> usize {
unsafe { atomic_sub(self.as_ptr(), val, order) }
}
/// Bitwise "and" with the current value.
///
/// Performs a bitwise "and" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let foo = AtomicUsize::new(0b101101);"]
/// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_and(&self, val: usize, order: Ordering) -> usize {
unsafe { atomic_and(self.as_ptr(), val, order) }
}
/// Bitwise "nand" with the current value.
///
/// Performs a bitwise "nand" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let foo = AtomicUsize::new(0x13);"]
/// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
/// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
/// ```
#[inline]
#[stable(feature = "atomic_nand", since = "1.27.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_nand(&self, val: usize, order: Ordering) -> usize {
unsafe { atomic_nand(self.as_ptr(), val, order) }
}
/// Bitwise "or" with the current value.
///
/// Performs a bitwise "or" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let foo = AtomicUsize::new(0b101101);"]
/// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_or(&self, val: usize, order: Ordering) -> usize {
unsafe { atomic_or(self.as_ptr(), val, order) }
}
/// Bitwise "xor" with the current value.
///
/// Performs a bitwise "xor" operation on the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let foo = AtomicUsize::new(0b101101);"]
/// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
/// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_xor(&self, val: usize, order: Ordering) -> usize {
unsafe { atomic_xor(self.as_ptr(), val, order) }
}
/// An alias for
#[doc = "[`AtomicUsize::try_update`]"]
/// .
#[inline]
#[stable(feature = "no_more_cas", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
#[deprecated(since = "1.99.0", note =
"renamed to `try_update` for consistency", suggestion = "try_update")]
pub fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering,
f: F) -> Result<usize, usize> where F: FnMut(usize) -> Option<usize> {
self.try_update(set_order, fetch_order, f)
}
/// Fetches the value, and applies a function to it that returns an optional
/// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
/// `Err(previous_value)`.
///
#[doc = "See also: [`update`](`AtomicUsize::update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
/// only once to the stored value.
///
/// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicUsize::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Considerations
///
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let x = AtomicUsize::new(7);"]
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
/// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn try_update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(usize) -> Option<usize>) -> Result<usize, usize> {
let mut prev = self.load(fetch_order);
while let Some(next) = f(prev) {
match self.compare_exchange_weak(prev, next, set_order,
fetch_order) {
x @ Ok(_) => return x,
Err(next_prev) => prev = next_prev,
}
}
Err(prev)
}
/// Fetches the value, applies a function to it that it return a new value.
/// The new value is stored and the old value is returned.
///
#[doc = "See also: [`try_update`](`AtomicUsize::try_update`)."]
///
/// Note: This may call the function multiple times if the value has been changed from other threads in
/// the meantime, but the function will have been applied only once to the stored value.
///
/// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
/// The first describes the required ordering for when the operation finally succeeds while the second
/// describes the required ordering for loads. These correspond to the success and failure orderings of
#[doc = "[`AtomicUsize::compare_exchange`]"]
/// respectively.
///
/// Using [`Acquire`] as success ordering makes the store part
/// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
/// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Considerations
///
/// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
/// This method is not magic; it is not provided by the hardware, and does not act like a
/// critical section or mutex.
///
/// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
/// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
/// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
/// of the atomic is not in and of itself sufficient to ensure any required preconditions.
///
/// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
/// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
///
/// # Examples
///
#[doc = "```rust"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let x = AtomicUsize::new(7);"]
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
/// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
/// assert_eq!(x.load(Ordering::SeqCst), 9);
/// ```
#[inline]
#[stable(feature = "atomic_try_update", since = "1.95.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn update(&self, set_order: Ordering, fetch_order: Ordering,
mut f: impl FnMut(usize) -> usize) -> usize {
let mut prev = self.load(fetch_order);
loop {
match self.compare_exchange_weak(prev, f(prev), set_order,
fetch_order) {
Ok(x) => break x,
Err(next_prev) => prev = next_prev,
}
}
}
/// Maximum with the current value.
///
/// Finds the maximum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let foo = AtomicUsize::new(23);"]
/// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
/// assert_eq!(foo.load(Ordering::SeqCst), 42);
/// ```
///
/// If you want to obtain the maximum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let foo = AtomicUsize::new(23);"]
/// let bar = 42;
/// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
/// assert!(max_foo == 42);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_max(&self, val: usize, order: Ordering) -> usize {
unsafe { atomic_umax(self.as_ptr(), val, order) }
}
/// Minimum with the current value.
///
/// Finds the minimum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
#[doc = "[`usize`]."]
///
/// # Examples
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let foo = AtomicUsize::new(23);"]
/// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 23);
/// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
/// assert_eq!(foo.load(Ordering::Relaxed), 22);
/// ```
///
/// If you want to obtain the minimum value in one step, you can use the following:
///
#[doc = "```"]
#[doc = "use std::sync::atomic::{AtomicUsize, Ordering};"]
///
#[doc = "let foo = AtomicUsize::new(23);"]
/// let bar = 12;
/// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
/// assert_eq!(min_foo, 12);
/// ```
#[inline]
#[stable(feature = "atomic_min_max", since = "1.45.0")]
#[rustc_should_not_be_called_on_const_items]
pub fn fetch_min(&self, val: usize, order: Ordering) -> usize {
unsafe { atomic_umin(self.as_ptr(), val, order) }
}
/// Returns a mutable pointer to the underlying integer.
///
/// Doing non-atomic reads and writes on the resulting integer can be a data race.
/// This method is mostly useful for FFI, where the function signature may use
#[doc = "`*mut usize` instead of `&AtomicUsize`."]
///
/// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
/// atomic types work with interior mutability. All modifications of an atomic change the value
/// through a shared reference, and can do so safely as long as they use atomic operations. Any
/// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
/// requirements of the [memory model].
///
/// # Examples
///
/// ```ignore (extern-declaration)
/// # fn main() {
#[doc = "use std::sync::atomic::AtomicUsize;"]
///
/// extern "C" {
#[doc = " fn my_atomic_op(arg: *mut usize);"]
/// }
///
#[doc = "let atomic = AtomicUsize::new(1);"]
///
/// // SAFETY: Safe as long as `my_atomic_op` is atomic.
/// unsafe {
/// my_atomic_op(atomic.as_ptr());
/// }
/// # }
/// ```
///
/// [memory model]: self#memory-model-for-atomic-accesses
#[inline]
#[stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
#[rustc_never_returns_null_ptr]
pub const fn as_ptr(&self) -> *mut usize { self.v.get().cast() }
}
/// An [`AtomicIsize`] initialized to `0`.
#[stable(feature = "rust1", since = "1.0.0")]
#[deprecated(since = "1.34.0", note = "the `new` function is now preferred",
suggestion = "AtomicIsize::new(0)",)]
pub const ATOMIC_ISIZE_INIT: AtomicIsize = AtomicIsize::new(0);
/// An [`AtomicUsize`] initialized to `0`.
#[stable(feature = "rust1", since = "1.0.0")]
#[deprecated(since = "1.34.0", note = "the `new` function is now preferred",
suggestion = "AtomicUsize::new(0)",)]
pub const ATOMIC_USIZE_INIT: AtomicUsize = AtomicUsize::new(0);atomic_int_ptr_sized! {
3914"16" 2
3915"32" 4
3916"64" 8
3917}39183919#[inline]
3920#[cfg(target_has_atomic)]
3921fn strongest_failure_ordering(order: Ordering) -> Ordering {
3922match order {
3923Release => Relaxed,
3924Relaxed => Relaxed,
3925SeqCst => SeqCst,
3926Acquire => Acquire,
3927AcqRel => Acquire,
3928 }
3929}
39303931#[inline]
3932#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3933unsafe fn atomic_store<T: Copy>(dst: *mut T, val: T, order: Ordering) {
3934// SAFETY: the caller must uphold the safety contract for `atomic_store`.
3935unsafe {
3936match order {
3937Relaxed => intrinsics::atomic_store::<T, { AO::Relaxed }>(dst, val),
3938Release => intrinsics::atomic_store::<T, { AO::Release }>(dst, val),
3939SeqCst => intrinsics::atomic_store::<T, { AO::SeqCst }>(dst, val),
3940Acquire => {
crate::panicking::panic_fmt(format_args!("there is no such thing as an acquire store"));
}panic!("there is no such thing as an acquire store"),
3941AcqRel => {
crate::panicking::panic_fmt(format_args!("there is no such thing as an acquire-release store"));
}panic!("there is no such thing as an acquire-release store"),
3942 }
3943 }
3944}
39453946#[inline]
3947#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3948unsafe fn atomic_load<T: Copy>(dst: *const T, order: Ordering) -> T {
3949// SAFETY: the caller must uphold the safety contract for `atomic_load`.
3950unsafe {
3951match order {
3952Relaxed => intrinsics::atomic_load::<T, { AO::Relaxed }>(dst),
3953Acquire => intrinsics::atomic_load::<T, { AO::Acquire }>(dst),
3954SeqCst => intrinsics::atomic_load::<T, { AO::SeqCst }>(dst),
3955Release => {
crate::panicking::panic_fmt(format_args!("there is no such thing as a release load"));
}panic!("there is no such thing as a release load"),
3956AcqRel => {
crate::panicking::panic_fmt(format_args!("there is no such thing as an acquire-release load"));
}panic!("there is no such thing as an acquire-release load"),
3957 }
3958 }
3959}
39603961#[inline]
3962#[cfg(target_has_atomic)]
3963#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3964unsafe fn atomic_swap<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3965// SAFETY: the caller must uphold the safety contract for `atomic_swap`.
3966unsafe {
3967match order {
3968Relaxed => intrinsics::atomic_xchg::<T, { AO::Relaxed }>(dst, val),
3969Acquire => intrinsics::atomic_xchg::<T, { AO::Acquire }>(dst, val),
3970Release => intrinsics::atomic_xchg::<T, { AO::Release }>(dst, val),
3971AcqRel => intrinsics::atomic_xchg::<T, { AO::AcqRel }>(dst, val),
3972SeqCst => intrinsics::atomic_xchg::<T, { AO::SeqCst }>(dst, val),
3973 }
3974 }
3975}
39763977/// Returns the previous value (like __sync_fetch_and_add).
3978#[inline]
3979#[cfg(target_has_atomic)]
3980#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3981unsafe fn atomic_add<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
3982// SAFETY: the caller must uphold the safety contract for `atomic_add`.
3983unsafe {
3984match order {
3985Relaxed => intrinsics::atomic_xadd::<T, U, { AO::Relaxed }>(dst, val),
3986Acquire => intrinsics::atomic_xadd::<T, U, { AO::Acquire }>(dst, val),
3987Release => intrinsics::atomic_xadd::<T, U, { AO::Release }>(dst, val),
3988AcqRel => intrinsics::atomic_xadd::<T, U, { AO::AcqRel }>(dst, val),
3989SeqCst => intrinsics::atomic_xadd::<T, U, { AO::SeqCst }>(dst, val),
3990 }
3991 }
3992}
39933994/// Returns the previous value (like __sync_fetch_and_sub).
3995#[inline]
3996#[cfg(target_has_atomic)]
3997#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3998unsafe fn atomic_sub<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
3999// SAFETY: the caller must uphold the safety contract for `atomic_sub`.
4000unsafe {
4001match order {
4002Relaxed => intrinsics::atomic_xsub::<T, U, { AO::Relaxed }>(dst, val),
4003Acquire => intrinsics::atomic_xsub::<T, U, { AO::Acquire }>(dst, val),
4004Release => intrinsics::atomic_xsub::<T, U, { AO::Release }>(dst, val),
4005AcqRel => intrinsics::atomic_xsub::<T, U, { AO::AcqRel }>(dst, val),
4006SeqCst => intrinsics::atomic_xsub::<T, U, { AO::SeqCst }>(dst, val),
4007 }
4008 }
4009}
40104011/// Publicly exposed for stdarch; nobody else should use this.
4012#[inline]
4013#[cfg(target_has_atomic)]
4014#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4015#[unstable(feature = "core_intrinsics", issue = "none")]
4016#[doc(hidden)]
4017pub unsafe fn atomic_compare_exchange<T: Copy>(
4018 dst: *mut T,
4019 old: T,
4020 new: T,
4021 success: Ordering,
4022 failure: Ordering,
4023) -> Result<T, T> {
4024// SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`.
4025let (val, ok) = unsafe {
4026match (success, failure) {
4027 (Relaxed, Relaxed) => {
4028 intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::Relaxed }>(dst, old, new)
4029 }
4030 (Relaxed, Acquire) => {
4031 intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::Acquire }>(dst, old, new)
4032 }
4033 (Relaxed, SeqCst) => {
4034 intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::SeqCst }>(dst, old, new)
4035 }
4036 (Acquire, Relaxed) => {
4037 intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::Relaxed }>(dst, old, new)
4038 }
4039 (Acquire, Acquire) => {
4040 intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::Acquire }>(dst, old, new)
4041 }
4042 (Acquire, SeqCst) => {
4043 intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::SeqCst }>(dst, old, new)
4044 }
4045 (Release, Relaxed) => {
4046 intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::Relaxed }>(dst, old, new)
4047 }
4048 (Release, Acquire) => {
4049 intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::Acquire }>(dst, old, new)
4050 }
4051 (Release, SeqCst) => {
4052 intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::SeqCst }>(dst, old, new)
4053 }
4054 (AcqRel, Relaxed) => {
4055 intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::Relaxed }>(dst, old, new)
4056 }
4057 (AcqRel, Acquire) => {
4058 intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::Acquire }>(dst, old, new)
4059 }
4060 (AcqRel, SeqCst) => {
4061 intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::SeqCst }>(dst, old, new)
4062 }
4063 (SeqCst, Relaxed) => {
4064 intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::Relaxed }>(dst, old, new)
4065 }
4066 (SeqCst, Acquire) => {
4067 intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::Acquire }>(dst, old, new)
4068 }
4069 (SeqCst, SeqCst) => {
4070 intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::SeqCst }>(dst, old, new)
4071 }
4072 (_, AcqRel) => {
crate::panicking::panic_fmt(format_args!("there is no such thing as an acquire-release failure ordering"));
}panic!("there is no such thing as an acquire-release failure ordering"),
4073 (_, Release) => {
crate::panicking::panic_fmt(format_args!("there is no such thing as a release failure ordering"));
}panic!("there is no such thing as a release failure ordering"),
4074 }
4075 };
4076if ok { Ok(val) } else { Err(val) }
4077}
40784079#[inline]
4080#[cfg(target_has_atomic)]
4081#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4082unsafe fn atomic_compare_exchange_weak<T: Copy>(
4083 dst: *mut T,
4084 old: T,
4085 new: T,
4086 success: Ordering,
4087 failure: Ordering,
4088) -> Result<T, T> {
4089// SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`.
4090let (val, ok) = unsafe {
4091match (success, failure) {
4092 (Relaxed, Relaxed) => {
4093 intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::Relaxed }>(dst, old, new)
4094 }
4095 (Relaxed, Acquire) => {
4096 intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::Acquire }>(dst, old, new)
4097 }
4098 (Relaxed, SeqCst) => {
4099 intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::SeqCst }>(dst, old, new)
4100 }
4101 (Acquire, Relaxed) => {
4102 intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::Relaxed }>(dst, old, new)
4103 }
4104 (Acquire, Acquire) => {
4105 intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::Acquire }>(dst, old, new)
4106 }
4107 (Acquire, SeqCst) => {
4108 intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::SeqCst }>(dst, old, new)
4109 }
4110 (Release, Relaxed) => {
4111 intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::Relaxed }>(dst, old, new)
4112 }
4113 (Release, Acquire) => {
4114 intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::Acquire }>(dst, old, new)
4115 }
4116 (Release, SeqCst) => {
4117 intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::SeqCst }>(dst, old, new)
4118 }
4119 (AcqRel, Relaxed) => {
4120 intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::Relaxed }>(dst, old, new)
4121 }
4122 (AcqRel, Acquire) => {
4123 intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::Acquire }>(dst, old, new)
4124 }
4125 (AcqRel, SeqCst) => {
4126 intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::SeqCst }>(dst, old, new)
4127 }
4128 (SeqCst, Relaxed) => {
4129 intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::Relaxed }>(dst, old, new)
4130 }
4131 (SeqCst, Acquire) => {
4132 intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::Acquire }>(dst, old, new)
4133 }
4134 (SeqCst, SeqCst) => {
4135 intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::SeqCst }>(dst, old, new)
4136 }
4137 (_, AcqRel) => {
crate::panicking::panic_fmt(format_args!("there is no such thing as an acquire-release failure ordering"));
}panic!("there is no such thing as an acquire-release failure ordering"),
4138 (_, Release) => {
crate::panicking::panic_fmt(format_args!("there is no such thing as a release failure ordering"));
}panic!("there is no such thing as a release failure ordering"),
4139 }
4140 };
4141if ok { Ok(val) } else { Err(val) }
4142}
41434144#[inline]
4145#[cfg(target_has_atomic)]
4146#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4147unsafe fn atomic_and<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4148// SAFETY: the caller must uphold the safety contract for `atomic_and`
4149unsafe {
4150match order {
4151Relaxed => intrinsics::atomic_and::<T, U, { AO::Relaxed }>(dst, val),
4152Acquire => intrinsics::atomic_and::<T, U, { AO::Acquire }>(dst, val),
4153Release => intrinsics::atomic_and::<T, U, { AO::Release }>(dst, val),
4154AcqRel => intrinsics::atomic_and::<T, U, { AO::AcqRel }>(dst, val),
4155SeqCst => intrinsics::atomic_and::<T, U, { AO::SeqCst }>(dst, val),
4156 }
4157 }
4158}
41594160#[inline]
4161#[cfg(target_has_atomic)]
4162#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4163unsafe fn atomic_nand<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4164// SAFETY: the caller must uphold the safety contract for `atomic_nand`
4165unsafe {
4166match order {
4167Relaxed => intrinsics::atomic_nand::<T, U, { AO::Relaxed }>(dst, val),
4168Acquire => intrinsics::atomic_nand::<T, U, { AO::Acquire }>(dst, val),
4169Release => intrinsics::atomic_nand::<T, U, { AO::Release }>(dst, val),
4170AcqRel => intrinsics::atomic_nand::<T, U, { AO::AcqRel }>(dst, val),
4171SeqCst => intrinsics::atomic_nand::<T, U, { AO::SeqCst }>(dst, val),
4172 }
4173 }
4174}
41754176#[inline]
4177#[cfg(target_has_atomic)]
4178#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4179unsafe fn atomic_or<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4180// SAFETY: the caller must uphold the safety contract for `atomic_or`
4181unsafe {
4182match order {
4183SeqCst => intrinsics::atomic_or::<T, U, { AO::SeqCst }>(dst, val),
4184Acquire => intrinsics::atomic_or::<T, U, { AO::Acquire }>(dst, val),
4185Release => intrinsics::atomic_or::<T, U, { AO::Release }>(dst, val),
4186AcqRel => intrinsics::atomic_or::<T, U, { AO::AcqRel }>(dst, val),
4187Relaxed => intrinsics::atomic_or::<T, U, { AO::Relaxed }>(dst, val),
4188 }
4189 }
4190}
41914192#[inline]
4193#[cfg(target_has_atomic)]
4194#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4195unsafe fn atomic_xor<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4196// SAFETY: the caller must uphold the safety contract for `atomic_xor`
4197unsafe {
4198match order {
4199SeqCst => intrinsics::atomic_xor::<T, U, { AO::SeqCst }>(dst, val),
4200Acquire => intrinsics::atomic_xor::<T, U, { AO::Acquire }>(dst, val),
4201Release => intrinsics::atomic_xor::<T, U, { AO::Release }>(dst, val),
4202AcqRel => intrinsics::atomic_xor::<T, U, { AO::AcqRel }>(dst, val),
4203Relaxed => intrinsics::atomic_xor::<T, U, { AO::Relaxed }>(dst, val),
4204 }
4205 }
4206}
42074208/// Updates `*dst` to the max value of `val` and the old value (signed comparison)
4209#[inline]
4210#[cfg(target_has_atomic)]
4211#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4212unsafe fn atomic_max<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4213// SAFETY: the caller must uphold the safety contract for `atomic_max`
4214unsafe {
4215match order {
4216Relaxed => intrinsics::atomic_max::<T, { AO::Relaxed }>(dst, val),
4217Acquire => intrinsics::atomic_max::<T, { AO::Acquire }>(dst, val),
4218Release => intrinsics::atomic_max::<T, { AO::Release }>(dst, val),
4219AcqRel => intrinsics::atomic_max::<T, { AO::AcqRel }>(dst, val),
4220SeqCst => intrinsics::atomic_max::<T, { AO::SeqCst }>(dst, val),
4221 }
4222 }
4223}
42244225/// Updates `*dst` to the min value of `val` and the old value (signed comparison)
4226#[inline]
4227#[cfg(target_has_atomic)]
4228#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4229unsafe fn atomic_min<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4230// SAFETY: the caller must uphold the safety contract for `atomic_min`
4231unsafe {
4232match order {
4233Relaxed => intrinsics::atomic_min::<T, { AO::Relaxed }>(dst, val),
4234Acquire => intrinsics::atomic_min::<T, { AO::Acquire }>(dst, val),
4235Release => intrinsics::atomic_min::<T, { AO::Release }>(dst, val),
4236AcqRel => intrinsics::atomic_min::<T, { AO::AcqRel }>(dst, val),
4237SeqCst => intrinsics::atomic_min::<T, { AO::SeqCst }>(dst, val),
4238 }
4239 }
4240}
42414242/// Updates `*dst` to the max value of `val` and the old value (unsigned comparison)
4243#[inline]
4244#[cfg(target_has_atomic)]
4245#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4246unsafe fn atomic_umax<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4247// SAFETY: the caller must uphold the safety contract for `atomic_umax`
4248unsafe {
4249match order {
4250Relaxed => intrinsics::atomic_umax::<T, { AO::Relaxed }>(dst, val),
4251Acquire => intrinsics::atomic_umax::<T, { AO::Acquire }>(dst, val),
4252Release => intrinsics::atomic_umax::<T, { AO::Release }>(dst, val),
4253AcqRel => intrinsics::atomic_umax::<T, { AO::AcqRel }>(dst, val),
4254SeqCst => intrinsics::atomic_umax::<T, { AO::SeqCst }>(dst, val),
4255 }
4256 }
4257}
42584259/// Updates `*dst` to the min value of `val` and the old value (unsigned comparison)
4260#[inline]
4261#[cfg(target_has_atomic)]
4262#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4263unsafe fn atomic_umin<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4264// SAFETY: the caller must uphold the safety contract for `atomic_umin`
4265unsafe {
4266match order {
4267Relaxed => intrinsics::atomic_umin::<T, { AO::Relaxed }>(dst, val),
4268Acquire => intrinsics::atomic_umin::<T, { AO::Acquire }>(dst, val),
4269Release => intrinsics::atomic_umin::<T, { AO::Release }>(dst, val),
4270AcqRel => intrinsics::atomic_umin::<T, { AO::AcqRel }>(dst, val),
4271SeqCst => intrinsics::atomic_umin::<T, { AO::SeqCst }>(dst, val),
4272 }
4273 }
4274}
42754276/// An atomic fence.
4277///
4278/// Fences create synchronization between themselves and atomic operations or fences in other
4279/// threads. It can be helpful to think of a fence as preventing the compiler and CPU from
4280/// reordering certain types of memory operations around it, but that is a simplified model which
4281/// fails to capture some of the nuances.
4282///
4283/// There are 3 different ways to use an atomic fence:
4284///
4285/// - atomic - fence synchronization: an atomic operation with (at least) [`Release`] ordering
4286/// semantics synchronizes with a fence with (at least) [`Acquire`] ordering semantics.
4287/// - fence - atomic synchronization: a fence with (at least) [`Release`] ordering semantics
4288/// synchronizes with an atomic operation with (at least) [`Acquire`] ordering semantics.
4289/// - fence - fence synchronization: a fence with (at least) [`Release`] ordering semantics
4290/// synchronizes with a fence with (at least) [`Acquire`] ordering semantics.
4291///
4292/// These 3 ways complement the regular, fence-less, atomic - atomic synchronization.
4293///
4294/// ## Atomic - Fence
4295///
4296/// An atomic operation on one thread will synchronize with a fence on another thread when:
4297///
4298/// - on thread 1:
4299/// - an atomic operation 'X' with (at least) [`Release`] ordering semantics on some atomic
4300/// object 'm',
4301///
4302/// - is paired on thread 2 with:
4303/// - an atomic read 'Y' with any order on 'm',
4304/// - followed by a fence 'B' with (at least) [`Acquire`] ordering semantics.
4305///
4306/// This provides a happens-before dependence between X and B.
4307///
4308/// ```text
4309/// Thread 1 Thread 2
4310///
4311/// m.store(3, Release); X ---------
4312/// |
4313/// |
4314/// -------------> Y if m.load(Relaxed) == 3 {
4315/// B fence(Acquire);
4316/// ...
4317/// }
4318/// ```
4319///
4320/// ## Fence - Atomic
4321///
4322/// A fence on one thread will synchronize with an atomic operation on another thread when:
4323///
4324/// - on thread:
4325/// - a fence 'A' with (at least) [`Release`] ordering semantics,
4326/// - followed by an atomic write 'X' with any ordering on some atomic object 'm',
4327///
4328/// - is paired on thread 2 with:
4329/// - an atomic operation 'Y' with (at least) [`Acquire`] ordering semantics.
4330///
4331/// This provides a happens-before dependence between A and Y.
4332///
4333/// ```text
4334/// Thread 1 Thread 2
4335///
4336/// fence(Release); A
4337/// m.store(3, Relaxed); X ---------
4338/// |
4339/// |
4340/// -------------> Y if m.load(Acquire) == 3 {
4341/// ...
4342/// }
4343/// ```
4344///
4345/// ## Fence - Fence
4346///
4347/// A fence on one thread will synchronize with a fence on another thread when:
4348///
4349/// - on thread 1:
4350/// - a fence 'A' which has (at least) [`Release`] ordering semantics,
4351/// - followed by an atomic write 'X' with any ordering on some atomic object 'm',
4352///
4353/// - is paired on thread 2 with:
4354/// - an atomic read 'Y' with any ordering on 'm',
4355/// - followed by a fence 'B' with (at least) [`Acquire`] ordering semantics.
4356///
4357/// This provides a happens-before dependence between A and B.
4358///
4359/// ```text
4360/// Thread 1 Thread 2
4361///
4362/// fence(Release); A --------------
4363/// m.store(3, Relaxed); X --------- |
4364/// | |
4365/// | |
4366/// -------------> Y if m.load(Relaxed) == 3 {
4367/// |-------> B fence(Acquire);
4368/// ...
4369/// }
4370/// ```
4371///
4372/// ## Mandatory Atomic
4373///
4374/// Note that in the examples above, it is crucial that the access to `m` are atomic. Fences cannot
4375/// be used to establish synchronization between non-atomic accesses in different threads. However,
4376/// thanks to the happens-before relationship, any non-atomic access that happen-before the atomic
4377/// operation or fence with (at least) [`Release`] ordering semantics are now also properly
4378/// synchronized with any non-atomic accesses that happen-after the atomic operation or fence with
4379/// (at least) [`Acquire`] ordering semantics.
4380///
4381/// ## Memory Ordering
4382///
4383/// A fence which has [`SeqCst`] ordering, in addition to having both [`Acquire`] and [`Release`]
4384/// semantics, participates in the global program order of the other [`SeqCst`] operations and/or
4385/// fences.
4386///
4387/// Accepts [`Acquire`], [`Release`], [`AcqRel`] and [`SeqCst`] orderings.
4388///
4389/// # Panics
4390///
4391/// Panics if `order` is [`Relaxed`].
4392///
4393/// # Examples
4394///
4395/// ```
4396/// use std::sync::atomic::AtomicBool;
4397/// use std::sync::atomic::fence;
4398/// use std::sync::atomic::Ordering;
4399///
4400/// // A mutual exclusion primitive based on spinlock.
4401/// pub struct Mutex {
4402/// flag: AtomicBool,
4403/// }
4404///
4405/// impl Mutex {
4406/// pub fn new() -> Mutex {
4407/// Mutex {
4408/// flag: AtomicBool::new(false),
4409/// }
4410/// }
4411///
4412/// pub fn lock(&self) {
4413/// // Wait until the old value is `false`.
4414/// while self
4415/// .flag
4416/// .compare_exchange_weak(false, true, Ordering::Relaxed, Ordering::Relaxed)
4417/// .is_err()
4418/// {}
4419/// // This fence synchronizes-with store in `unlock`.
4420/// fence(Ordering::Acquire);
4421/// }
4422///
4423/// pub fn unlock(&self) {
4424/// self.flag.store(false, Ordering::Release);
4425/// }
4426/// }
4427/// ```
4428#[inline]
4429#[stable(feature = "rust1", since = "1.0.0")]
4430#[rustc_diagnostic_item = "fence"]
4431#[doc(alias = "atomic_thread_fence")]
4432#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4433pub fn fence(order: Ordering) {
4434// SAFETY: using an atomic fence is safe.
4435unsafe {
4436match order {
4437Acquire => intrinsics::atomic_fence::<{ AO::Acquire }>(),
4438Release => intrinsics::atomic_fence::<{ AO::Release }>(),
4439AcqRel => intrinsics::atomic_fence::<{ AO::AcqRel }>(),
4440SeqCst => intrinsics::atomic_fence::<{ AO::SeqCst }>(),
4441Relaxed => {
crate::panicking::panic_fmt(format_args!("there is no such thing as a relaxed fence"));
}panic!("there is no such thing as a relaxed fence"),
4442 }
4443 }
4444}
44454446/// An atomic fence for synchronization within a single thread.
4447///
4448/// Like [`fence`], this function establishes synchronization with other atomic operations and
4449/// fences. However, unlike [`fence`], `compiler_fence` only establishes synchronization with
4450/// operations *in the same thread*. This may at first sound rather useless, since code within a
4451/// thread is typically already totally ordered and does not need any further synchronization.
4452/// However, there are cases where code can run on the same thread without being synchronized:
4453/// - The most common case is that of a *signal handler*: a signal handler runs in the same thread
4454/// as the code it interrupted, but it is not synchronized with that code. `compiler_fence`
4455/// can be used to establish synchronization between a thread and its signal handler, the same way
4456/// that `fence` can be used to establish synchronization across threads.
4457/// - Similar situations can arise in embedded programming with interrupt handlers, or in custom
4458/// implementations of preemptive green threads. In general, `compiler_fence` can establish
4459/// synchronization with code that is guaranteed to run on the same hardware CPU.
4460///
4461/// See [`fence`] for how a fence can be used to achieve synchronization. Note that just like
4462/// [`fence`], synchronization still requires atomic operations to be used in both threads -- it is
4463/// not possible to perform synchronization entirely with fences and non-atomic operations.
4464///
4465/// `compiler_fence` does not emit any machine code. However, note that `compiler_fence` is also
4466/// *not* a "compiler barrier". It can be helpful to think of a `compiler_fence` as preventing the
4467/// compiler from reordering certain types of memory operations around it, but that is a simplified
4468/// model which fails to capture some of the nuances. The only actual guarantee made by
4469/// `compiler_fence` is establishing synchronization with signal handlers and similar kinds of code,
4470/// under the rules described in the [`fence`] documentation.
4471///
4472/// `compiler_fence` corresponds to [`atomic_signal_fence`] in C and C++.
4473///
4474/// [`atomic_signal_fence`]: https://en.cppreference.com/w/cpp/atomic/atomic_signal_fence
4475///
4476/// # Panics
4477///
4478/// Panics if `order` is [`Relaxed`].
4479///
4480/// # Examples
4481///
4482/// Without the two `compiler_fence` calls, the read of `IMPORTANT_VARIABLE` in `signal_handler`
4483/// is *undefined behavior* due to a data race, despite everything happening in a single thread.
4484/// This is because the signal handler is considered to run concurrently with its associated
4485/// thread, and explicit synchronization is required to pass data between a thread and its
4486/// signal handler. The code below uses two `compiler_fence` calls to establish the usual
4487/// release-acquire synchronization pattern (see [`fence`] for an image).
4488///
4489/// ```
4490/// use std::sync::atomic::AtomicBool;
4491/// use std::sync::atomic::Ordering;
4492/// use std::sync::atomic::compiler_fence;
4493///
4494/// static mut IMPORTANT_VARIABLE: usize = 0;
4495/// static IS_READY: AtomicBool = AtomicBool::new(false);
4496///
4497/// fn main() {
4498/// unsafe { IMPORTANT_VARIABLE = 42 };
4499/// // Marks earlier writes as being released with future relaxed stores.
4500/// compiler_fence(Ordering::Release);
4501/// IS_READY.store(true, Ordering::Relaxed);
4502/// }
4503///
4504/// fn signal_handler() {
4505/// if IS_READY.load(Ordering::Relaxed) {
4506/// // Acquires writes that were released with relaxed stores that we read from.
4507/// compiler_fence(Ordering::Acquire);
4508/// assert_eq!(unsafe { IMPORTANT_VARIABLE }, 42);
4509/// }
4510/// }
4511/// ```
4512#[inline]
4513#[stable(feature = "compiler_fences", since = "1.21.0")]
4514#[rustc_diagnostic_item = "compiler_fence"]
4515#[doc(alias = "atomic_signal_fence")]
4516#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4517pub fn compiler_fence(order: Ordering) {
4518// SAFETY: using an atomic fence is safe.
4519unsafe {
4520match order {
4521Acquire => intrinsics::atomic_singlethreadfence::<{ AO::Acquire }>(),
4522Release => intrinsics::atomic_singlethreadfence::<{ AO::Release }>(),
4523AcqRel => intrinsics::atomic_singlethreadfence::<{ AO::AcqRel }>(),
4524SeqCst => intrinsics::atomic_singlethreadfence::<{ AO::SeqCst }>(),
4525Relaxed => {
crate::panicking::panic_fmt(format_args!("there is no such thing as a relaxed fence"));
}panic!("there is no such thing as a relaxed fence"),
4526 }
4527 }
4528}
45294530#[cfg(target_has_atomic_load_store = "8")]
4531#[stable(feature = "atomic_debug", since = "1.3.0")]
4532impl fmt::Debugfor AtomicBool {
4533fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4534 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
4535 }
4536}
45374538#[cfg(target_has_atomic_load_store = "ptr")]
4539#[stable(feature = "atomic_debug", since = "1.3.0")]
4540impl<T> fmt::Debugfor AtomicPtr<T> {
4541fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4542 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
4543 }
4544}
45454546#[cfg(target_has_atomic_load_store = "ptr")]
4547#[stable(feature = "atomic_pointer", since = "1.24.0")]
4548impl<T> fmt::Pointerfor AtomicPtr<T> {
4549fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4550 fmt::Pointer::fmt(&self.load(Ordering::Relaxed), f)
4551 }
4552}
45534554/// Signals the processor that it is inside a busy-wait spin-loop ("spin lock").
4555///
4556/// This function is deprecated in favor of [`hint::spin_loop`].
4557///
4558/// [`hint::spin_loop`]: crate::hint::spin_loop
4559#[inline]
4560#[stable(feature = "spin_loop_hint", since = "1.24.0")]
4561#[deprecated(since = "1.51.0", note = "use hint::spin_loop instead")]
4562pub fn spin_loop_hint() {
4563spin_loop()
4564}