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