]> git.lizzy.rs Git - rust.git/blob - library/core/src/sync/atomic.rs
Auto merge of #97841 - nvzqz:inline-encode-wide, r=thomcc
[rust.git] / library / core / src / sync / atomic.rs
1 //! Atomic types
2 //!
3 //! Atomic types provide primitive shared-memory communication between
4 //! threads, and are the building blocks of other concurrent
5 //! types.
6 //!
7 //! Rust atomics currently follow the same rules as [C++20 atomics][cpp], specifically `atomic_ref`.
8 //! Basically, creating a *shared reference* to one of the Rust atomic types corresponds to creating
9 //! an `atomic_ref` in C++; the `atomic_ref` is destroyed when the lifetime of the shared reference
10 //! ends. (A Rust atomic type that is exclusively owned or behind a mutable reference does *not*
11 //! correspond to an "atomic object" in C++, since it can be accessed via non-atomic operations.)
12 //!
13 //! This module defines atomic versions of a select number of primitive
14 //! types, including [`AtomicBool`], [`AtomicIsize`], [`AtomicUsize`],
15 //! [`AtomicI8`], [`AtomicU16`], etc.
16 //! Atomic types present operations that, when used correctly, synchronize
17 //! updates between threads.
18 //!
19 //! Each method takes an [`Ordering`] which represents the strength of
20 //! the memory barrier for that operation. These orderings are the
21 //! same as the [C++20 atomic orderings][1]. For more information see the [nomicon][2].
22 //!
23 //! [cpp]: https://en.cppreference.com/w/cpp/atomic
24 //! [1]: https://en.cppreference.com/w/cpp/atomic/memory_order
25 //! [2]: ../../../nomicon/atomics.html
26 //!
27 //! Atomic variables are safe to share between threads (they implement [`Sync`])
28 //! but they do not themselves provide the mechanism for sharing and follow the
29 //! [threading model](../../../std/thread/index.html#the-threading-model) of Rust.
30 //! The most common way to share an atomic variable is to put it into an [`Arc`][arc] (an
31 //! atomically-reference-counted shared pointer).
32 //!
33 //! [arc]: ../../../std/sync/struct.Arc.html
34 //!
35 //! Atomic types may be stored in static variables, initialized using
36 //! the constant initializers like [`AtomicBool::new`]. Atomic statics
37 //! are often used for lazy global initialization.
38 //!
39 //! # Portability
40 //!
41 //! All atomic types in this module are guaranteed to be [lock-free] if they're
42 //! available. This means they don't internally acquire a global mutex. Atomic
43 //! types and operations are not guaranteed to be wait-free. This means that
44 //! operations like `fetch_or` may be implemented with a compare-and-swap loop.
45 //!
46 //! Atomic operations may be implemented at the instruction layer with
47 //! larger-size atomics. For example some platforms use 4-byte atomic
48 //! instructions to implement `AtomicI8`. Note that this emulation should not
49 //! have an impact on correctness of code, it's just something to be aware of.
50 //!
51 //! The atomic types in this module might not be available on all platforms. The
52 //! atomic types here are all widely available, however, and can generally be
53 //! relied upon existing. Some notable exceptions are:
54 //!
55 //! * PowerPC and MIPS platforms with 32-bit pointers do not have `AtomicU64` or
56 //!   `AtomicI64` types.
57 //! * ARM platforms like `armv5te` that aren't for Linux only provide `load`
58 //!   and `store` operations, and do not support Compare and Swap (CAS)
59 //!   operations, such as `swap`, `fetch_add`, etc. Additionally on Linux,
60 //!   these CAS operations are implemented via [operating system support], which
61 //!   may come with a performance penalty.
62 //! * ARM targets with `thumbv6m` only provide `load` and `store` operations,
63 //!   and do not support Compare and Swap (CAS) operations, such as `swap`,
64 //!   `fetch_add`, etc.
65 //!
66 //! [operating system support]: https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt
67 //!
68 //! Note that future platforms may be added that also do not have support for
69 //! some atomic operations. Maximally portable code will want to be careful
70 //! about which atomic types are used. `AtomicUsize` and `AtomicIsize` are
71 //! generally the most portable, but even then they're not available everywhere.
72 //! For reference, the `std` library requires `AtomicBool`s and pointer-sized atomics, although
73 //! `core` does not.
74 //!
75 //! The `#[cfg(target_has_atomic)]` attribute can be used to conditionally
76 //! compile based on the target's supported bit widths. It is a key-value
77 //! option set for each supported size, with values "8", "16", "32", "64",
78 //! "128", and "ptr" for pointer-sized atomics.
79 //!
80 //! [lock-free]: https://en.wikipedia.org/wiki/Non-blocking_algorithm
81 //!
82 //! # Examples
83 //!
84 //! A simple spinlock:
85 //!
86 //! ```
87 //! use std::sync::Arc;
88 //! use std::sync::atomic::{AtomicUsize, Ordering};
89 //! use std::{hint, thread};
90 //!
91 //! fn main() {
92 //!     let spinlock = Arc::new(AtomicUsize::new(1));
93 //!
94 //!     let spinlock_clone = Arc::clone(&spinlock);
95 //!     let thread = thread::spawn(move|| {
96 //!         spinlock_clone.store(0, Ordering::SeqCst);
97 //!     });
98 //!
99 //!     // Wait for the other thread to release the lock
100 //!     while spinlock.load(Ordering::SeqCst) != 0 {
101 //!         hint::spin_loop();
102 //!     }
103 //!
104 //!     if let Err(panic) = thread.join() {
105 //!         println!("Thread had an error: {panic:?}");
106 //!     }
107 //! }
108 //! ```
109 //!
110 //! Keep a global count of live threads:
111 //!
112 //! ```
113 //! use std::sync::atomic::{AtomicUsize, Ordering};
114 //!
115 //! static GLOBAL_THREAD_COUNT: AtomicUsize = AtomicUsize::new(0);
116 //!
117 //! let old_thread_count = GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::SeqCst);
118 //! println!("live threads: {}", old_thread_count + 1);
119 //! ```
120
121 #![stable(feature = "rust1", since = "1.0.0")]
122 #![cfg_attr(not(target_has_atomic_load_store = "8"), allow(dead_code))]
123 #![cfg_attr(not(target_has_atomic_load_store = "8"), allow(unused_imports))]
124 #![rustc_diagnostic_item = "atomic_mod"]
125
126 use self::Ordering::*;
127
128 use crate::cell::UnsafeCell;
129 use crate::fmt;
130 use crate::intrinsics;
131
132 use crate::hint::spin_loop;
133
134 /// A boolean type which can be safely shared between threads.
135 ///
136 /// This type has the same in-memory representation as a [`bool`].
137 ///
138 /// **Note**: This type is only available on platforms that support atomic
139 /// loads and stores of `u8`.
140 #[cfg(target_has_atomic_load_store = "8")]
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[rustc_diagnostic_item = "AtomicBool"]
143 #[repr(C, align(1))]
144 pub struct AtomicBool {
145     v: UnsafeCell<u8>,
146 }
147
148 #[cfg(target_has_atomic_load_store = "8")]
149 #[stable(feature = "rust1", since = "1.0.0")]
150 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
151 impl const Default for AtomicBool {
152     /// Creates an `AtomicBool` initialized to `false`.
153     #[inline]
154     fn default() -> Self {
155         Self::new(false)
156     }
157 }
158
159 // Send is implicitly implemented for AtomicBool.
160 #[cfg(target_has_atomic_load_store = "8")]
161 #[stable(feature = "rust1", since = "1.0.0")]
162 unsafe impl Sync for AtomicBool {}
163
164 /// A raw pointer type which can be safely shared between threads.
165 ///
166 /// This type has the same in-memory representation as a `*mut T`.
167 ///
168 /// **Note**: This type is only available on platforms that support atomic
169 /// loads and stores of pointers. Its size depends on the target pointer's size.
170 #[cfg(target_has_atomic_load_store = "ptr")]
171 #[stable(feature = "rust1", since = "1.0.0")]
172 #[cfg_attr(not(test), rustc_diagnostic_item = "AtomicPtr")]
173 #[cfg_attr(target_pointer_width = "16", repr(C, align(2)))]
174 #[cfg_attr(target_pointer_width = "32", repr(C, align(4)))]
175 #[cfg_attr(target_pointer_width = "64", repr(C, align(8)))]
176 pub struct AtomicPtr<T> {
177     p: UnsafeCell<*mut T>,
178 }
179
180 #[cfg(target_has_atomic_load_store = "ptr")]
181 #[stable(feature = "rust1", since = "1.0.0")]
182 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
183 impl<T> const Default for AtomicPtr<T> {
184     /// Creates a null `AtomicPtr<T>`.
185     fn default() -> AtomicPtr<T> {
186         AtomicPtr::new(crate::ptr::null_mut())
187     }
188 }
189
190 #[cfg(target_has_atomic_load_store = "ptr")]
191 #[stable(feature = "rust1", since = "1.0.0")]
192 unsafe impl<T> Send for AtomicPtr<T> {}
193 #[cfg(target_has_atomic_load_store = "ptr")]
194 #[stable(feature = "rust1", since = "1.0.0")]
195 unsafe impl<T> Sync for AtomicPtr<T> {}
196
197 /// Atomic memory orderings
198 ///
199 /// Memory orderings specify the way atomic operations synchronize memory.
200 /// In its weakest [`Ordering::Relaxed`], only the memory directly touched by the
201 /// operation is synchronized. On the other hand, a store-load pair of [`Ordering::SeqCst`]
202 /// operations synchronize other memory while additionally preserving a total order of such
203 /// operations across all threads.
204 ///
205 /// Rust's memory orderings are [the same as those of
206 /// C++20](https://en.cppreference.com/w/cpp/atomic/memory_order).
207 ///
208 /// For more information see the [nomicon].
209 ///
210 /// [nomicon]: ../../../nomicon/atomics.html
211 #[stable(feature = "rust1", since = "1.0.0")]
212 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
213 #[non_exhaustive]
214 #[rustc_diagnostic_item = "Ordering"]
215 pub enum Ordering {
216     /// No ordering constraints, only atomic operations.
217     ///
218     /// Corresponds to [`memory_order_relaxed`] in C++20.
219     ///
220     /// [`memory_order_relaxed`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Relaxed_ordering
221     #[stable(feature = "rust1", since = "1.0.0")]
222     Relaxed,
223     /// When coupled with a store, all previous operations become ordered
224     /// before any load of this value with [`Acquire`] (or stronger) ordering.
225     /// In particular, all previous writes become visible to all threads
226     /// that perform an [`Acquire`] (or stronger) load of this value.
227     ///
228     /// Notice that using this ordering for an operation that combines loads
229     /// and stores leads to a [`Relaxed`] load operation!
230     ///
231     /// This ordering is only applicable for operations that can perform a store.
232     ///
233     /// Corresponds to [`memory_order_release`] in C++20.
234     ///
235     /// [`memory_order_release`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
236     #[stable(feature = "rust1", since = "1.0.0")]
237     Release,
238     /// When coupled with a load, if the loaded value was written by a store operation with
239     /// [`Release`] (or stronger) ordering, then all subsequent operations
240     /// become ordered after that store. In particular, all subsequent loads will see data
241     /// written before the store.
242     ///
243     /// Notice that using this ordering for an operation that combines loads
244     /// and stores leads to a [`Relaxed`] store operation!
245     ///
246     /// This ordering is only applicable for operations that can perform a load.
247     ///
248     /// Corresponds to [`memory_order_acquire`] in C++20.
249     ///
250     /// [`memory_order_acquire`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
251     #[stable(feature = "rust1", since = "1.0.0")]
252     Acquire,
253     /// Has the effects of both [`Acquire`] and [`Release`] together:
254     /// For loads it uses [`Acquire`] ordering. For stores it uses the [`Release`] ordering.
255     ///
256     /// Notice that in the case of `compare_and_swap`, it is possible that the operation ends up
257     /// not performing any store and hence it has just [`Acquire`] ordering. However,
258     /// `AcqRel` will never perform [`Relaxed`] accesses.
259     ///
260     /// This ordering is only applicable for operations that combine both loads and stores.
261     ///
262     /// Corresponds to [`memory_order_acq_rel`] in C++20.
263     ///
264     /// [`memory_order_acq_rel`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
265     #[stable(feature = "rust1", since = "1.0.0")]
266     AcqRel,
267     /// Like [`Acquire`]/[`Release`]/[`AcqRel`] (for load, store, and load-with-store
268     /// operations, respectively) with the additional guarantee that all threads see all
269     /// sequentially consistent operations in the same order.
270     ///
271     /// Corresponds to [`memory_order_seq_cst`] in C++20.
272     ///
273     /// [`memory_order_seq_cst`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Sequentially-consistent_ordering
274     #[stable(feature = "rust1", since = "1.0.0")]
275     SeqCst,
276 }
277
278 /// An [`AtomicBool`] initialized to `false`.
279 #[cfg(target_has_atomic_load_store = "8")]
280 #[stable(feature = "rust1", since = "1.0.0")]
281 #[deprecated(
282     since = "1.34.0",
283     note = "the `new` function is now preferred",
284     suggestion = "AtomicBool::new(false)"
285 )]
286 pub const ATOMIC_BOOL_INIT: AtomicBool = AtomicBool::new(false);
287
288 #[cfg(target_has_atomic_load_store = "8")]
289 impl AtomicBool {
290     /// Creates a new `AtomicBool`.
291     ///
292     /// # Examples
293     ///
294     /// ```
295     /// use std::sync::atomic::AtomicBool;
296     ///
297     /// let atomic_true  = AtomicBool::new(true);
298     /// let atomic_false = AtomicBool::new(false);
299     /// ```
300     #[inline]
301     #[stable(feature = "rust1", since = "1.0.0")]
302     #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")]
303     #[must_use]
304     pub const fn new(v: bool) -> AtomicBool {
305         AtomicBool { v: UnsafeCell::new(v as u8) }
306     }
307
308     /// Returns a mutable reference to the underlying [`bool`].
309     ///
310     /// This is safe because the mutable reference guarantees that no other threads are
311     /// concurrently accessing the atomic data.
312     ///
313     /// # Examples
314     ///
315     /// ```
316     /// use std::sync::atomic::{AtomicBool, Ordering};
317     ///
318     /// let mut some_bool = AtomicBool::new(true);
319     /// assert_eq!(*some_bool.get_mut(), true);
320     /// *some_bool.get_mut() = false;
321     /// assert_eq!(some_bool.load(Ordering::SeqCst), false);
322     /// ```
323     #[inline]
324     #[stable(feature = "atomic_access", since = "1.15.0")]
325     pub fn get_mut(&mut self) -> &mut bool {
326         // SAFETY: the mutable reference guarantees unique ownership.
327         unsafe { &mut *(self.v.get() as *mut bool) }
328     }
329
330     /// Get atomic access to a `&mut bool`.
331     ///
332     /// # Examples
333     ///
334     /// ```
335     /// #![feature(atomic_from_mut)]
336     /// use std::sync::atomic::{AtomicBool, Ordering};
337     ///
338     /// let mut some_bool = true;
339     /// let a = AtomicBool::from_mut(&mut some_bool);
340     /// a.store(false, Ordering::Relaxed);
341     /// assert_eq!(some_bool, false);
342     /// ```
343     #[inline]
344     #[cfg(target_has_atomic_equal_alignment = "8")]
345     #[unstable(feature = "atomic_from_mut", issue = "76314")]
346     pub fn from_mut(v: &mut bool) -> &mut Self {
347         // SAFETY: the mutable reference guarantees unique ownership, and
348         // alignment of both `bool` and `Self` is 1.
349         unsafe { &mut *(v as *mut bool as *mut Self) }
350     }
351
352     /// Get non-atomic access to a `&mut [AtomicBool]` slice.
353     ///
354     /// This is safe because the mutable reference guarantees that no other threads are
355     /// concurrently accessing the atomic data.
356     ///
357     /// # Examples
358     ///
359     /// ```
360     /// #![feature(atomic_from_mut, inline_const)]
361     /// use std::sync::atomic::{AtomicBool, Ordering};
362     ///
363     /// let mut some_bools = [const { AtomicBool::new(false) }; 10];
364     ///
365     /// let view: &mut [bool] = AtomicBool::get_mut_slice(&mut some_bools);
366     /// assert_eq!(view, [false; 10]);
367     /// view[..5].copy_from_slice(&[true; 5]);
368     ///
369     /// std::thread::scope(|s| {
370     ///     for t in &some_bools[..5] {
371     ///         s.spawn(move || assert_eq!(t.load(Ordering::Relaxed), true));
372     ///     }
373     ///
374     ///     for f in &some_bools[5..] {
375     ///         s.spawn(move || assert_eq!(f.load(Ordering::Relaxed), false));
376     ///     }
377     /// });
378     /// ```
379     #[inline]
380     #[unstable(feature = "atomic_from_mut", issue = "76314")]
381     pub fn get_mut_slice(this: &mut [Self]) -> &mut [bool] {
382         // SAFETY: the mutable reference guarantees unique ownership.
383         unsafe { &mut *(this as *mut [Self] as *mut [bool]) }
384     }
385
386     /// Get atomic access to a `&mut [bool]` slice.
387     ///
388     /// # Examples
389     ///
390     /// ```
391     /// #![feature(atomic_from_mut)]
392     /// use std::sync::atomic::{AtomicBool, Ordering};
393     ///
394     /// let mut some_bools = [false; 10];
395     /// let a = &*AtomicBool::from_mut_slice(&mut some_bools);
396     /// std::thread::scope(|s| {
397     ///     for i in 0..a.len() {
398     ///         s.spawn(move || a[i].store(true, Ordering::Relaxed));
399     ///     }
400     /// });
401     /// assert_eq!(some_bools, [true; 10]);
402     /// ```
403     #[inline]
404     #[cfg(target_has_atomic_equal_alignment = "8")]
405     #[unstable(feature = "atomic_from_mut", issue = "76314")]
406     pub fn from_mut_slice(v: &mut [bool]) -> &mut [Self] {
407         // SAFETY: the mutable reference guarantees unique ownership, and
408         // alignment of both `bool` and `Self` is 1.
409         unsafe { &mut *(v as *mut [bool] as *mut [Self]) }
410     }
411
412     /// Consumes the atomic and returns the contained value.
413     ///
414     /// This is safe because passing `self` by value guarantees that no other threads are
415     /// concurrently accessing the atomic data.
416     ///
417     /// # Examples
418     ///
419     /// ```
420     /// use std::sync::atomic::AtomicBool;
421     ///
422     /// let some_bool = AtomicBool::new(true);
423     /// assert_eq!(some_bool.into_inner(), true);
424     /// ```
425     #[inline]
426     #[stable(feature = "atomic_access", since = "1.15.0")]
427     #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")]
428     pub const fn into_inner(self) -> bool {
429         self.v.into_inner() != 0
430     }
431
432     /// Loads a value from the bool.
433     ///
434     /// `load` takes an [`Ordering`] argument which describes the memory ordering
435     /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
436     ///
437     /// # Panics
438     ///
439     /// Panics if `order` is [`Release`] or [`AcqRel`].
440     ///
441     /// # Examples
442     ///
443     /// ```
444     /// use std::sync::atomic::{AtomicBool, Ordering};
445     ///
446     /// let some_bool = AtomicBool::new(true);
447     ///
448     /// assert_eq!(some_bool.load(Ordering::Relaxed), true);
449     /// ```
450     #[inline]
451     #[stable(feature = "rust1", since = "1.0.0")]
452     pub fn load(&self, order: Ordering) -> bool {
453         // SAFETY: any data races are prevented by atomic intrinsics and the raw
454         // pointer passed in is valid because we got it from a reference.
455         unsafe { atomic_load(self.v.get(), order) != 0 }
456     }
457
458     /// Stores a value into the bool.
459     ///
460     /// `store` takes an [`Ordering`] argument which describes the memory ordering
461     /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
462     ///
463     /// # Panics
464     ///
465     /// Panics if `order` is [`Acquire`] or [`AcqRel`].
466     ///
467     /// # Examples
468     ///
469     /// ```
470     /// use std::sync::atomic::{AtomicBool, Ordering};
471     ///
472     /// let some_bool = AtomicBool::new(true);
473     ///
474     /// some_bool.store(false, Ordering::Relaxed);
475     /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
476     /// ```
477     #[inline]
478     #[stable(feature = "rust1", since = "1.0.0")]
479     pub fn store(&self, val: bool, order: Ordering) {
480         // SAFETY: any data races are prevented by atomic intrinsics and the raw
481         // pointer passed in is valid because we got it from a reference.
482         unsafe {
483             atomic_store(self.v.get(), val as u8, order);
484         }
485     }
486
487     /// Stores a value into the bool, returning the previous value.
488     ///
489     /// `swap` takes an [`Ordering`] argument which describes the memory ordering
490     /// of this operation. All ordering modes are possible. Note that using
491     /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
492     /// using [`Release`] makes the load part [`Relaxed`].
493     ///
494     /// **Note:** This method is only available on platforms that support atomic
495     /// operations on `u8`.
496     ///
497     /// # Examples
498     ///
499     /// ```
500     /// use std::sync::atomic::{AtomicBool, Ordering};
501     ///
502     /// let some_bool = AtomicBool::new(true);
503     ///
504     /// assert_eq!(some_bool.swap(false, Ordering::Relaxed), true);
505     /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
506     /// ```
507     #[inline]
508     #[stable(feature = "rust1", since = "1.0.0")]
509     #[cfg(target_has_atomic = "8")]
510     pub fn swap(&self, val: bool, order: Ordering) -> bool {
511         // SAFETY: data races are prevented by atomic intrinsics.
512         unsafe { atomic_swap(self.v.get(), val as u8, order) != 0 }
513     }
514
515     /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
516     ///
517     /// The return value is always the previous value. If it is equal to `current`, then the value
518     /// was updated.
519     ///
520     /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
521     /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
522     /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
523     /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
524     /// happens, and using [`Release`] makes the load part [`Relaxed`].
525     ///
526     /// **Note:** This method is only available on platforms that support atomic
527     /// operations on `u8`.
528     ///
529     /// # Migrating to `compare_exchange` and `compare_exchange_weak`
530     ///
531     /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
532     /// memory orderings:
533     ///
534     /// Original | Success | Failure
535     /// -------- | ------- | -------
536     /// Relaxed  | Relaxed | Relaxed
537     /// Acquire  | Acquire | Acquire
538     /// Release  | Release | Relaxed
539     /// AcqRel   | AcqRel  | Acquire
540     /// SeqCst   | SeqCst  | SeqCst
541     ///
542     /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
543     /// which allows the compiler to generate better assembly code when the compare and swap
544     /// is used in a loop.
545     ///
546     /// # Examples
547     ///
548     /// ```
549     /// use std::sync::atomic::{AtomicBool, Ordering};
550     ///
551     /// let some_bool = AtomicBool::new(true);
552     ///
553     /// assert_eq!(some_bool.compare_and_swap(true, false, Ordering::Relaxed), true);
554     /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
555     ///
556     /// assert_eq!(some_bool.compare_and_swap(true, true, Ordering::Relaxed), false);
557     /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
558     /// ```
559     #[inline]
560     #[stable(feature = "rust1", since = "1.0.0")]
561     #[deprecated(
562         since = "1.50.0",
563         note = "Use `compare_exchange` or `compare_exchange_weak` instead"
564     )]
565     #[cfg(target_has_atomic = "8")]
566     pub fn compare_and_swap(&self, current: bool, new: bool, order: Ordering) -> bool {
567         match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
568             Ok(x) => x,
569             Err(x) => x,
570         }
571     }
572
573     /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
574     ///
575     /// The return value is a result indicating whether the new value was written and containing
576     /// the previous value. On success this value is guaranteed to be equal to `current`.
577     ///
578     /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
579     /// ordering of this operation. `success` describes the required ordering for the
580     /// read-modify-write operation that takes place if the comparison with `current` succeeds.
581     /// `failure` describes the required ordering for the load operation that takes place when
582     /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
583     /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
584     /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
585     /// and must be equivalent to or weaker than the success ordering.
586     ///
587     /// **Note:** This method is only available on platforms that support atomic
588     /// operations on `u8`.
589     ///
590     /// # Examples
591     ///
592     /// ```
593     /// use std::sync::atomic::{AtomicBool, Ordering};
594     ///
595     /// let some_bool = AtomicBool::new(true);
596     ///
597     /// assert_eq!(some_bool.compare_exchange(true,
598     ///                                       false,
599     ///                                       Ordering::Acquire,
600     ///                                       Ordering::Relaxed),
601     ///            Ok(true));
602     /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
603     ///
604     /// assert_eq!(some_bool.compare_exchange(true, true,
605     ///                                       Ordering::SeqCst,
606     ///                                       Ordering::Acquire),
607     ///            Err(false));
608     /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
609     /// ```
610     #[inline]
611     #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
612     #[doc(alias = "compare_and_swap")]
613     #[cfg(target_has_atomic = "8")]
614     pub fn compare_exchange(
615         &self,
616         current: bool,
617         new: bool,
618         success: Ordering,
619         failure: Ordering,
620     ) -> Result<bool, bool> {
621         // SAFETY: data races are prevented by atomic intrinsics.
622         match unsafe {
623             atomic_compare_exchange(self.v.get(), current as u8, new as u8, success, failure)
624         } {
625             Ok(x) => Ok(x != 0),
626             Err(x) => Err(x != 0),
627         }
628     }
629
630     /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
631     ///
632     /// Unlike [`AtomicBool::compare_exchange`], this function is allowed to spuriously fail even when the
633     /// comparison succeeds, which can result in more efficient code on some platforms. The
634     /// return value is a result indicating whether the new value was written and containing the
635     /// previous value.
636     ///
637     /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
638     /// ordering of this operation. `success` describes the required ordering for the
639     /// read-modify-write operation that takes place if the comparison with `current` succeeds.
640     /// `failure` describes the required ordering for the load operation that takes place when
641     /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
642     /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
643     /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
644     /// and must be equivalent to or weaker than the success ordering.
645     ///
646     /// **Note:** This method is only available on platforms that support atomic
647     /// operations on `u8`.
648     ///
649     /// # Examples
650     ///
651     /// ```
652     /// use std::sync::atomic::{AtomicBool, Ordering};
653     ///
654     /// let val = AtomicBool::new(false);
655     ///
656     /// let new = true;
657     /// let mut old = val.load(Ordering::Relaxed);
658     /// loop {
659     ///     match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
660     ///         Ok(_) => break,
661     ///         Err(x) => old = x,
662     ///     }
663     /// }
664     /// ```
665     #[inline]
666     #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
667     #[doc(alias = "compare_and_swap")]
668     #[cfg(target_has_atomic = "8")]
669     pub fn compare_exchange_weak(
670         &self,
671         current: bool,
672         new: bool,
673         success: Ordering,
674         failure: Ordering,
675     ) -> Result<bool, bool> {
676         // SAFETY: data races are prevented by atomic intrinsics.
677         match unsafe {
678             atomic_compare_exchange_weak(self.v.get(), current as u8, new as u8, success, failure)
679         } {
680             Ok(x) => Ok(x != 0),
681             Err(x) => Err(x != 0),
682         }
683     }
684
685     /// Logical "and" with a boolean value.
686     ///
687     /// Performs a logical "and" operation on the current value and the argument `val`, and sets
688     /// the new value to the result.
689     ///
690     /// Returns the previous value.
691     ///
692     /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
693     /// of this operation. All ordering modes are possible. Note that using
694     /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
695     /// using [`Release`] makes the load part [`Relaxed`].
696     ///
697     /// **Note:** This method is only available on platforms that support atomic
698     /// operations on `u8`.
699     ///
700     /// # Examples
701     ///
702     /// ```
703     /// use std::sync::atomic::{AtomicBool, Ordering};
704     ///
705     /// let foo = AtomicBool::new(true);
706     /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), true);
707     /// assert_eq!(foo.load(Ordering::SeqCst), false);
708     ///
709     /// let foo = AtomicBool::new(true);
710     /// assert_eq!(foo.fetch_and(true, Ordering::SeqCst), true);
711     /// assert_eq!(foo.load(Ordering::SeqCst), true);
712     ///
713     /// let foo = AtomicBool::new(false);
714     /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), false);
715     /// assert_eq!(foo.load(Ordering::SeqCst), false);
716     /// ```
717     #[inline]
718     #[stable(feature = "rust1", since = "1.0.0")]
719     #[cfg(target_has_atomic = "8")]
720     pub fn fetch_and(&self, val: bool, order: Ordering) -> bool {
721         // SAFETY: data races are prevented by atomic intrinsics.
722         unsafe { atomic_and(self.v.get(), val as u8, order) != 0 }
723     }
724
725     /// Logical "nand" with a boolean value.
726     ///
727     /// Performs a logical "nand" operation on the current value and the argument `val`, and sets
728     /// the new value to the result.
729     ///
730     /// Returns the previous value.
731     ///
732     /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
733     /// of this operation. All ordering modes are possible. Note that using
734     /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
735     /// using [`Release`] makes the load part [`Relaxed`].
736     ///
737     /// **Note:** This method is only available on platforms that support atomic
738     /// operations on `u8`.
739     ///
740     /// # Examples
741     ///
742     /// ```
743     /// use std::sync::atomic::{AtomicBool, Ordering};
744     ///
745     /// let foo = AtomicBool::new(true);
746     /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), true);
747     /// assert_eq!(foo.load(Ordering::SeqCst), true);
748     ///
749     /// let foo = AtomicBool::new(true);
750     /// assert_eq!(foo.fetch_nand(true, Ordering::SeqCst), true);
751     /// assert_eq!(foo.load(Ordering::SeqCst) as usize, 0);
752     /// assert_eq!(foo.load(Ordering::SeqCst), false);
753     ///
754     /// let foo = AtomicBool::new(false);
755     /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), false);
756     /// assert_eq!(foo.load(Ordering::SeqCst), true);
757     /// ```
758     #[inline]
759     #[stable(feature = "rust1", since = "1.0.0")]
760     #[cfg(target_has_atomic = "8")]
761     pub fn fetch_nand(&self, val: bool, order: Ordering) -> bool {
762         // We can't use atomic_nand here because it can result in a bool with
763         // an invalid value. This happens because the atomic operation is done
764         // with an 8-bit integer internally, which would set the upper 7 bits.
765         // So we just use fetch_xor or swap instead.
766         if val {
767             // !(x & true) == !x
768             // We must invert the bool.
769             self.fetch_xor(true, order)
770         } else {
771             // !(x & false) == true
772             // We must set the bool to true.
773             self.swap(true, order)
774         }
775     }
776
777     /// Logical "or" with a boolean value.
778     ///
779     /// Performs a logical "or" operation on the current value and the argument `val`, and sets the
780     /// new value to the result.
781     ///
782     /// Returns the previous value.
783     ///
784     /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
785     /// of this operation. All ordering modes are possible. Note that using
786     /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
787     /// using [`Release`] makes the load part [`Relaxed`].
788     ///
789     /// **Note:** This method is only available on platforms that support atomic
790     /// operations on `u8`.
791     ///
792     /// # Examples
793     ///
794     /// ```
795     /// use std::sync::atomic::{AtomicBool, Ordering};
796     ///
797     /// let foo = AtomicBool::new(true);
798     /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), true);
799     /// assert_eq!(foo.load(Ordering::SeqCst), true);
800     ///
801     /// let foo = AtomicBool::new(true);
802     /// assert_eq!(foo.fetch_or(true, Ordering::SeqCst), true);
803     /// assert_eq!(foo.load(Ordering::SeqCst), true);
804     ///
805     /// let foo = AtomicBool::new(false);
806     /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), false);
807     /// assert_eq!(foo.load(Ordering::SeqCst), false);
808     /// ```
809     #[inline]
810     #[stable(feature = "rust1", since = "1.0.0")]
811     #[cfg(target_has_atomic = "8")]
812     pub fn fetch_or(&self, val: bool, order: Ordering) -> bool {
813         // SAFETY: data races are prevented by atomic intrinsics.
814         unsafe { atomic_or(self.v.get(), val as u8, order) != 0 }
815     }
816
817     /// Logical "xor" with a boolean value.
818     ///
819     /// Performs a logical "xor" operation on the current value and the argument `val`, and sets
820     /// the new value to the result.
821     ///
822     /// Returns the previous value.
823     ///
824     /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
825     /// of this operation. All ordering modes are possible. Note that using
826     /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
827     /// using [`Release`] makes the load part [`Relaxed`].
828     ///
829     /// **Note:** This method is only available on platforms that support atomic
830     /// operations on `u8`.
831     ///
832     /// # Examples
833     ///
834     /// ```
835     /// use std::sync::atomic::{AtomicBool, Ordering};
836     ///
837     /// let foo = AtomicBool::new(true);
838     /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), true);
839     /// assert_eq!(foo.load(Ordering::SeqCst), true);
840     ///
841     /// let foo = AtomicBool::new(true);
842     /// assert_eq!(foo.fetch_xor(true, Ordering::SeqCst), true);
843     /// assert_eq!(foo.load(Ordering::SeqCst), false);
844     ///
845     /// let foo = AtomicBool::new(false);
846     /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), false);
847     /// assert_eq!(foo.load(Ordering::SeqCst), false);
848     /// ```
849     #[inline]
850     #[stable(feature = "rust1", since = "1.0.0")]
851     #[cfg(target_has_atomic = "8")]
852     pub fn fetch_xor(&self, val: bool, order: Ordering) -> bool {
853         // SAFETY: data races are prevented by atomic intrinsics.
854         unsafe { atomic_xor(self.v.get(), val as u8, order) != 0 }
855     }
856
857     /// Logical "not" with a boolean value.
858     ///
859     /// Performs a logical "not" operation on the current value, and sets
860     /// the new value to the result.
861     ///
862     /// Returns the previous value.
863     ///
864     /// `fetch_not` takes an [`Ordering`] argument which describes the memory ordering
865     /// of this operation. All ordering modes are possible. Note that using
866     /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
867     /// using [`Release`] makes the load part [`Relaxed`].
868     ///
869     /// **Note:** This method is only available on platforms that support atomic
870     /// operations on `u8`.
871     ///
872     /// # Examples
873     ///
874     /// ```
875     /// #![feature(atomic_bool_fetch_not)]
876     /// use std::sync::atomic::{AtomicBool, Ordering};
877     ///
878     /// let foo = AtomicBool::new(true);
879     /// assert_eq!(foo.fetch_not(Ordering::SeqCst), true);
880     /// assert_eq!(foo.load(Ordering::SeqCst), false);
881     ///
882     /// let foo = AtomicBool::new(false);
883     /// assert_eq!(foo.fetch_not(Ordering::SeqCst), false);
884     /// assert_eq!(foo.load(Ordering::SeqCst), true);
885     /// ```
886     #[inline]
887     #[unstable(feature = "atomic_bool_fetch_not", issue = "98485")]
888     #[cfg(target_has_atomic = "8")]
889     pub fn fetch_not(&self, order: Ordering) -> bool {
890         self.fetch_xor(true, order)
891     }
892
893     /// Returns a mutable pointer to the underlying [`bool`].
894     ///
895     /// Doing non-atomic reads and writes on the resulting integer can be a data race.
896     /// This method is mostly useful for FFI, where the function signature may use
897     /// `*mut bool` instead of `&AtomicBool`.
898     ///
899     /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
900     /// atomic types work with interior mutability. All modifications of an atomic change the value
901     /// through a shared reference, and can do so safely as long as they use atomic operations. Any
902     /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the same
903     /// restriction: operations on it must be atomic.
904     ///
905     /// # Examples
906     ///
907     /// ```ignore (extern-declaration)
908     /// # fn main() {
909     /// use std::sync::atomic::AtomicBool;
910     /// extern "C" {
911     ///     fn my_atomic_op(arg: *mut bool);
912     /// }
913     ///
914     /// let mut atomic = AtomicBool::new(true);
915     /// unsafe {
916     ///     my_atomic_op(atomic.as_mut_ptr());
917     /// }
918     /// # }
919     /// ```
920     #[inline]
921     #[unstable(feature = "atomic_mut_ptr", reason = "recently added", issue = "66893")]
922     pub fn as_mut_ptr(&self) -> *mut bool {
923         self.v.get() as *mut bool
924     }
925
926     /// Fetches the value, and applies a function to it that returns an optional
927     /// new value. Returns a `Result` of `Ok(previous_value)` if the function
928     /// returned `Some(_)`, else `Err(previous_value)`.
929     ///
930     /// Note: This may call the function multiple times if the value has been
931     /// changed from other threads in the meantime, as long as the function
932     /// returns `Some(_)`, but the function will have been applied only once to
933     /// the stored value.
934     ///
935     /// `fetch_update` takes two [`Ordering`] arguments to describe the memory
936     /// ordering of this operation. The first describes the required ordering for
937     /// when the operation finally succeeds while the second describes the
938     /// required ordering for loads. These correspond to the success and failure
939     /// orderings of [`AtomicBool::compare_exchange`] respectively.
940     ///
941     /// Using [`Acquire`] as success ordering makes the store part of this
942     /// operation [`Relaxed`], and using [`Release`] makes the final successful
943     /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
944     /// [`Acquire`] or [`Relaxed`] and must be equivalent to or weaker than the
945     /// success ordering.
946     ///
947     /// **Note:** This method is only available on platforms that support atomic
948     /// operations on `u8`.
949     ///
950     /// # Examples
951     ///
952     /// ```rust
953     /// use std::sync::atomic::{AtomicBool, Ordering};
954     ///
955     /// let x = AtomicBool::new(false);
956     /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(false));
957     /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(false));
958     /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(true));
959     /// assert_eq!(x.load(Ordering::SeqCst), false);
960     /// ```
961     #[inline]
962     #[stable(feature = "atomic_fetch_update", since = "1.53.0")]
963     #[cfg(target_has_atomic = "8")]
964     pub fn fetch_update<F>(
965         &self,
966         set_order: Ordering,
967         fetch_order: Ordering,
968         mut f: F,
969     ) -> Result<bool, bool>
970     where
971         F: FnMut(bool) -> Option<bool>,
972     {
973         let mut prev = self.load(fetch_order);
974         while let Some(next) = f(prev) {
975             match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
976                 x @ Ok(_) => return x,
977                 Err(next_prev) => prev = next_prev,
978             }
979         }
980         Err(prev)
981     }
982 }
983
984 #[cfg(target_has_atomic_load_store = "ptr")]
985 impl<T> AtomicPtr<T> {
986     /// Creates a new `AtomicPtr`.
987     ///
988     /// # Examples
989     ///
990     /// ```
991     /// use std::sync::atomic::AtomicPtr;
992     ///
993     /// let ptr = &mut 5;
994     /// let atomic_ptr = AtomicPtr::new(ptr);
995     /// ```
996     #[inline]
997     #[stable(feature = "rust1", since = "1.0.0")]
998     #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")]
999     pub const fn new(p: *mut T) -> AtomicPtr<T> {
1000         AtomicPtr { p: UnsafeCell::new(p) }
1001     }
1002
1003     /// Returns a mutable reference to the underlying pointer.
1004     ///
1005     /// This is safe because the mutable reference guarantees that no other threads are
1006     /// concurrently accessing the atomic data.
1007     ///
1008     /// # Examples
1009     ///
1010     /// ```
1011     /// use std::sync::atomic::{AtomicPtr, Ordering};
1012     ///
1013     /// let mut data = 10;
1014     /// let mut atomic_ptr = AtomicPtr::new(&mut data);
1015     /// let mut other_data = 5;
1016     /// *atomic_ptr.get_mut() = &mut other_data;
1017     /// assert_eq!(unsafe { *atomic_ptr.load(Ordering::SeqCst) }, 5);
1018     /// ```
1019     #[inline]
1020     #[stable(feature = "atomic_access", since = "1.15.0")]
1021     pub fn get_mut(&mut self) -> &mut *mut T {
1022         self.p.get_mut()
1023     }
1024
1025     /// Get atomic access to a pointer.
1026     ///
1027     /// # Examples
1028     ///
1029     /// ```
1030     /// #![feature(atomic_from_mut)]
1031     /// use std::sync::atomic::{AtomicPtr, Ordering};
1032     ///
1033     /// let mut data = 123;
1034     /// let mut some_ptr = &mut data as *mut i32;
1035     /// let a = AtomicPtr::from_mut(&mut some_ptr);
1036     /// let mut other_data = 456;
1037     /// a.store(&mut other_data, Ordering::Relaxed);
1038     /// assert_eq!(unsafe { *some_ptr }, 456);
1039     /// ```
1040     #[inline]
1041     #[cfg(target_has_atomic_equal_alignment = "ptr")]
1042     #[unstable(feature = "atomic_from_mut", issue = "76314")]
1043     pub fn from_mut(v: &mut *mut T) -> &mut Self {
1044         use crate::mem::align_of;
1045         let [] = [(); align_of::<AtomicPtr<()>>() - align_of::<*mut ()>()];
1046         // SAFETY:
1047         //  - the mutable reference guarantees unique ownership.
1048         //  - the alignment of `*mut T` and `Self` is the same on all platforms
1049         //    supported by rust, as verified above.
1050         unsafe { &mut *(v as *mut *mut T as *mut Self) }
1051     }
1052
1053     /// Get non-atomic access to a `&mut [AtomicPtr]` slice.
1054     ///
1055     /// This is safe because the mutable reference guarantees that no other threads are
1056     /// concurrently accessing the atomic data.
1057     ///
1058     /// # Examples
1059     ///
1060     /// ```
1061     /// #![feature(atomic_from_mut, inline_const)]
1062     /// use std::ptr::null_mut;
1063     /// use std::sync::atomic::{AtomicPtr, Ordering};
1064     ///
1065     /// let mut some_ptrs = [const { AtomicPtr::new(null_mut::<String>()) }; 10];
1066     ///
1067     /// let view: &mut [*mut String] = AtomicPtr::get_mut_slice(&mut some_ptrs);
1068     /// assert_eq!(view, [null_mut::<String>(); 10]);
1069     /// view
1070     ///     .iter_mut()
1071     ///     .enumerate()
1072     ///     .for_each(|(i, ptr)| *ptr = Box::into_raw(Box::new(format!("iteration#{i}"))));
1073     ///
1074     /// std::thread::scope(|s| {
1075     ///     for ptr in &some_ptrs {
1076     ///         s.spawn(move || {
1077     ///             let ptr = ptr.load(Ordering::Relaxed);
1078     ///             assert!(!ptr.is_null());
1079     ///
1080     ///             let name = unsafe { Box::from_raw(ptr) };
1081     ///             println!("Hello, {name}!");
1082     ///         });
1083     ///     }
1084     /// });
1085     /// ```
1086     #[inline]
1087     #[unstable(feature = "atomic_from_mut", issue = "76314")]
1088     pub fn get_mut_slice(this: &mut [Self]) -> &mut [*mut T] {
1089         // SAFETY: the mutable reference guarantees unique ownership.
1090         unsafe { &mut *(this as *mut [Self] as *mut [*mut T]) }
1091     }
1092
1093     /// Get atomic access to a slice of pointers.
1094     ///
1095     /// # Examples
1096     ///
1097     /// ```
1098     /// #![feature(atomic_from_mut)]
1099     /// use std::ptr::null_mut;
1100     /// use std::sync::atomic::{AtomicPtr, Ordering};
1101     ///
1102     /// let mut some_ptrs = [null_mut::<String>(); 10];
1103     /// let a = &*AtomicPtr::from_mut_slice(&mut some_ptrs);
1104     /// std::thread::scope(|s| {
1105     ///     for i in 0..a.len() {
1106     ///         s.spawn(move || {
1107     ///             let name = Box::new(format!("thread{i}"));
1108     ///             a[i].store(Box::into_raw(name), Ordering::Relaxed);
1109     ///         });
1110     ///     }
1111     /// });
1112     /// for p in some_ptrs {
1113     ///     assert!(!p.is_null());
1114     ///     let name = unsafe { Box::from_raw(p) };
1115     ///     println!("Hello, {name}!");
1116     /// }
1117     /// ```
1118     #[inline]
1119     #[cfg(target_has_atomic_equal_alignment = "ptr")]
1120     #[unstable(feature = "atomic_from_mut", issue = "76314")]
1121     pub fn from_mut_slice(v: &mut [*mut T]) -> &mut [Self] {
1122         // SAFETY:
1123         //  - the mutable reference guarantees unique ownership.
1124         //  - the alignment of `*mut T` and `Self` is the same on all platforms
1125         //    supported by rust, as verified above.
1126         unsafe { &mut *(v as *mut [*mut T] as *mut [Self]) }
1127     }
1128
1129     /// Consumes the atomic and returns the contained value.
1130     ///
1131     /// This is safe because passing `self` by value guarantees that no other threads are
1132     /// concurrently accessing the atomic data.
1133     ///
1134     /// # Examples
1135     ///
1136     /// ```
1137     /// use std::sync::atomic::AtomicPtr;
1138     ///
1139     /// let mut data = 5;
1140     /// let atomic_ptr = AtomicPtr::new(&mut data);
1141     /// assert_eq!(unsafe { *atomic_ptr.into_inner() }, 5);
1142     /// ```
1143     #[inline]
1144     #[stable(feature = "atomic_access", since = "1.15.0")]
1145     #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")]
1146     pub const fn into_inner(self) -> *mut T {
1147         self.p.into_inner()
1148     }
1149
1150     /// Loads a value from the pointer.
1151     ///
1152     /// `load` takes an [`Ordering`] argument which describes the memory ordering
1153     /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
1154     ///
1155     /// # Panics
1156     ///
1157     /// Panics if `order` is [`Release`] or [`AcqRel`].
1158     ///
1159     /// # Examples
1160     ///
1161     /// ```
1162     /// use std::sync::atomic::{AtomicPtr, Ordering};
1163     ///
1164     /// let ptr = &mut 5;
1165     /// let some_ptr  = AtomicPtr::new(ptr);
1166     ///
1167     /// let value = some_ptr.load(Ordering::Relaxed);
1168     /// ```
1169     #[inline]
1170     #[stable(feature = "rust1", since = "1.0.0")]
1171     pub fn load(&self, order: Ordering) -> *mut T {
1172         // SAFETY: data races are prevented by atomic intrinsics.
1173         unsafe { atomic_load(self.p.get(), order) }
1174     }
1175
1176     /// Stores a value into the pointer.
1177     ///
1178     /// `store` takes an [`Ordering`] argument which describes the memory ordering
1179     /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
1180     ///
1181     /// # Panics
1182     ///
1183     /// Panics if `order` is [`Acquire`] or [`AcqRel`].
1184     ///
1185     /// # Examples
1186     ///
1187     /// ```
1188     /// use std::sync::atomic::{AtomicPtr, Ordering};
1189     ///
1190     /// let ptr = &mut 5;
1191     /// let some_ptr  = AtomicPtr::new(ptr);
1192     ///
1193     /// let other_ptr = &mut 10;
1194     ///
1195     /// some_ptr.store(other_ptr, Ordering::Relaxed);
1196     /// ```
1197     #[inline]
1198     #[stable(feature = "rust1", since = "1.0.0")]
1199     pub fn store(&self, ptr: *mut T, order: Ordering) {
1200         // SAFETY: data races are prevented by atomic intrinsics.
1201         unsafe {
1202             atomic_store(self.p.get(), ptr, order);
1203         }
1204     }
1205
1206     /// Stores a value into the pointer, returning the previous value.
1207     ///
1208     /// `swap` takes an [`Ordering`] argument which describes the memory ordering
1209     /// of this operation. All ordering modes are possible. Note that using
1210     /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1211     /// using [`Release`] makes the load part [`Relaxed`].
1212     ///
1213     /// **Note:** This method is only available on platforms that support atomic
1214     /// operations on pointers.
1215     ///
1216     /// # Examples
1217     ///
1218     /// ```
1219     /// use std::sync::atomic::{AtomicPtr, Ordering};
1220     ///
1221     /// let ptr = &mut 5;
1222     /// let some_ptr  = AtomicPtr::new(ptr);
1223     ///
1224     /// let other_ptr = &mut 10;
1225     ///
1226     /// let value = some_ptr.swap(other_ptr, Ordering::Relaxed);
1227     /// ```
1228     #[inline]
1229     #[stable(feature = "rust1", since = "1.0.0")]
1230     #[cfg(target_has_atomic = "ptr")]
1231     pub fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T {
1232         // SAFETY: data races are prevented by atomic intrinsics.
1233         unsafe { atomic_swap(self.p.get(), ptr, order) }
1234     }
1235
1236     /// Stores a value into the pointer if the current value is the same as the `current` value.
1237     ///
1238     /// The return value is always the previous value. If it is equal to `current`, then the value
1239     /// was updated.
1240     ///
1241     /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
1242     /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
1243     /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
1244     /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
1245     /// happens, and using [`Release`] makes the load part [`Relaxed`].
1246     ///
1247     /// **Note:** This method is only available on platforms that support atomic
1248     /// operations on pointers.
1249     ///
1250     /// # Migrating to `compare_exchange` and `compare_exchange_weak`
1251     ///
1252     /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
1253     /// memory orderings:
1254     ///
1255     /// Original | Success | Failure
1256     /// -------- | ------- | -------
1257     /// Relaxed  | Relaxed | Relaxed
1258     /// Acquire  | Acquire | Acquire
1259     /// Release  | Release | Relaxed
1260     /// AcqRel   | AcqRel  | Acquire
1261     /// SeqCst   | SeqCst  | SeqCst
1262     ///
1263     /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
1264     /// which allows the compiler to generate better assembly code when the compare and swap
1265     /// is used in a loop.
1266     ///
1267     /// # Examples
1268     ///
1269     /// ```
1270     /// use std::sync::atomic::{AtomicPtr, Ordering};
1271     ///
1272     /// let ptr = &mut 5;
1273     /// let some_ptr  = AtomicPtr::new(ptr);
1274     ///
1275     /// let other_ptr   = &mut 10;
1276     ///
1277     /// let value = some_ptr.compare_and_swap(ptr, other_ptr, Ordering::Relaxed);
1278     /// ```
1279     #[inline]
1280     #[stable(feature = "rust1", since = "1.0.0")]
1281     #[deprecated(
1282         since = "1.50.0",
1283         note = "Use `compare_exchange` or `compare_exchange_weak` instead"
1284     )]
1285     #[cfg(target_has_atomic = "ptr")]
1286     pub fn compare_and_swap(&self, current: *mut T, new: *mut T, order: Ordering) -> *mut T {
1287         match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
1288             Ok(x) => x,
1289             Err(x) => x,
1290         }
1291     }
1292
1293     /// Stores a value into the pointer if the current value is the same as the `current` value.
1294     ///
1295     /// The return value is a result indicating whether the new value was written and containing
1296     /// the previous value. On success this value is guaranteed to be equal to `current`.
1297     ///
1298     /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
1299     /// ordering of this operation. `success` describes the required ordering for the
1300     /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1301     /// `failure` describes the required ordering for the load operation that takes place when
1302     /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1303     /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1304     /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
1305     /// and must be equivalent to or weaker than the success ordering.
1306     ///
1307     /// **Note:** This method is only available on platforms that support atomic
1308     /// operations on pointers.
1309     ///
1310     /// # Examples
1311     ///
1312     /// ```
1313     /// use std::sync::atomic::{AtomicPtr, Ordering};
1314     ///
1315     /// let ptr = &mut 5;
1316     /// let some_ptr  = AtomicPtr::new(ptr);
1317     ///
1318     /// let other_ptr   = &mut 10;
1319     ///
1320     /// let value = some_ptr.compare_exchange(ptr, other_ptr,
1321     ///                                       Ordering::SeqCst, Ordering::Relaxed);
1322     /// ```
1323     #[inline]
1324     #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1325     #[cfg(target_has_atomic = "ptr")]
1326     pub fn compare_exchange(
1327         &self,
1328         current: *mut T,
1329         new: *mut T,
1330         success: Ordering,
1331         failure: Ordering,
1332     ) -> Result<*mut T, *mut T> {
1333         // SAFETY: data races are prevented by atomic intrinsics.
1334         unsafe { atomic_compare_exchange(self.p.get(), current, new, success, failure) }
1335     }
1336
1337     /// Stores a value into the pointer if the current value is the same as the `current` value.
1338     ///
1339     /// Unlike [`AtomicPtr::compare_exchange`], this function is allowed to spuriously fail even when the
1340     /// comparison succeeds, which can result in more efficient code on some platforms. The
1341     /// return value is a result indicating whether the new value was written and containing the
1342     /// previous value.
1343     ///
1344     /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
1345     /// ordering of this operation. `success` describes the required ordering for the
1346     /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1347     /// `failure` describes the required ordering for the load operation that takes place when
1348     /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1349     /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1350     /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
1351     /// and must be equivalent to or weaker than the success ordering.
1352     ///
1353     /// **Note:** This method is only available on platforms that support atomic
1354     /// operations on pointers.
1355     ///
1356     /// # Examples
1357     ///
1358     /// ```
1359     /// use std::sync::atomic::{AtomicPtr, Ordering};
1360     ///
1361     /// let some_ptr = AtomicPtr::new(&mut 5);
1362     ///
1363     /// let new = &mut 10;
1364     /// let mut old = some_ptr.load(Ordering::Relaxed);
1365     /// loop {
1366     ///     match some_ptr.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
1367     ///         Ok(_) => break,
1368     ///         Err(x) => old = x,
1369     ///     }
1370     /// }
1371     /// ```
1372     #[inline]
1373     #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1374     #[cfg(target_has_atomic = "ptr")]
1375     pub fn compare_exchange_weak(
1376         &self,
1377         current: *mut T,
1378         new: *mut T,
1379         success: Ordering,
1380         failure: Ordering,
1381     ) -> Result<*mut T, *mut T> {
1382         // SAFETY: This intrinsic is unsafe because it operates on a raw pointer
1383         // but we know for sure that the pointer is valid (we just got it from
1384         // an `UnsafeCell` that we have by reference) and the atomic operation
1385         // itself allows us to safely mutate the `UnsafeCell` contents.
1386         unsafe { atomic_compare_exchange_weak(self.p.get(), current, new, success, failure) }
1387     }
1388
1389     /// Fetches the value, and applies a function to it that returns an optional
1390     /// new value. Returns a `Result` of `Ok(previous_value)` if the function
1391     /// returned `Some(_)`, else `Err(previous_value)`.
1392     ///
1393     /// Note: This may call the function multiple times if the value has been
1394     /// changed from other threads in the meantime, as long as the function
1395     /// returns `Some(_)`, but the function will have been applied only once to
1396     /// the stored value.
1397     ///
1398     /// `fetch_update` takes two [`Ordering`] arguments to describe the memory
1399     /// ordering of this operation. The first describes the required ordering for
1400     /// when the operation finally succeeds while the second describes the
1401     /// required ordering for loads. These correspond to the success and failure
1402     /// orderings of [`AtomicPtr::compare_exchange`] respectively.
1403     ///
1404     /// Using [`Acquire`] as success ordering makes the store part of this
1405     /// operation [`Relaxed`], and using [`Release`] makes the final successful
1406     /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
1407     /// [`Acquire`] or [`Relaxed`] and must be equivalent to or weaker than the
1408     /// success ordering.
1409     ///
1410     /// **Note:** This method is only available on platforms that support atomic
1411     /// operations on pointers.
1412     ///
1413     /// # Examples
1414     ///
1415     /// ```rust
1416     /// use std::sync::atomic::{AtomicPtr, Ordering};
1417     ///
1418     /// let ptr: *mut _ = &mut 5;
1419     /// let some_ptr = AtomicPtr::new(ptr);
1420     ///
1421     /// let new: *mut _ = &mut 10;
1422     /// assert_eq!(some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr));
1423     /// let result = some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
1424     ///     if x == ptr {
1425     ///         Some(new)
1426     ///     } else {
1427     ///         None
1428     ///     }
1429     /// });
1430     /// assert_eq!(result, Ok(ptr));
1431     /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
1432     /// ```
1433     #[inline]
1434     #[stable(feature = "atomic_fetch_update", since = "1.53.0")]
1435     #[cfg(target_has_atomic = "ptr")]
1436     pub fn fetch_update<F>(
1437         &self,
1438         set_order: Ordering,
1439         fetch_order: Ordering,
1440         mut f: F,
1441     ) -> Result<*mut T, *mut T>
1442     where
1443         F: FnMut(*mut T) -> Option<*mut T>,
1444     {
1445         let mut prev = self.load(fetch_order);
1446         while let Some(next) = f(prev) {
1447             match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
1448                 x @ Ok(_) => return x,
1449                 Err(next_prev) => prev = next_prev,
1450             }
1451         }
1452         Err(prev)
1453     }
1454
1455     /// Offsets the pointer's address by adding `val` (in units of `T`),
1456     /// returning the previous pointer.
1457     ///
1458     /// This is equivalent to using [`wrapping_add`] to atomically perform the
1459     /// equivalent of `ptr = ptr.wrapping_add(val);`.
1460     ///
1461     /// This method operates in units of `T`, which means that it cannot be used
1462     /// to offset the pointer by an amount which is not a multiple of
1463     /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
1464     /// work with a deliberately misaligned pointer. In such cases, you may use
1465     /// the [`fetch_byte_add`](Self::fetch_byte_add) method instead.
1466     ///
1467     /// `fetch_ptr_add` takes an [`Ordering`] argument which describes the
1468     /// memory ordering of this operation. All ordering modes are possible. Note
1469     /// that using [`Acquire`] makes the store part of this operation
1470     /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
1471     ///
1472     /// **Note**: This method is only available on platforms that support atomic
1473     /// operations on [`AtomicPtr`].
1474     ///
1475     /// [`wrapping_add`]: pointer::wrapping_add
1476     ///
1477     /// # Examples
1478     ///
1479     /// ```
1480     /// #![feature(strict_provenance_atomic_ptr, strict_provenance)]
1481     /// use core::sync::atomic::{AtomicPtr, Ordering};
1482     ///
1483     /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
1484     /// assert_eq!(atom.fetch_ptr_add(1, Ordering::Relaxed).addr(), 0);
1485     /// // Note: units of `size_of::<i64>()`.
1486     /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 8);
1487     /// ```
1488     #[inline]
1489     #[cfg(target_has_atomic = "ptr")]
1490     #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1491     pub fn fetch_ptr_add(&self, val: usize, order: Ordering) -> *mut T {
1492         self.fetch_byte_add(val.wrapping_mul(core::mem::size_of::<T>()), order)
1493     }
1494
1495     /// Offsets the pointer's address by subtracting `val` (in units of `T`),
1496     /// returning the previous pointer.
1497     ///
1498     /// This is equivalent to using [`wrapping_sub`] to atomically perform the
1499     /// equivalent of `ptr = ptr.wrapping_sub(val);`.
1500     ///
1501     /// This method operates in units of `T`, which means that it cannot be used
1502     /// to offset the pointer by an amount which is not a multiple of
1503     /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
1504     /// work with a deliberately misaligned pointer. In such cases, you may use
1505     /// the [`fetch_byte_sub`](Self::fetch_byte_sub) method instead.
1506     ///
1507     /// `fetch_ptr_sub` takes an [`Ordering`] argument which describes the memory
1508     /// ordering of this operation. All ordering modes are possible. Note that
1509     /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
1510     /// and using [`Release`] makes the load part [`Relaxed`].
1511     ///
1512     /// **Note**: This method is only available on platforms that support atomic
1513     /// operations on [`AtomicPtr`].
1514     ///
1515     /// [`wrapping_sub`]: pointer::wrapping_sub
1516     ///
1517     /// # Examples
1518     ///
1519     /// ```
1520     /// #![feature(strict_provenance_atomic_ptr)]
1521     /// use core::sync::atomic::{AtomicPtr, Ordering};
1522     ///
1523     /// let array = [1i32, 2i32];
1524     /// let atom = AtomicPtr::new(array.as_ptr().wrapping_add(1) as *mut _);
1525     ///
1526     /// assert!(core::ptr::eq(
1527     ///     atom.fetch_ptr_sub(1, Ordering::Relaxed),
1528     ///     &array[1],
1529     /// ));
1530     /// assert!(core::ptr::eq(atom.load(Ordering::Relaxed), &array[0]));
1531     /// ```
1532     #[inline]
1533     #[cfg(target_has_atomic = "ptr")]
1534     #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1535     pub fn fetch_ptr_sub(&self, val: usize, order: Ordering) -> *mut T {
1536         self.fetch_byte_sub(val.wrapping_mul(core::mem::size_of::<T>()), order)
1537     }
1538
1539     /// Offsets the pointer's address by adding `val` *bytes*, returning the
1540     /// previous pointer.
1541     ///
1542     /// This is equivalent to using [`wrapping_add`] and [`cast`] to atomically
1543     /// perform `ptr = ptr.cast::<u8>().wrapping_add(val).cast::<T>()`.
1544     ///
1545     /// `fetch_byte_add` takes an [`Ordering`] argument which describes the
1546     /// memory ordering of this operation. All ordering modes are possible. Note
1547     /// that using [`Acquire`] makes the store part of this operation
1548     /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
1549     ///
1550     /// **Note**: This method is only available on platforms that support atomic
1551     /// operations on [`AtomicPtr`].
1552     ///
1553     /// [`wrapping_add`]: pointer::wrapping_add
1554     /// [`cast`]: pointer::cast
1555     ///
1556     /// # Examples
1557     ///
1558     /// ```
1559     /// #![feature(strict_provenance_atomic_ptr, strict_provenance)]
1560     /// use core::sync::atomic::{AtomicPtr, Ordering};
1561     ///
1562     /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
1563     /// assert_eq!(atom.fetch_byte_add(1, Ordering::Relaxed).addr(), 0);
1564     /// // Note: in units of bytes, not `size_of::<i64>()`.
1565     /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 1);
1566     /// ```
1567     #[inline]
1568     #[cfg(target_has_atomic = "ptr")]
1569     #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1570     pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T {
1571         #[cfg(not(bootstrap))]
1572         // SAFETY: data races are prevented by atomic intrinsics.
1573         unsafe {
1574             atomic_add(self.p.get(), core::ptr::invalid_mut(val), order).cast()
1575         }
1576         #[cfg(bootstrap)]
1577         // SAFETY: data races are prevented by atomic intrinsics.
1578         unsafe {
1579             atomic_add(self.p.get().cast::<usize>(), val, order) as *mut T
1580         }
1581     }
1582
1583     /// Offsets the pointer's address by subtracting `val` *bytes*, returning the
1584     /// previous pointer.
1585     ///
1586     /// This is equivalent to using [`wrapping_sub`] and [`cast`] to atomically
1587     /// perform `ptr = ptr.cast::<u8>().wrapping_sub(val).cast::<T>()`.
1588     ///
1589     /// `fetch_byte_sub` takes an [`Ordering`] argument which describes the
1590     /// memory ordering of this operation. All ordering modes are possible. Note
1591     /// that using [`Acquire`] makes the store part of this operation
1592     /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
1593     ///
1594     /// **Note**: This method is only available on platforms that support atomic
1595     /// operations on [`AtomicPtr`].
1596     ///
1597     /// [`wrapping_sub`]: pointer::wrapping_sub
1598     /// [`cast`]: pointer::cast
1599     ///
1600     /// # Examples
1601     ///
1602     /// ```
1603     /// #![feature(strict_provenance_atomic_ptr, strict_provenance)]
1604     /// use core::sync::atomic::{AtomicPtr, Ordering};
1605     ///
1606     /// let atom = AtomicPtr::<i64>::new(core::ptr::invalid_mut(1));
1607     /// assert_eq!(atom.fetch_byte_sub(1, Ordering::Relaxed).addr(), 1);
1608     /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 0);
1609     /// ```
1610     #[inline]
1611     #[cfg(target_has_atomic = "ptr")]
1612     #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1613     pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T {
1614         #[cfg(not(bootstrap))]
1615         // SAFETY: data races are prevented by atomic intrinsics.
1616         unsafe {
1617             atomic_sub(self.p.get(), core::ptr::invalid_mut(val), order).cast()
1618         }
1619         #[cfg(bootstrap)]
1620         // SAFETY: data races are prevented by atomic intrinsics.
1621         unsafe {
1622             atomic_sub(self.p.get().cast::<usize>(), val, order) as *mut T
1623         }
1624     }
1625
1626     /// Performs a bitwise "or" operation on the address of the current pointer,
1627     /// and the argument `val`, and stores a pointer with provenance of the
1628     /// current pointer and the resulting address.
1629     ///
1630     /// This is equivalent equivalent to using [`map_addr`] to atomically
1631     /// perform `ptr = ptr.map_addr(|a| a | val)`. This can be used in tagged
1632     /// pointer schemes to atomically set tag bits.
1633     ///
1634     /// **Caveat**: This operation returns the previous value. To compute the
1635     /// stored value without losing provenance, you may use [`map_addr`]. For
1636     /// example: `a.fetch_or(val).map_addr(|a| a | val)`.
1637     ///
1638     /// `fetch_or` takes an [`Ordering`] argument which describes the memory
1639     /// ordering of this operation. All ordering modes are possible. Note that
1640     /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
1641     /// and using [`Release`] makes the load part [`Relaxed`].
1642     ///
1643     /// **Note**: This method is only available on platforms that support atomic
1644     /// operations on [`AtomicPtr`].
1645     ///
1646     /// This API and its claimed semantics are part of the Strict Provenance
1647     /// experiment, see the [module documentation for `ptr`][crate::ptr] for
1648     /// details.
1649     ///
1650     /// [`map_addr`]: pointer::map_addr
1651     ///
1652     /// # Examples
1653     ///
1654     /// ```
1655     /// #![feature(strict_provenance_atomic_ptr, strict_provenance)]
1656     /// use core::sync::atomic::{AtomicPtr, Ordering};
1657     ///
1658     /// let pointer = &mut 3i64 as *mut i64;
1659     ///
1660     /// let atom = AtomicPtr::<i64>::new(pointer);
1661     /// // Tag the bottom bit of the pointer.
1662     /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 0);
1663     /// // Extract and untag.
1664     /// let tagged = atom.load(Ordering::Relaxed);
1665     /// assert_eq!(tagged.addr() & 1, 1);
1666     /// assert_eq!(tagged.map_addr(|p| p & !1), pointer);
1667     /// ```
1668     #[inline]
1669     #[cfg(target_has_atomic = "ptr")]
1670     #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1671     pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T {
1672         #[cfg(not(bootstrap))]
1673         // SAFETY: data races are prevented by atomic intrinsics.
1674         unsafe {
1675             atomic_or(self.p.get(), core::ptr::invalid_mut(val), order).cast()
1676         }
1677         #[cfg(bootstrap)]
1678         // SAFETY: data races are prevented by atomic intrinsics.
1679         unsafe {
1680             atomic_or(self.p.get().cast::<usize>(), val, order) as *mut T
1681         }
1682     }
1683
1684     /// Performs a bitwise "and" operation on the address of the current
1685     /// pointer, and the argument `val`, and stores a pointer with provenance of
1686     /// the current pointer and the resulting address.
1687     ///
1688     /// This is equivalent equivalent to using [`map_addr`] to atomically
1689     /// perform `ptr = ptr.map_addr(|a| a & val)`. This can be used in tagged
1690     /// pointer schemes to atomically unset tag bits.
1691     ///
1692     /// **Caveat**: This operation returns the previous value. To compute the
1693     /// stored value without losing provenance, you may use [`map_addr`]. For
1694     /// example: `a.fetch_and(val).map_addr(|a| a & val)`.
1695     ///
1696     /// `fetch_and` takes an [`Ordering`] argument which describes the memory
1697     /// ordering of this operation. All ordering modes are possible. Note that
1698     /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
1699     /// and using [`Release`] makes the load part [`Relaxed`].
1700     ///
1701     /// **Note**: This method is only available on platforms that support atomic
1702     /// operations on [`AtomicPtr`].
1703     ///
1704     /// This API and its claimed semantics are part of the Strict Provenance
1705     /// experiment, see the [module documentation for `ptr`][crate::ptr] for
1706     /// details.
1707     ///
1708     /// [`map_addr`]: pointer::map_addr
1709     ///
1710     /// # Examples
1711     ///
1712     /// ```
1713     /// #![feature(strict_provenance_atomic_ptr, strict_provenance)]
1714     /// use core::sync::atomic::{AtomicPtr, Ordering};
1715     ///
1716     /// let pointer = &mut 3i64 as *mut i64;
1717     /// // A tagged pointer
1718     /// let atom = AtomicPtr::<i64>::new(pointer.map_addr(|a| a | 1));
1719     /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 1);
1720     /// // Untag, and extract the previously tagged pointer.
1721     /// let untagged = atom.fetch_and(!1, Ordering::Relaxed)
1722     ///     .map_addr(|a| a & !1);
1723     /// assert_eq!(untagged, pointer);
1724     /// ```
1725     #[inline]
1726     #[cfg(target_has_atomic = "ptr")]
1727     #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1728     pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T {
1729         #[cfg(not(bootstrap))]
1730         // SAFETY: data races are prevented by atomic intrinsics.
1731         unsafe {
1732             atomic_and(self.p.get(), core::ptr::invalid_mut(val), order).cast()
1733         }
1734         #[cfg(bootstrap)]
1735         // SAFETY: data races are prevented by atomic intrinsics.
1736         unsafe {
1737             atomic_and(self.p.get().cast::<usize>(), val, order) as *mut T
1738         }
1739     }
1740
1741     /// Performs a bitwise "xor" operation on the address of the current
1742     /// pointer, and the argument `val`, and stores a pointer with provenance of
1743     /// the current pointer and the resulting address.
1744     ///
1745     /// This is equivalent equivalent to using [`map_addr`] to atomically
1746     /// perform `ptr = ptr.map_addr(|a| a ^ val)`. This can be used in tagged
1747     /// pointer schemes to atomically toggle tag bits.
1748     ///
1749     /// **Caveat**: This operation returns the previous value. To compute the
1750     /// stored value without losing provenance, you may use [`map_addr`]. For
1751     /// example: `a.fetch_xor(val).map_addr(|a| a ^ val)`.
1752     ///
1753     /// `fetch_xor` takes an [`Ordering`] argument which describes the memory
1754     /// ordering of this operation. All ordering modes are possible. Note that
1755     /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
1756     /// and using [`Release`] makes the load part [`Relaxed`].
1757     ///
1758     /// **Note**: This method is only available on platforms that support atomic
1759     /// operations on [`AtomicPtr`].
1760     ///
1761     /// This API and its claimed semantics are part of the Strict Provenance
1762     /// experiment, see the [module documentation for `ptr`][crate::ptr] for
1763     /// details.
1764     ///
1765     /// [`map_addr`]: pointer::map_addr
1766     ///
1767     /// # Examples
1768     ///
1769     /// ```
1770     /// #![feature(strict_provenance_atomic_ptr, strict_provenance)]
1771     /// use core::sync::atomic::{AtomicPtr, Ordering};
1772     ///
1773     /// let pointer = &mut 3i64 as *mut i64;
1774     /// let atom = AtomicPtr::<i64>::new(pointer);
1775     ///
1776     /// // Toggle a tag bit on the pointer.
1777     /// atom.fetch_xor(1, Ordering::Relaxed);
1778     /// assert_eq!(atom.load(Ordering::Relaxed).addr() & 1, 1);
1779     /// ```
1780     #[inline]
1781     #[cfg(target_has_atomic = "ptr")]
1782     #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1783     pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T {
1784         #[cfg(not(bootstrap))]
1785         // SAFETY: data races are prevented by atomic intrinsics.
1786         unsafe {
1787             atomic_xor(self.p.get(), core::ptr::invalid_mut(val), order).cast()
1788         }
1789         #[cfg(bootstrap)]
1790         // SAFETY: data races are prevented by atomic intrinsics.
1791         unsafe {
1792             atomic_xor(self.p.get().cast::<usize>(), val, order) as *mut T
1793         }
1794     }
1795 }
1796
1797 #[cfg(target_has_atomic_load_store = "8")]
1798 #[stable(feature = "atomic_bool_from", since = "1.24.0")]
1799 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
1800 impl const From<bool> for AtomicBool {
1801     /// Converts a `bool` into an `AtomicBool`.
1802     ///
1803     /// # Examples
1804     ///
1805     /// ```
1806     /// use std::sync::atomic::AtomicBool;
1807     /// let atomic_bool = AtomicBool::from(true);
1808     /// assert_eq!(format!("{atomic_bool:?}"), "true")
1809     /// ```
1810     #[inline]
1811     fn from(b: bool) -> Self {
1812         Self::new(b)
1813     }
1814 }
1815
1816 #[cfg(target_has_atomic_load_store = "ptr")]
1817 #[stable(feature = "atomic_from", since = "1.23.0")]
1818 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
1819 impl<T> const From<*mut T> for AtomicPtr<T> {
1820     /// Converts a `*mut T` into an `AtomicPtr<T>`.
1821     #[inline]
1822     fn from(p: *mut T) -> Self {
1823         Self::new(p)
1824     }
1825 }
1826
1827 #[allow(unused_macros)] // This macro ends up being unused on some architectures.
1828 macro_rules! if_not_8_bit {
1829     (u8, $($tt:tt)*) => { "" };
1830     (i8, $($tt:tt)*) => { "" };
1831     ($_:ident, $($tt:tt)*) => { $($tt)* };
1832 }
1833
1834 #[cfg(target_has_atomic_load_store = "8")]
1835 macro_rules! atomic_int {
1836     ($cfg_cas:meta,
1837      $cfg_align:meta,
1838      $stable:meta,
1839      $stable_cxchg:meta,
1840      $stable_debug:meta,
1841      $stable_access:meta,
1842      $stable_from:meta,
1843      $stable_nand:meta,
1844      $const_stable:meta,
1845      $stable_init_const:meta,
1846      $diagnostic_item:meta,
1847      $s_int_type:literal,
1848      $extra_feature:expr,
1849      $min_fn:ident, $max_fn:ident,
1850      $align:expr,
1851      $atomic_new:expr,
1852      $int_type:ident $atomic_type:ident $atomic_init:ident) => {
1853         /// An integer type which can be safely shared between threads.
1854         ///
1855         /// This type has the same in-memory representation as the underlying
1856         /// integer type, [`
1857         #[doc = $s_int_type]
1858         /// `]. For more about the differences between atomic types and
1859         /// non-atomic types as well as information about the portability of
1860         /// this type, please see the [module-level documentation].
1861         ///
1862         /// **Note:** This type is only available on platforms that support
1863         /// atomic loads and stores of [`
1864         #[doc = $s_int_type]
1865         /// `].
1866         ///
1867         /// [module-level documentation]: crate::sync::atomic
1868         #[$stable]
1869         #[$diagnostic_item]
1870         #[repr(C, align($align))]
1871         pub struct $atomic_type {
1872             v: UnsafeCell<$int_type>,
1873         }
1874
1875         /// An atomic integer initialized to `0`.
1876         #[$stable_init_const]
1877         #[deprecated(
1878             since = "1.34.0",
1879             note = "the `new` function is now preferred",
1880             suggestion = $atomic_new,
1881         )]
1882         pub const $atomic_init: $atomic_type = $atomic_type::new(0);
1883
1884         #[$stable]
1885         #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1886         impl const Default for $atomic_type {
1887             #[inline]
1888             fn default() -> Self {
1889                 Self::new(Default::default())
1890             }
1891         }
1892
1893         #[$stable_from]
1894         #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")]
1895         impl const From<$int_type> for $atomic_type {
1896             #[doc = concat!("Converts an `", stringify!($int_type), "` into an `", stringify!($atomic_type), "`.")]
1897             #[inline]
1898             fn from(v: $int_type) -> Self { Self::new(v) }
1899         }
1900
1901         #[$stable_debug]
1902         impl fmt::Debug for $atomic_type {
1903             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1904                 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
1905             }
1906         }
1907
1908         // Send is implicitly implemented.
1909         #[$stable]
1910         unsafe impl Sync for $atomic_type {}
1911
1912         impl $atomic_type {
1913             /// Creates a new atomic integer.
1914             ///
1915             /// # Examples
1916             ///
1917             /// ```
1918             #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
1919             ///
1920             #[doc = concat!("let atomic_forty_two = ", stringify!($atomic_type), "::new(42);")]
1921             /// ```
1922             #[inline]
1923             #[$stable]
1924             #[$const_stable]
1925             #[must_use]
1926             pub const fn new(v: $int_type) -> Self {
1927                 Self {v: UnsafeCell::new(v)}
1928             }
1929
1930             /// Returns a mutable reference to the underlying integer.
1931             ///
1932             /// This is safe because the mutable reference guarantees that no other threads are
1933             /// concurrently accessing the atomic data.
1934             ///
1935             /// # Examples
1936             ///
1937             /// ```
1938             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
1939             ///
1940             #[doc = concat!("let mut some_var = ", stringify!($atomic_type), "::new(10);")]
1941             /// assert_eq!(*some_var.get_mut(), 10);
1942             /// *some_var.get_mut() = 5;
1943             /// assert_eq!(some_var.load(Ordering::SeqCst), 5);
1944             /// ```
1945             #[inline]
1946             #[$stable_access]
1947             pub fn get_mut(&mut self) -> &mut $int_type {
1948                 self.v.get_mut()
1949             }
1950
1951             #[doc = concat!("Get atomic access to a `&mut ", stringify!($int_type), "`.")]
1952             ///
1953             #[doc = if_not_8_bit! {
1954                 $int_type,
1955                 concat!(
1956                     "**Note:** This function is only available on targets where `",
1957                     stringify!($int_type), "` has an alignment of ", $align, " bytes."
1958                 )
1959             }]
1960             ///
1961             /// # Examples
1962             ///
1963             /// ```
1964             /// #![feature(atomic_from_mut)]
1965             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
1966             ///
1967             /// let mut some_int = 123;
1968             #[doc = concat!("let a = ", stringify!($atomic_type), "::from_mut(&mut some_int);")]
1969             /// a.store(100, Ordering::Relaxed);
1970             /// assert_eq!(some_int, 100);
1971             /// ```
1972             ///
1973             #[inline]
1974             #[$cfg_align]
1975             #[unstable(feature = "atomic_from_mut", issue = "76314")]
1976             pub fn from_mut(v: &mut $int_type) -> &mut Self {
1977                 use crate::mem::align_of;
1978                 let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
1979                 // SAFETY:
1980                 //  - the mutable reference guarantees unique ownership.
1981                 //  - the alignment of `$int_type` and `Self` is the
1982                 //    same, as promised by $cfg_align and verified above.
1983                 unsafe { &mut *(v as *mut $int_type as *mut Self) }
1984             }
1985
1986             #[doc = concat!("Get non-atomic access to a `&mut [", stringify!($atomic_type), "]` slice")]
1987             ///
1988             /// This is safe because the mutable reference guarantees that no other threads are
1989             /// concurrently accessing the atomic data.
1990             ///
1991             /// # Examples
1992             ///
1993             /// ```
1994             /// #![feature(atomic_from_mut, inline_const)]
1995             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
1996             ///
1997             #[doc = concat!("let mut some_ints = [const { ", stringify!($atomic_type), "::new(0) }; 10];")]
1998             ///
1999             #[doc = concat!("let view: &mut [", stringify!($int_type), "] = ", stringify!($atomic_type), "::get_mut_slice(&mut some_ints);")]
2000             /// assert_eq!(view, [0; 10]);
2001             /// view
2002             ///     .iter_mut()
2003             ///     .enumerate()
2004             ///     .for_each(|(idx, int)| *int = idx as _);
2005             ///
2006             /// std::thread::scope(|s| {
2007             ///     some_ints
2008             ///         .iter()
2009             ///         .enumerate()
2010             ///         .for_each(|(idx, int)| {
2011             ///             s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
2012             ///         })
2013             /// });
2014             /// ```
2015             #[inline]
2016             #[unstable(feature = "atomic_from_mut", issue = "76314")]
2017             pub fn get_mut_slice(this: &mut [Self]) -> &mut [$int_type] {
2018                 // SAFETY: the mutable reference guarantees unique ownership.
2019                 unsafe { &mut *(this as *mut [Self] as *mut [$int_type]) }
2020             }
2021
2022             #[doc = concat!("Get atomic access to a `&mut [", stringify!($int_type), "]` slice.")]
2023             ///
2024             /// # Examples
2025             ///
2026             /// ```
2027             /// #![feature(atomic_from_mut)]
2028             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2029             ///
2030             /// let mut some_ints = [0; 10];
2031             #[doc = concat!("let a = &*", stringify!($atomic_type), "::from_mut_slice(&mut some_ints);")]
2032             /// std::thread::scope(|s| {
2033             ///     for i in 0..a.len() {
2034             ///         s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
2035             ///     }
2036             /// });
2037             /// for (i, n) in some_ints.into_iter().enumerate() {
2038             ///     assert_eq!(i, n as usize);
2039             /// }
2040             /// ```
2041             #[inline]
2042             #[$cfg_align]
2043             #[unstable(feature = "atomic_from_mut", issue = "76314")]
2044             pub fn from_mut_slice(v: &mut [$int_type]) -> &mut [Self] {
2045                 use crate::mem::align_of;
2046                 let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
2047                 // SAFETY:
2048                 //  - the mutable reference guarantees unique ownership.
2049                 //  - the alignment of `$int_type` and `Self` is the
2050                 //    same, as promised by $cfg_align and verified above.
2051                 unsafe { &mut *(v as *mut [$int_type] as *mut [Self]) }
2052             }
2053
2054             /// Consumes the atomic and returns the contained value.
2055             ///
2056             /// This is safe because passing `self` by value guarantees that no other threads are
2057             /// concurrently accessing the atomic data.
2058             ///
2059             /// # Examples
2060             ///
2061             /// ```
2062             #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2063             ///
2064             #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2065             /// assert_eq!(some_var.into_inner(), 5);
2066             /// ```
2067             #[inline]
2068             #[$stable_access]
2069             #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")]
2070             pub const fn into_inner(self) -> $int_type {
2071                 self.v.into_inner()
2072             }
2073
2074             /// Loads a value from the atomic integer.
2075             ///
2076             /// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2077             /// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
2078             ///
2079             /// # Panics
2080             ///
2081             /// Panics if `order` is [`Release`] or [`AcqRel`].
2082             ///
2083             /// # Examples
2084             ///
2085             /// ```
2086             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2087             ///
2088             #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2089             ///
2090             /// assert_eq!(some_var.load(Ordering::Relaxed), 5);
2091             /// ```
2092             #[inline]
2093             #[$stable]
2094             pub fn load(&self, order: Ordering) -> $int_type {
2095                 // SAFETY: data races are prevented by atomic intrinsics.
2096                 unsafe { atomic_load(self.v.get(), order) }
2097             }
2098
2099             /// Stores a value into the atomic integer.
2100             ///
2101             /// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2102             ///  Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
2103             ///
2104             /// # Panics
2105             ///
2106             /// Panics if `order` is [`Acquire`] or [`AcqRel`].
2107             ///
2108             /// # Examples
2109             ///
2110             /// ```
2111             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2112             ///
2113             #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2114             ///
2115             /// some_var.store(10, Ordering::Relaxed);
2116             /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2117             /// ```
2118             #[inline]
2119             #[$stable]
2120             pub fn store(&self, val: $int_type, order: Ordering) {
2121                 // SAFETY: data races are prevented by atomic intrinsics.
2122                 unsafe { atomic_store(self.v.get(), val, order); }
2123             }
2124
2125             /// Stores a value into the atomic integer, returning the previous value.
2126             ///
2127             /// `swap` takes an [`Ordering`] argument which describes the memory ordering
2128             /// of this operation. All ordering modes are possible. Note that using
2129             /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2130             /// using [`Release`] makes the load part [`Relaxed`].
2131             ///
2132             /// **Note**: This method is only available on platforms that support atomic operations on
2133             #[doc = concat!("[`", $s_int_type, "`].")]
2134             ///
2135             /// # Examples
2136             ///
2137             /// ```
2138             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2139             ///
2140             #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2141             ///
2142             /// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
2143             /// ```
2144             #[inline]
2145             #[$stable]
2146             #[$cfg_cas]
2147             pub fn swap(&self, val: $int_type, order: Ordering) -> $int_type {
2148                 // SAFETY: data races are prevented by atomic intrinsics.
2149                 unsafe { atomic_swap(self.v.get(), val, order) }
2150             }
2151
2152             /// Stores a value into the atomic integer if the current value is the same as
2153             /// the `current` value.
2154             ///
2155             /// The return value is always the previous value. If it is equal to `current`, then the
2156             /// value was updated.
2157             ///
2158             /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
2159             /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
2160             /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
2161             /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
2162             /// happens, and using [`Release`] makes the load part [`Relaxed`].
2163             ///
2164             /// **Note**: This method is only available on platforms that support atomic operations on
2165             #[doc = concat!("[`", $s_int_type, "`].")]
2166             ///
2167             /// # Migrating to `compare_exchange` and `compare_exchange_weak`
2168             ///
2169             /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
2170             /// memory orderings:
2171             ///
2172             /// Original | Success | Failure
2173             /// -------- | ------- | -------
2174             /// Relaxed  | Relaxed | Relaxed
2175             /// Acquire  | Acquire | Acquire
2176             /// Release  | Release | Relaxed
2177             /// AcqRel   | AcqRel  | Acquire
2178             /// SeqCst   | SeqCst  | SeqCst
2179             ///
2180             /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
2181             /// which allows the compiler to generate better assembly code when the compare and swap
2182             /// is used in a loop.
2183             ///
2184             /// # Examples
2185             ///
2186             /// ```
2187             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2188             ///
2189             #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2190             ///
2191             /// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
2192             /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2193             ///
2194             /// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
2195             /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2196             /// ```
2197             #[inline]
2198             #[$stable]
2199             #[deprecated(
2200                 since = "1.50.0",
2201                 note = "Use `compare_exchange` or `compare_exchange_weak` instead")
2202             ]
2203             #[$cfg_cas]
2204             pub fn compare_and_swap(&self,
2205                                     current: $int_type,
2206                                     new: $int_type,
2207                                     order: Ordering) -> $int_type {
2208                 match self.compare_exchange(current,
2209                                             new,
2210                                             order,
2211                                             strongest_failure_ordering(order)) {
2212                     Ok(x) => x,
2213                     Err(x) => x,
2214                 }
2215             }
2216
2217             /// Stores a value into the atomic integer if the current value is the same as
2218             /// the `current` value.
2219             ///
2220             /// The return value is a result indicating whether the new value was written and
2221             /// containing the previous value. On success this value is guaranteed to be equal to
2222             /// `current`.
2223             ///
2224             /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
2225             /// ordering of this operation. `success` describes the required ordering for the
2226             /// read-modify-write operation that takes place if the comparison with `current` succeeds.
2227             /// `failure` describes the required ordering for the load operation that takes place when
2228             /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
2229             /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
2230             /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
2231             /// and must be equivalent to or weaker than the success ordering.
2232             ///
2233             /// **Note**: This method is only available on platforms that support atomic operations on
2234             #[doc = concat!("[`", $s_int_type, "`].")]
2235             ///
2236             /// # Examples
2237             ///
2238             /// ```
2239             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2240             ///
2241             #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2242             ///
2243             /// assert_eq!(some_var.compare_exchange(5, 10,
2244             ///                                      Ordering::Acquire,
2245             ///                                      Ordering::Relaxed),
2246             ///            Ok(5));
2247             /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2248             ///
2249             /// assert_eq!(some_var.compare_exchange(6, 12,
2250             ///                                      Ordering::SeqCst,
2251             ///                                      Ordering::Acquire),
2252             ///            Err(10));
2253             /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2254             /// ```
2255             #[inline]
2256             #[$stable_cxchg]
2257             #[$cfg_cas]
2258             pub fn compare_exchange(&self,
2259                                     current: $int_type,
2260                                     new: $int_type,
2261                                     success: Ordering,
2262                                     failure: Ordering) -> Result<$int_type, $int_type> {
2263                 // SAFETY: data races are prevented by atomic intrinsics.
2264                 unsafe { atomic_compare_exchange(self.v.get(), current, new, success, failure) }
2265             }
2266
2267             /// Stores a value into the atomic integer if the current value is the same as
2268             /// the `current` value.
2269             ///
2270             #[doc = concat!("Unlike [`", stringify!($atomic_type), "::compare_exchange`],")]
2271             /// this function is allowed to spuriously fail even
2272             /// when the comparison succeeds, which can result in more efficient code on some
2273             /// platforms. The return value is a result indicating whether the new value was
2274             /// written and containing the previous value.
2275             ///
2276             /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
2277             /// ordering of this operation. `success` describes the required ordering for the
2278             /// read-modify-write operation that takes place if the comparison with `current` succeeds.
2279             /// `failure` describes the required ordering for the load operation that takes place when
2280             /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
2281             /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
2282             /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
2283             /// and must be equivalent to or weaker than the success ordering.
2284             ///
2285             /// **Note**: This method is only available on platforms that support atomic operations on
2286             #[doc = concat!("[`", $s_int_type, "`].")]
2287             ///
2288             /// # Examples
2289             ///
2290             /// ```
2291             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2292             ///
2293             #[doc = concat!("let val = ", stringify!($atomic_type), "::new(4);")]
2294             ///
2295             /// let mut old = val.load(Ordering::Relaxed);
2296             /// loop {
2297             ///     let new = old * 2;
2298             ///     match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
2299             ///         Ok(_) => break,
2300             ///         Err(x) => old = x,
2301             ///     }
2302             /// }
2303             /// ```
2304             #[inline]
2305             #[$stable_cxchg]
2306             #[$cfg_cas]
2307             pub fn compare_exchange_weak(&self,
2308                                          current: $int_type,
2309                                          new: $int_type,
2310                                          success: Ordering,
2311                                          failure: Ordering) -> Result<$int_type, $int_type> {
2312                 // SAFETY: data races are prevented by atomic intrinsics.
2313                 unsafe {
2314                     atomic_compare_exchange_weak(self.v.get(), current, new, success, failure)
2315                 }
2316             }
2317
2318             /// Adds to the current value, returning the previous value.
2319             ///
2320             /// This operation wraps around on overflow.
2321             ///
2322             /// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
2323             /// of this operation. All ordering modes are possible. Note that using
2324             /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2325             /// using [`Release`] makes the load part [`Relaxed`].
2326             ///
2327             /// **Note**: This method is only available on platforms that support atomic operations on
2328             #[doc = concat!("[`", $s_int_type, "`].")]
2329             ///
2330             /// # Examples
2331             ///
2332             /// ```
2333             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2334             ///
2335             #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0);")]
2336             /// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
2337             /// assert_eq!(foo.load(Ordering::SeqCst), 10);
2338             /// ```
2339             #[inline]
2340             #[$stable]
2341             #[$cfg_cas]
2342             pub fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type {
2343                 // SAFETY: data races are prevented by atomic intrinsics.
2344                 unsafe { atomic_add(self.v.get(), val, order) }
2345             }
2346
2347             /// Subtracts from the current value, returning the previous value.
2348             ///
2349             /// This operation wraps around on overflow.
2350             ///
2351             /// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
2352             /// of this operation. All ordering modes are possible. Note that using
2353             /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2354             /// using [`Release`] makes the load part [`Relaxed`].
2355             ///
2356             /// **Note**: This method is only available on platforms that support atomic operations on
2357             #[doc = concat!("[`", $s_int_type, "`].")]
2358             ///
2359             /// # Examples
2360             ///
2361             /// ```
2362             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2363             ///
2364             #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(20);")]
2365             /// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
2366             /// assert_eq!(foo.load(Ordering::SeqCst), 10);
2367             /// ```
2368             #[inline]
2369             #[$stable]
2370             #[$cfg_cas]
2371             pub fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type {
2372                 // SAFETY: data races are prevented by atomic intrinsics.
2373                 unsafe { atomic_sub(self.v.get(), val, order) }
2374             }
2375
2376             /// Bitwise "and" with the current value.
2377             ///
2378             /// Performs a bitwise "and" operation on the current value and the argument `val`, and
2379             /// sets the new value to the result.
2380             ///
2381             /// Returns the previous value.
2382             ///
2383             /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
2384             /// of this operation. All ordering modes are possible. Note that using
2385             /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2386             /// using [`Release`] makes the load part [`Relaxed`].
2387             ///
2388             /// **Note**: This method is only available on platforms that support atomic operations on
2389             #[doc = concat!("[`", $s_int_type, "`].")]
2390             ///
2391             /// # Examples
2392             ///
2393             /// ```
2394             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2395             ///
2396             #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
2397             /// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
2398             /// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
2399             /// ```
2400             #[inline]
2401             #[$stable]
2402             #[$cfg_cas]
2403             pub fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type {
2404                 // SAFETY: data races are prevented by atomic intrinsics.
2405                 unsafe { atomic_and(self.v.get(), val, order) }
2406             }
2407
2408             /// Bitwise "nand" with the current value.
2409             ///
2410             /// Performs a bitwise "nand" operation on the current value and the argument `val`, and
2411             /// sets the new value to the result.
2412             ///
2413             /// Returns the previous value.
2414             ///
2415             /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
2416             /// of this operation. All ordering modes are possible. Note that using
2417             /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2418             /// using [`Release`] makes the load part [`Relaxed`].
2419             ///
2420             /// **Note**: This method is only available on platforms that support atomic operations on
2421             #[doc = concat!("[`", $s_int_type, "`].")]
2422             ///
2423             /// # Examples
2424             ///
2425             /// ```
2426             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2427             ///
2428             #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0x13);")]
2429             /// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
2430             /// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
2431             /// ```
2432             #[inline]
2433             #[$stable_nand]
2434             #[$cfg_cas]
2435             pub fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type {
2436                 // SAFETY: data races are prevented by atomic intrinsics.
2437                 unsafe { atomic_nand(self.v.get(), val, order) }
2438             }
2439
2440             /// Bitwise "or" with the current value.
2441             ///
2442             /// Performs a bitwise "or" operation on the current value and the argument `val`, and
2443             /// sets the new value to the result.
2444             ///
2445             /// Returns the previous value.
2446             ///
2447             /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
2448             /// of this operation. All ordering modes are possible. Note that using
2449             /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2450             /// using [`Release`] makes the load part [`Relaxed`].
2451             ///
2452             /// **Note**: This method is only available on platforms that support atomic operations on
2453             #[doc = concat!("[`", $s_int_type, "`].")]
2454             ///
2455             /// # Examples
2456             ///
2457             /// ```
2458             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2459             ///
2460             #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
2461             /// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
2462             /// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
2463             /// ```
2464             #[inline]
2465             #[$stable]
2466             #[$cfg_cas]
2467             pub fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type {
2468                 // SAFETY: data races are prevented by atomic intrinsics.
2469                 unsafe { atomic_or(self.v.get(), val, order) }
2470             }
2471
2472             /// Bitwise "xor" with the current value.
2473             ///
2474             /// Performs a bitwise "xor" operation on the current value and the argument `val`, and
2475             /// sets the new value to the result.
2476             ///
2477             /// Returns the previous value.
2478             ///
2479             /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
2480             /// of this operation. All ordering modes are possible. Note that using
2481             /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2482             /// using [`Release`] makes the load part [`Relaxed`].
2483             ///
2484             /// **Note**: This method is only available on platforms that support atomic operations on
2485             #[doc = concat!("[`", $s_int_type, "`].")]
2486             ///
2487             /// # Examples
2488             ///
2489             /// ```
2490             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2491             ///
2492             #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
2493             /// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
2494             /// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
2495             /// ```
2496             #[inline]
2497             #[$stable]
2498             #[$cfg_cas]
2499             pub fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type {
2500                 // SAFETY: data races are prevented by atomic intrinsics.
2501                 unsafe { atomic_xor(self.v.get(), val, order) }
2502             }
2503
2504             /// Fetches the value, and applies a function to it that returns an optional
2505             /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
2506             /// `Err(previous_value)`.
2507             ///
2508             /// Note: This may call the function multiple times if the value has been changed from other threads in
2509             /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
2510             /// only once to the stored value.
2511             ///
2512             /// `fetch_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
2513             /// The first describes the required ordering for when the operation finally succeeds while the second
2514             /// describes the required ordering for loads. These correspond to the success and failure orderings of
2515             #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
2516             /// respectively.
2517             ///
2518             /// Using [`Acquire`] as success ordering makes the store part
2519             /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
2520             /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
2521             /// and must be equivalent to or weaker than the success ordering.
2522             ///
2523             /// **Note**: This method is only available on platforms that support atomic operations on
2524             #[doc = concat!("[`", $s_int_type, "`].")]
2525             ///
2526             /// # Examples
2527             ///
2528             /// ```rust
2529             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2530             ///
2531             #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
2532             /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
2533             /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
2534             /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
2535             /// assert_eq!(x.load(Ordering::SeqCst), 9);
2536             /// ```
2537             #[inline]
2538             #[stable(feature = "no_more_cas", since = "1.45.0")]
2539             #[$cfg_cas]
2540             pub fn fetch_update<F>(&self,
2541                                    set_order: Ordering,
2542                                    fetch_order: Ordering,
2543                                    mut f: F) -> Result<$int_type, $int_type>
2544             where F: FnMut($int_type) -> Option<$int_type> {
2545                 let mut prev = self.load(fetch_order);
2546                 while let Some(next) = f(prev) {
2547                     match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
2548                         x @ Ok(_) => return x,
2549                         Err(next_prev) => prev = next_prev
2550                     }
2551                 }
2552                 Err(prev)
2553             }
2554
2555             /// Maximum with the current value.
2556             ///
2557             /// Finds the maximum of the current value and the argument `val`, and
2558             /// sets the new value to the result.
2559             ///
2560             /// Returns the previous value.
2561             ///
2562             /// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
2563             /// of this operation. All ordering modes are possible. Note that using
2564             /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2565             /// using [`Release`] makes the load part [`Relaxed`].
2566             ///
2567             /// **Note**: This method is only available on platforms that support atomic operations on
2568             #[doc = concat!("[`", $s_int_type, "`].")]
2569             ///
2570             /// # Examples
2571             ///
2572             /// ```
2573             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2574             ///
2575             #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
2576             /// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
2577             /// assert_eq!(foo.load(Ordering::SeqCst), 42);
2578             /// ```
2579             ///
2580             /// If you want to obtain the maximum value in one step, you can use the following:
2581             ///
2582             /// ```
2583             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2584             ///
2585             #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
2586             /// let bar = 42;
2587             /// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
2588             /// assert!(max_foo == 42);
2589             /// ```
2590             #[inline]
2591             #[stable(feature = "atomic_min_max", since = "1.45.0")]
2592             #[$cfg_cas]
2593             pub fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type {
2594                 // SAFETY: data races are prevented by atomic intrinsics.
2595                 unsafe { $max_fn(self.v.get(), val, order) }
2596             }
2597
2598             /// Minimum with the current value.
2599             ///
2600             /// Finds the minimum of the current value and the argument `val`, and
2601             /// sets the new value to the result.
2602             ///
2603             /// Returns the previous value.
2604             ///
2605             /// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
2606             /// of this operation. All ordering modes are possible. Note that using
2607             /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2608             /// using [`Release`] makes the load part [`Relaxed`].
2609             ///
2610             /// **Note**: This method is only available on platforms that support atomic operations on
2611             #[doc = concat!("[`", $s_int_type, "`].")]
2612             ///
2613             /// # Examples
2614             ///
2615             /// ```
2616             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2617             ///
2618             #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
2619             /// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
2620             /// assert_eq!(foo.load(Ordering::Relaxed), 23);
2621             /// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
2622             /// assert_eq!(foo.load(Ordering::Relaxed), 22);
2623             /// ```
2624             ///
2625             /// If you want to obtain the minimum value in one step, you can use the following:
2626             ///
2627             /// ```
2628             #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2629             ///
2630             #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
2631             /// let bar = 12;
2632             /// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
2633             /// assert_eq!(min_foo, 12);
2634             /// ```
2635             #[inline]
2636             #[stable(feature = "atomic_min_max", since = "1.45.0")]
2637             #[$cfg_cas]
2638             pub fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type {
2639                 // SAFETY: data races are prevented by atomic intrinsics.
2640                 unsafe { $min_fn(self.v.get(), val, order) }
2641             }
2642
2643             /// Returns a mutable pointer to the underlying integer.
2644             ///
2645             /// Doing non-atomic reads and writes on the resulting integer can be a data race.
2646             /// This method is mostly useful for FFI, where the function signature may use
2647             #[doc = concat!("`*mut ", stringify!($int_type), "` instead of `&", stringify!($atomic_type), "`.")]
2648             ///
2649             /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
2650             /// atomic types work with interior mutability. All modifications of an atomic change the value
2651             /// through a shared reference, and can do so safely as long as they use atomic operations. Any
2652             /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the same
2653             /// restriction: operations on it must be atomic.
2654             ///
2655             /// # Examples
2656             ///
2657             /// ```ignore (extern-declaration)
2658             /// # fn main() {
2659             #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2660             ///
2661             /// extern "C" {
2662             #[doc = concat!("    fn my_atomic_op(arg: *mut ", stringify!($int_type), ");")]
2663             /// }
2664             ///
2665             #[doc = concat!("let mut atomic = ", stringify!($atomic_type), "::new(1);")]
2666             ///
2667             // SAFETY: Safe as long as `my_atomic_op` is atomic.
2668             /// unsafe {
2669             ///     my_atomic_op(atomic.as_mut_ptr());
2670             /// }
2671             /// # }
2672             /// ```
2673             #[inline]
2674             #[unstable(feature = "atomic_mut_ptr",
2675                    reason = "recently added",
2676                    issue = "66893")]
2677             pub fn as_mut_ptr(&self) -> *mut $int_type {
2678                 self.v.get()
2679             }
2680         }
2681     }
2682 }
2683
2684 #[cfg(target_has_atomic_load_store = "8")]
2685 atomic_int! {
2686     cfg(target_has_atomic = "8"),
2687     cfg(target_has_atomic_equal_alignment = "8"),
2688     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2689     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2690     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2691     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2692     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2693     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2694     rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2695     unstable(feature = "integer_atomics", issue = "99069"),
2696     cfg_attr(not(test), rustc_diagnostic_item = "AtomicI8"),
2697     "i8",
2698     "",
2699     atomic_min, atomic_max,
2700     1,
2701     "AtomicI8::new(0)",
2702     i8 AtomicI8 ATOMIC_I8_INIT
2703 }
2704 #[cfg(target_has_atomic_load_store = "8")]
2705 atomic_int! {
2706     cfg(target_has_atomic = "8"),
2707     cfg(target_has_atomic_equal_alignment = "8"),
2708     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2709     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2710     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2711     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2712     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2713     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2714     rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2715     unstable(feature = "integer_atomics", issue = "99069"),
2716     cfg_attr(not(test), rustc_diagnostic_item = "AtomicU8"),
2717     "u8",
2718     "",
2719     atomic_umin, atomic_umax,
2720     1,
2721     "AtomicU8::new(0)",
2722     u8 AtomicU8 ATOMIC_U8_INIT
2723 }
2724 #[cfg(target_has_atomic_load_store = "16")]
2725 atomic_int! {
2726     cfg(target_has_atomic = "16"),
2727     cfg(target_has_atomic_equal_alignment = "16"),
2728     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2729     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2730     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2731     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2732     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2733     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2734     rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2735     unstable(feature = "integer_atomics", issue = "99069"),
2736     cfg_attr(not(test), rustc_diagnostic_item = "AtomicI16"),
2737     "i16",
2738     "",
2739     atomic_min, atomic_max,
2740     2,
2741     "AtomicI16::new(0)",
2742     i16 AtomicI16 ATOMIC_I16_INIT
2743 }
2744 #[cfg(target_has_atomic_load_store = "16")]
2745 atomic_int! {
2746     cfg(target_has_atomic = "16"),
2747     cfg(target_has_atomic_equal_alignment = "16"),
2748     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2749     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2750     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2751     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2752     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2753     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2754     rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2755     unstable(feature = "integer_atomics", issue = "99069"),
2756     cfg_attr(not(test), rustc_diagnostic_item = "AtomicU16"),
2757     "u16",
2758     "",
2759     atomic_umin, atomic_umax,
2760     2,
2761     "AtomicU16::new(0)",
2762     u16 AtomicU16 ATOMIC_U16_INIT
2763 }
2764 #[cfg(target_has_atomic_load_store = "32")]
2765 atomic_int! {
2766     cfg(target_has_atomic = "32"),
2767     cfg(target_has_atomic_equal_alignment = "32"),
2768     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2769     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2770     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2771     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2772     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2773     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2774     rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2775     unstable(feature = "integer_atomics", issue = "99069"),
2776     cfg_attr(not(test), rustc_diagnostic_item = "AtomicI32"),
2777     "i32",
2778     "",
2779     atomic_min, atomic_max,
2780     4,
2781     "AtomicI32::new(0)",
2782     i32 AtomicI32 ATOMIC_I32_INIT
2783 }
2784 #[cfg(target_has_atomic_load_store = "32")]
2785 atomic_int! {
2786     cfg(target_has_atomic = "32"),
2787     cfg(target_has_atomic_equal_alignment = "32"),
2788     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2789     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2790     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2791     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2792     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2793     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2794     rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2795     unstable(feature = "integer_atomics", issue = "99069"),
2796     cfg_attr(not(test), rustc_diagnostic_item = "AtomicU32"),
2797     "u32",
2798     "",
2799     atomic_umin, atomic_umax,
2800     4,
2801     "AtomicU32::new(0)",
2802     u32 AtomicU32 ATOMIC_U32_INIT
2803 }
2804 #[cfg(target_has_atomic_load_store = "64")]
2805 atomic_int! {
2806     cfg(target_has_atomic = "64"),
2807     cfg(target_has_atomic_equal_alignment = "64"),
2808     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2809     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2810     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2811     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2812     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2813     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2814     rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2815     unstable(feature = "integer_atomics", issue = "99069"),
2816     cfg_attr(not(test), rustc_diagnostic_item = "AtomicI64"),
2817     "i64",
2818     "",
2819     atomic_min, atomic_max,
2820     8,
2821     "AtomicI64::new(0)",
2822     i64 AtomicI64 ATOMIC_I64_INIT
2823 }
2824 #[cfg(target_has_atomic_load_store = "64")]
2825 atomic_int! {
2826     cfg(target_has_atomic = "64"),
2827     cfg(target_has_atomic_equal_alignment = "64"),
2828     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2829     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2830     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2831     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2832     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2833     stable(feature = "integer_atomics_stable", since = "1.34.0"),
2834     rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2835     unstable(feature = "integer_atomics", issue = "99069"),
2836     cfg_attr(not(test), rustc_diagnostic_item = "AtomicU64"),
2837     "u64",
2838     "",
2839     atomic_umin, atomic_umax,
2840     8,
2841     "AtomicU64::new(0)",
2842     u64 AtomicU64 ATOMIC_U64_INIT
2843 }
2844 #[cfg(target_has_atomic_load_store = "128")]
2845 atomic_int! {
2846     cfg(target_has_atomic = "128"),
2847     cfg(target_has_atomic_equal_alignment = "128"),
2848     unstable(feature = "integer_atomics", issue = "99069"),
2849     unstable(feature = "integer_atomics", issue = "99069"),
2850     unstable(feature = "integer_atomics", issue = "99069"),
2851     unstable(feature = "integer_atomics", issue = "99069"),
2852     unstable(feature = "integer_atomics", issue = "99069"),
2853     unstable(feature = "integer_atomics", issue = "99069"),
2854     rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2855     unstable(feature = "integer_atomics", issue = "99069"),
2856     cfg_attr(not(test), rustc_diagnostic_item = "AtomicI128"),
2857     "i128",
2858     "#![feature(integer_atomics)]\n\n",
2859     atomic_min, atomic_max,
2860     16,
2861     "AtomicI128::new(0)",
2862     i128 AtomicI128 ATOMIC_I128_INIT
2863 }
2864 #[cfg(target_has_atomic_load_store = "128")]
2865 atomic_int! {
2866     cfg(target_has_atomic = "128"),
2867     cfg(target_has_atomic_equal_alignment = "128"),
2868     unstable(feature = "integer_atomics", issue = "99069"),
2869     unstable(feature = "integer_atomics", issue = "99069"),
2870     unstable(feature = "integer_atomics", issue = "99069"),
2871     unstable(feature = "integer_atomics", issue = "99069"),
2872     unstable(feature = "integer_atomics", issue = "99069"),
2873     unstable(feature = "integer_atomics", issue = "99069"),
2874     rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2875     unstable(feature = "integer_atomics", issue = "99069"),
2876     cfg_attr(not(test), rustc_diagnostic_item = "AtomicU128"),
2877     "u128",
2878     "#![feature(integer_atomics)]\n\n",
2879     atomic_umin, atomic_umax,
2880     16,
2881     "AtomicU128::new(0)",
2882     u128 AtomicU128 ATOMIC_U128_INIT
2883 }
2884
2885 macro_rules! atomic_int_ptr_sized {
2886     ( $($target_pointer_width:literal $align:literal)* ) => { $(
2887         #[cfg(target_has_atomic_load_store = "ptr")]
2888         #[cfg(target_pointer_width = $target_pointer_width)]
2889         atomic_int! {
2890             cfg(target_has_atomic = "ptr"),
2891             cfg(target_has_atomic_equal_alignment = "ptr"),
2892             stable(feature = "rust1", since = "1.0.0"),
2893             stable(feature = "extended_compare_and_swap", since = "1.10.0"),
2894             stable(feature = "atomic_debug", since = "1.3.0"),
2895             stable(feature = "atomic_access", since = "1.15.0"),
2896             stable(feature = "atomic_from", since = "1.23.0"),
2897             stable(feature = "atomic_nand", since = "1.27.0"),
2898             rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
2899             stable(feature = "rust1", since = "1.0.0"),
2900             cfg_attr(not(test), rustc_diagnostic_item = "AtomicIsize"),
2901             "isize",
2902             "",
2903             atomic_min, atomic_max,
2904             $align,
2905             "AtomicIsize::new(0)",
2906             isize AtomicIsize ATOMIC_ISIZE_INIT
2907         }
2908         #[cfg(target_has_atomic_load_store = "ptr")]
2909         #[cfg(target_pointer_width = $target_pointer_width)]
2910         atomic_int! {
2911             cfg(target_has_atomic = "ptr"),
2912             cfg(target_has_atomic_equal_alignment = "ptr"),
2913             stable(feature = "rust1", since = "1.0.0"),
2914             stable(feature = "extended_compare_and_swap", since = "1.10.0"),
2915             stable(feature = "atomic_debug", since = "1.3.0"),
2916             stable(feature = "atomic_access", since = "1.15.0"),
2917             stable(feature = "atomic_from", since = "1.23.0"),
2918             stable(feature = "atomic_nand", since = "1.27.0"),
2919             rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
2920             stable(feature = "rust1", since = "1.0.0"),
2921             cfg_attr(not(test), rustc_diagnostic_item = "AtomicUsize"),
2922             "usize",
2923             "",
2924             atomic_umin, atomic_umax,
2925             $align,
2926             "AtomicUsize::new(0)",
2927             usize AtomicUsize ATOMIC_USIZE_INIT
2928         }
2929     )* };
2930 }
2931
2932 atomic_int_ptr_sized! {
2933     "16" 2
2934     "32" 4
2935     "64" 8
2936 }
2937
2938 #[inline]
2939 #[cfg(target_has_atomic = "8")]
2940 fn strongest_failure_ordering(order: Ordering) -> Ordering {
2941     match order {
2942         Release => Relaxed,
2943         Relaxed => Relaxed,
2944         SeqCst => SeqCst,
2945         Acquire => Acquire,
2946         AcqRel => Acquire,
2947     }
2948 }
2949
2950 #[inline]
2951 unsafe fn atomic_store<T: Copy>(dst: *mut T, val: T, order: Ordering) {
2952     // SAFETY: the caller must uphold the safety contract for `atomic_store`.
2953     unsafe {
2954         match order {
2955             Relaxed => intrinsics::atomic_store_relaxed(dst, val),
2956             Release => intrinsics::atomic_store_release(dst, val),
2957             SeqCst => intrinsics::atomic_store_seqcst(dst, val),
2958             Acquire => panic!("there is no such thing as an acquire store"),
2959             AcqRel => panic!("there is no such thing as an acquire-release store"),
2960         }
2961     }
2962 }
2963
2964 #[inline]
2965 unsafe fn atomic_load<T: Copy>(dst: *const T, order: Ordering) -> T {
2966     // SAFETY: the caller must uphold the safety contract for `atomic_load`.
2967     unsafe {
2968         match order {
2969             Relaxed => intrinsics::atomic_load_relaxed(dst),
2970             Acquire => intrinsics::atomic_load_acquire(dst),
2971             SeqCst => intrinsics::atomic_load_seqcst(dst),
2972             Release => panic!("there is no such thing as a release load"),
2973             AcqRel => panic!("there is no such thing as an acquire-release load"),
2974         }
2975     }
2976 }
2977
2978 #[inline]
2979 #[cfg(target_has_atomic = "8")]
2980 unsafe fn atomic_swap<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
2981     // SAFETY: the caller must uphold the safety contract for `atomic_swap`.
2982     unsafe {
2983         match order {
2984             Relaxed => intrinsics::atomic_xchg_relaxed(dst, val),
2985             Acquire => intrinsics::atomic_xchg_acquire(dst, val),
2986             Release => intrinsics::atomic_xchg_release(dst, val),
2987             AcqRel => intrinsics::atomic_xchg_acqrel(dst, val),
2988             SeqCst => intrinsics::atomic_xchg_seqcst(dst, val),
2989         }
2990     }
2991 }
2992
2993 /// Returns the previous value (like __sync_fetch_and_add).
2994 #[inline]
2995 #[cfg(target_has_atomic = "8")]
2996 unsafe fn atomic_add<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
2997     // SAFETY: the caller must uphold the safety contract for `atomic_add`.
2998     unsafe {
2999         match order {
3000             Relaxed => intrinsics::atomic_xadd_relaxed(dst, val),
3001             Acquire => intrinsics::atomic_xadd_acquire(dst, val),
3002             Release => intrinsics::atomic_xadd_release(dst, val),
3003             AcqRel => intrinsics::atomic_xadd_acqrel(dst, val),
3004             SeqCst => intrinsics::atomic_xadd_seqcst(dst, val),
3005         }
3006     }
3007 }
3008
3009 /// Returns the previous value (like __sync_fetch_and_sub).
3010 #[inline]
3011 #[cfg(target_has_atomic = "8")]
3012 unsafe fn atomic_sub<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3013     // SAFETY: the caller must uphold the safety contract for `atomic_sub`.
3014     unsafe {
3015         match order {
3016             Relaxed => intrinsics::atomic_xsub_relaxed(dst, val),
3017             Acquire => intrinsics::atomic_xsub_acquire(dst, val),
3018             Release => intrinsics::atomic_xsub_release(dst, val),
3019             AcqRel => intrinsics::atomic_xsub_acqrel(dst, val),
3020             SeqCst => intrinsics::atomic_xsub_seqcst(dst, val),
3021         }
3022     }
3023 }
3024
3025 #[inline]
3026 #[cfg(target_has_atomic = "8")]
3027 unsafe fn atomic_compare_exchange<T: Copy>(
3028     dst: *mut T,
3029     old: T,
3030     new: T,
3031     success: Ordering,
3032     failure: Ordering,
3033 ) -> Result<T, T> {
3034     // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`.
3035     let (val, ok) = unsafe {
3036         match (success, failure) {
3037             (Relaxed, Relaxed) => intrinsics::atomic_cxchg_relaxed_relaxed(dst, old, new),
3038             //(Relaxed, Acquire) => intrinsics::atomic_cxchg_relaxed_acquire(dst, old, new),
3039             //(Relaxed, SeqCst) => intrinsics::atomic_cxchg_relaxed_seqcst(dst, old, new),
3040             (Acquire, Relaxed) => intrinsics::atomic_cxchg_acquire_relaxed(dst, old, new),
3041             (Acquire, Acquire) => intrinsics::atomic_cxchg_acquire_acquire(dst, old, new),
3042             //(Acquire, SeqCst) => intrinsics::atomic_cxchg_acquire_seqcst(dst, old, new),
3043             (Release, Relaxed) => intrinsics::atomic_cxchg_release_relaxed(dst, old, new),
3044             //(Release, Acquire) => intrinsics::atomic_cxchg_release_acquire(dst, old, new),
3045             //(Release, SeqCst) => intrinsics::atomic_cxchg_release_seqcst(dst, old, new),
3046             (AcqRel, Relaxed) => intrinsics::atomic_cxchg_acqrel_relaxed(dst, old, new),
3047             (AcqRel, Acquire) => intrinsics::atomic_cxchg_acqrel_acquire(dst, old, new),
3048             //(AcqRel, SeqCst) => intrinsics::atomic_cxchg_acqrel_seqcst(dst, old, new),
3049             (SeqCst, Relaxed) => intrinsics::atomic_cxchg_seqcst_relaxed(dst, old, new),
3050             (SeqCst, Acquire) => intrinsics::atomic_cxchg_seqcst_acquire(dst, old, new),
3051             (SeqCst, SeqCst) => intrinsics::atomic_cxchg_seqcst_seqcst(dst, old, new),
3052             (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
3053             (_, Release) => panic!("there is no such thing as a release failure ordering"),
3054             _ => panic!("a failure ordering can't be stronger than a success ordering"),
3055         }
3056     };
3057     if ok { Ok(val) } else { Err(val) }
3058 }
3059
3060 #[inline]
3061 #[cfg(target_has_atomic = "8")]
3062 unsafe fn atomic_compare_exchange_weak<T: Copy>(
3063     dst: *mut T,
3064     old: T,
3065     new: T,
3066     success: Ordering,
3067     failure: Ordering,
3068 ) -> Result<T, T> {
3069     // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`.
3070     let (val, ok) = unsafe {
3071         match (success, failure) {
3072             (Relaxed, Relaxed) => intrinsics::atomic_cxchgweak_relaxed_relaxed(dst, old, new),
3073             //(Relaxed, Acquire) => intrinsics::atomic_cxchgweak_relaxed_acquire(dst, old, new),
3074             //(Relaxed, SeqCst) => intrinsics::atomic_cxchgweak_relaxed_seqcst(dst, old, new),
3075             (Acquire, Relaxed) => intrinsics::atomic_cxchgweak_acquire_relaxed(dst, old, new),
3076             (Acquire, Acquire) => intrinsics::atomic_cxchgweak_acquire_acquire(dst, old, new),
3077             //(Acquire, SeqCst) => intrinsics::atomic_cxchgweak_acquire_seqcst(dst, old, new),
3078             (Release, Relaxed) => intrinsics::atomic_cxchgweak_release_relaxed(dst, old, new),
3079             //(Release, Acquire) => intrinsics::atomic_cxchgweak_release_acquire(dst, old, new),
3080             //(Release, SeqCst) => intrinsics::atomic_cxchgweak_release_seqcst(dst, old, new),
3081             (AcqRel, Relaxed) => intrinsics::atomic_cxchgweak_acqrel_relaxed(dst, old, new),
3082             (AcqRel, Acquire) => intrinsics::atomic_cxchgweak_acqrel_acquire(dst, old, new),
3083             //(AcqRel, SeqCst) => intrinsics::atomic_cxchgweak_acqrel_seqcst(dst, old, new),
3084             (SeqCst, Relaxed) => intrinsics::atomic_cxchgweak_seqcst_relaxed(dst, old, new),
3085             (SeqCst, Acquire) => intrinsics::atomic_cxchgweak_seqcst_acquire(dst, old, new),
3086             (SeqCst, SeqCst) => intrinsics::atomic_cxchgweak_seqcst_seqcst(dst, old, new),
3087             (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
3088             (_, Release) => panic!("there is no such thing as a release failure ordering"),
3089             _ => panic!("a failure ordering can't be stronger than a success ordering"),
3090         }
3091     };
3092     if ok { Ok(val) } else { Err(val) }
3093 }
3094
3095 #[inline]
3096 #[cfg(target_has_atomic = "8")]
3097 unsafe fn atomic_and<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3098     // SAFETY: the caller must uphold the safety contract for `atomic_and`
3099     unsafe {
3100         match order {
3101             Relaxed => intrinsics::atomic_and_relaxed(dst, val),
3102             Acquire => intrinsics::atomic_and_acquire(dst, val),
3103             Release => intrinsics::atomic_and_release(dst, val),
3104             AcqRel => intrinsics::atomic_and_acqrel(dst, val),
3105             SeqCst => intrinsics::atomic_and_seqcst(dst, val),
3106         }
3107     }
3108 }
3109
3110 #[inline]
3111 #[cfg(target_has_atomic = "8")]
3112 unsafe fn atomic_nand<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3113     // SAFETY: the caller must uphold the safety contract for `atomic_nand`
3114     unsafe {
3115         match order {
3116             Relaxed => intrinsics::atomic_nand_relaxed(dst, val),
3117             Acquire => intrinsics::atomic_nand_acquire(dst, val),
3118             Release => intrinsics::atomic_nand_release(dst, val),
3119             AcqRel => intrinsics::atomic_nand_acqrel(dst, val),
3120             SeqCst => intrinsics::atomic_nand_seqcst(dst, val),
3121         }
3122     }
3123 }
3124
3125 #[inline]
3126 #[cfg(target_has_atomic = "8")]
3127 unsafe fn atomic_or<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3128     // SAFETY: the caller must uphold the safety contract for `atomic_or`
3129     unsafe {
3130         match order {
3131             SeqCst => intrinsics::atomic_or_seqcst(dst, val),
3132             Acquire => intrinsics::atomic_or_acquire(dst, val),
3133             Release => intrinsics::atomic_or_release(dst, val),
3134             AcqRel => intrinsics::atomic_or_acqrel(dst, val),
3135             Relaxed => intrinsics::atomic_or_relaxed(dst, val),
3136         }
3137     }
3138 }
3139
3140 #[inline]
3141 #[cfg(target_has_atomic = "8")]
3142 unsafe fn atomic_xor<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3143     // SAFETY: the caller must uphold the safety contract for `atomic_xor`
3144     unsafe {
3145         match order {
3146             SeqCst => intrinsics::atomic_xor_seqcst(dst, val),
3147             Acquire => intrinsics::atomic_xor_acquire(dst, val),
3148             Release => intrinsics::atomic_xor_release(dst, val),
3149             AcqRel => intrinsics::atomic_xor_acqrel(dst, val),
3150             Relaxed => intrinsics::atomic_xor_relaxed(dst, val),
3151         }
3152     }
3153 }
3154
3155 /// returns the max value (signed comparison)
3156 #[inline]
3157 #[cfg(target_has_atomic = "8")]
3158 unsafe fn atomic_max<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3159     // SAFETY: the caller must uphold the safety contract for `atomic_max`
3160     unsafe {
3161         match order {
3162             Relaxed => intrinsics::atomic_max_relaxed(dst, val),
3163             Acquire => intrinsics::atomic_max_acquire(dst, val),
3164             Release => intrinsics::atomic_max_release(dst, val),
3165             AcqRel => intrinsics::atomic_max_acqrel(dst, val),
3166             SeqCst => intrinsics::atomic_max_seqcst(dst, val),
3167         }
3168     }
3169 }
3170
3171 /// returns the min value (signed comparison)
3172 #[inline]
3173 #[cfg(target_has_atomic = "8")]
3174 unsafe fn atomic_min<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3175     // SAFETY: the caller must uphold the safety contract for `atomic_min`
3176     unsafe {
3177         match order {
3178             Relaxed => intrinsics::atomic_min_relaxed(dst, val),
3179             Acquire => intrinsics::atomic_min_acquire(dst, val),
3180             Release => intrinsics::atomic_min_release(dst, val),
3181             AcqRel => intrinsics::atomic_min_acqrel(dst, val),
3182             SeqCst => intrinsics::atomic_min_seqcst(dst, val),
3183         }
3184     }
3185 }
3186
3187 /// returns the max value (unsigned comparison)
3188 #[inline]
3189 #[cfg(target_has_atomic = "8")]
3190 unsafe fn atomic_umax<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3191     // SAFETY: the caller must uphold the safety contract for `atomic_umax`
3192     unsafe {
3193         match order {
3194             Relaxed => intrinsics::atomic_umax_relaxed(dst, val),
3195             Acquire => intrinsics::atomic_umax_acquire(dst, val),
3196             Release => intrinsics::atomic_umax_release(dst, val),
3197             AcqRel => intrinsics::atomic_umax_acqrel(dst, val),
3198             SeqCst => intrinsics::atomic_umax_seqcst(dst, val),
3199         }
3200     }
3201 }
3202
3203 /// returns the min value (unsigned comparison)
3204 #[inline]
3205 #[cfg(target_has_atomic = "8")]
3206 unsafe fn atomic_umin<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3207     // SAFETY: the caller must uphold the safety contract for `atomic_umin`
3208     unsafe {
3209         match order {
3210             Relaxed => intrinsics::atomic_umin_relaxed(dst, val),
3211             Acquire => intrinsics::atomic_umin_acquire(dst, val),
3212             Release => intrinsics::atomic_umin_release(dst, val),
3213             AcqRel => intrinsics::atomic_umin_acqrel(dst, val),
3214             SeqCst => intrinsics::atomic_umin_seqcst(dst, val),
3215         }
3216     }
3217 }
3218
3219 /// An atomic fence.
3220 ///
3221 /// Depending on the specified order, a fence prevents the compiler and CPU from
3222 /// reordering certain types of memory operations around it.
3223 /// That creates synchronizes-with relationships between it and atomic operations
3224 /// or fences in other threads.
3225 ///
3226 /// A fence 'A' which has (at least) [`Release`] ordering semantics, synchronizes
3227 /// with a fence 'B' with (at least) [`Acquire`] semantics, if and only if there
3228 /// exist operations X and Y, both operating on some atomic object 'M' such
3229 /// that A is sequenced before X, Y is sequenced before B and Y observes
3230 /// the change to M. This provides a happens-before dependence between A and B.
3231 ///
3232 /// ```text
3233 ///     Thread 1                                          Thread 2
3234 ///
3235 /// fence(Release);      A --------------
3236 /// x.store(3, Relaxed); X ---------    |
3237 ///                                |    |
3238 ///                                |    |
3239 ///                                -------------> Y  if x.load(Relaxed) == 3 {
3240 ///                                     |-------> B      fence(Acquire);
3241 ///                                                      ...
3242 ///                                                  }
3243 /// ```
3244 ///
3245 /// Atomic operations with [`Release`] or [`Acquire`] semantics can also synchronize
3246 /// with a fence.
3247 ///
3248 /// A fence which has [`SeqCst`] ordering, in addition to having both [`Acquire`]
3249 /// and [`Release`] semantics, participates in the global program order of the
3250 /// other [`SeqCst`] operations and/or fences.
3251 ///
3252 /// Accepts [`Acquire`], [`Release`], [`AcqRel`] and [`SeqCst`] orderings.
3253 ///
3254 /// # Panics
3255 ///
3256 /// Panics if `order` is [`Relaxed`].
3257 ///
3258 /// # Examples
3259 ///
3260 /// ```
3261 /// use std::sync::atomic::AtomicBool;
3262 /// use std::sync::atomic::fence;
3263 /// use std::sync::atomic::Ordering;
3264 ///
3265 /// // A mutual exclusion primitive based on spinlock.
3266 /// pub struct Mutex {
3267 ///     flag: AtomicBool,
3268 /// }
3269 ///
3270 /// impl Mutex {
3271 ///     pub fn new() -> Mutex {
3272 ///         Mutex {
3273 ///             flag: AtomicBool::new(false),
3274 ///         }
3275 ///     }
3276 ///
3277 ///     pub fn lock(&self) {
3278 ///         // Wait until the old value is `false`.
3279 ///         while self
3280 ///             .flag
3281 ///             .compare_exchange_weak(false, true, Ordering::Relaxed, Ordering::Relaxed)
3282 ///             .is_err()
3283 ///         {}
3284 ///         // This fence synchronizes-with store in `unlock`.
3285 ///         fence(Ordering::Acquire);
3286 ///     }
3287 ///
3288 ///     pub fn unlock(&self) {
3289 ///         self.flag.store(false, Ordering::Release);
3290 ///     }
3291 /// }
3292 /// ```
3293 #[inline]
3294 #[stable(feature = "rust1", since = "1.0.0")]
3295 #[rustc_diagnostic_item = "fence"]
3296 pub fn fence(order: Ordering) {
3297     // SAFETY: using an atomic fence is safe.
3298     unsafe {
3299         match order {
3300             Acquire => intrinsics::atomic_fence_acquire(),
3301             Release => intrinsics::atomic_fence_release(),
3302             AcqRel => intrinsics::atomic_fence_acqrel(),
3303             SeqCst => intrinsics::atomic_fence_seqcst(),
3304             Relaxed => panic!("there is no such thing as a relaxed fence"),
3305         }
3306     }
3307 }
3308
3309 /// A compiler memory fence.
3310 ///
3311 /// `compiler_fence` does not emit any machine code, but restricts the kinds
3312 /// of memory re-ordering the compiler is allowed to do. Specifically, depending on
3313 /// the given [`Ordering`] semantics, the compiler may be disallowed from moving reads
3314 /// or writes from before or after the call to the other side of the call to
3315 /// `compiler_fence`. Note that it does **not** prevent the *hardware*
3316 /// from doing such re-ordering. This is not a problem in a single-threaded,
3317 /// execution context, but when other threads may modify memory at the same
3318 /// time, stronger synchronization primitives such as [`fence`] are required.
3319 ///
3320 /// The re-ordering prevented by the different ordering semantics are:
3321 ///
3322 ///  - with [`SeqCst`], no re-ordering of reads and writes across this point is allowed.
3323 ///  - with [`Release`], preceding reads and writes cannot be moved past subsequent writes.
3324 ///  - with [`Acquire`], subsequent reads and writes cannot be moved ahead of preceding reads.
3325 ///  - with [`AcqRel`], both of the above rules are enforced.
3326 ///
3327 /// `compiler_fence` is generally only useful for preventing a thread from
3328 /// racing *with itself*. That is, if a given thread is executing one piece
3329 /// of code, and is then interrupted, and starts executing code elsewhere
3330 /// (while still in the same thread, and conceptually still on the same
3331 /// core). In traditional programs, this can only occur when a signal
3332 /// handler is registered. In more low-level code, such situations can also
3333 /// arise when handling interrupts, when implementing green threads with
3334 /// pre-emption, etc. Curious readers are encouraged to read the Linux kernel's
3335 /// discussion of [memory barriers].
3336 ///
3337 /// # Panics
3338 ///
3339 /// Panics if `order` is [`Relaxed`].
3340 ///
3341 /// # Examples
3342 ///
3343 /// Without `compiler_fence`, the `assert_eq!` in following code
3344 /// is *not* guaranteed to succeed, despite everything happening in a single thread.
3345 /// To see why, remember that the compiler is free to swap the stores to
3346 /// `IMPORTANT_VARIABLE` and `IS_READY` since they are both
3347 /// `Ordering::Relaxed`. If it does, and the signal handler is invoked right
3348 /// after `IS_READY` is updated, then the signal handler will see
3349 /// `IS_READY=1`, but `IMPORTANT_VARIABLE=0`.
3350 /// Using a `compiler_fence` remedies this situation.
3351 ///
3352 /// ```
3353 /// use std::sync::atomic::{AtomicBool, AtomicUsize};
3354 /// use std::sync::atomic::Ordering;
3355 /// use std::sync::atomic::compiler_fence;
3356 ///
3357 /// static IMPORTANT_VARIABLE: AtomicUsize = AtomicUsize::new(0);
3358 /// static IS_READY: AtomicBool = AtomicBool::new(false);
3359 ///
3360 /// fn main() {
3361 ///     IMPORTANT_VARIABLE.store(42, Ordering::Relaxed);
3362 ///     // prevent earlier writes from being moved beyond this point
3363 ///     compiler_fence(Ordering::Release);
3364 ///     IS_READY.store(true, Ordering::Relaxed);
3365 /// }
3366 ///
3367 /// fn signal_handler() {
3368 ///     if IS_READY.load(Ordering::Relaxed) {
3369 ///         assert_eq!(IMPORTANT_VARIABLE.load(Ordering::Relaxed), 42);
3370 ///     }
3371 /// }
3372 /// ```
3373 ///
3374 /// [memory barriers]: https://www.kernel.org/doc/Documentation/memory-barriers.txt
3375 #[inline]
3376 #[stable(feature = "compiler_fences", since = "1.21.0")]
3377 #[rustc_diagnostic_item = "compiler_fence"]
3378 pub fn compiler_fence(order: Ordering) {
3379     // SAFETY: using an atomic fence is safe.
3380     unsafe {
3381         match order {
3382             Acquire => intrinsics::atomic_singlethreadfence_acquire(),
3383             Release => intrinsics::atomic_singlethreadfence_release(),
3384             AcqRel => intrinsics::atomic_singlethreadfence_acqrel(),
3385             SeqCst => intrinsics::atomic_singlethreadfence_seqcst(),
3386             Relaxed => panic!("there is no such thing as a relaxed compiler fence"),
3387         }
3388     }
3389 }
3390
3391 #[cfg(target_has_atomic_load_store = "8")]
3392 #[stable(feature = "atomic_debug", since = "1.3.0")]
3393 impl fmt::Debug for AtomicBool {
3394     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3395         fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
3396     }
3397 }
3398
3399 #[cfg(target_has_atomic_load_store = "ptr")]
3400 #[stable(feature = "atomic_debug", since = "1.3.0")]
3401 impl<T> fmt::Debug for AtomicPtr<T> {
3402     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3403         fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
3404     }
3405 }
3406
3407 #[cfg(target_has_atomic_load_store = "ptr")]
3408 #[stable(feature = "atomic_pointer", since = "1.24.0")]
3409 impl<T> fmt::Pointer for AtomicPtr<T> {
3410     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3411         fmt::Pointer::fmt(&self.load(Ordering::SeqCst), f)
3412     }
3413 }
3414
3415 /// Signals the processor that it is inside a busy-wait spin-loop ("spin lock").
3416 ///
3417 /// This function is deprecated in favor of [`hint::spin_loop`].
3418 ///
3419 /// [`hint::spin_loop`]: crate::hint::spin_loop
3420 #[inline]
3421 #[stable(feature = "spin_loop_hint", since = "1.24.0")]
3422 #[deprecated(since = "1.51.0", note = "use hint::spin_loop instead")]
3423 pub fn spin_loop_hint() {
3424     spin_loop()
3425 }