Skip to content

Commit 9c271bb

Browse files
authored
Rollup merge of rust-lang#98479 - leocth:atomic-bool-fetch-not, r=joshtriplett
Add `fetch_not` method on `AtomicBool` This PR adds a `fetch_not` method on `AtomicBool` performs the NOT operation on the inner value. Internally, this just calls the `fetch_xor` method with the value `true`. [See this IRLO discussion](https://internals.rust-lang.org/t/could-we-have-fetch-not-for-atomicbool-s/16881)
2 parents 89870fc + b746e2f commit 9c271bb

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

core/src/sync/atomic.rs

+36
Original file line numberDiff line numberDiff line change
@@ -854,6 +854,42 @@ impl AtomicBool {
854854
unsafe { atomic_xor(self.v.get(), val as u8, order) != 0 }
855855
}
856856

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+
857893
/// Returns a mutable pointer to the underlying [`bool`].
858894
///
859895
/// Doing non-atomic reads and writes on the resulting integer can be a data race.

0 commit comments

Comments
 (0)