Skip to main content

rhwp_codec_resource/
atomic.rs

1//! Checked atomic ledger updates shared by import and Native resource owners.
2//!
3//! Rust 1.93.1 cannot use the renamed standard-library `try_update` API. Keep the
4//! same retry, previous-value and ordering contract using stable atomic operations.
5
6#[cfg(any(target_has_atomic = "ptr", target_has_atomic = "64"))]
7use core::sync::atomic::Ordering;
8
9#[cfg(any(target_has_atomic = "ptr", target_has_atomic = "64"))]
10macro_rules! checked_atomic_update {
11    ($name:ident, $atomic:ty, $value:ty) => {
12        /// Apply a checked update, returning the previous value on success or rejection.
13        ///
14        /// The callback can run again after contention or a spurious CAS failure.
15        /// `None` rejects without writing. The orderings are the successful CAS
16        /// ordering and the load/failed CAS ordering, respectively.
17        #[inline]
18        pub fn $name(
19            counter: &$atomic,
20            set_order: Ordering,
21            fetch_order: Ordering,
22            mut update: impl FnMut($value) -> Option<$value>,
23        ) -> Result<$value, $value> {
24            let mut observed = counter.load(fetch_order);
25            loop {
26                let next = update(observed).ok_or(observed)?;
27                match counter.compare_exchange_weak(observed, next, set_order, fetch_order) {
28                    Ok(previous) => return Ok(previous),
29                    Err(current) => observed = current,
30                }
31            }
32        }
33    };
34}
35
36#[cfg(target_has_atomic = "ptr")]
37checked_atomic_update!(try_update_usize, core::sync::atomic::AtomicUsize, usize);
38
39#[cfg(target_has_atomic = "64")]
40checked_atomic_update!(try_update_u64, core::sync::atomic::AtomicU64, u64);