Skip to main content

ArcAtomic

Struct ArcAtomic 

Source
pub struct ArcAtomic<T>
where T: AtomicValue,
{ /* private fields */ }
Expand description

Shared-owner wrapper around Atomic<T>.

This type is a convenience newtype for Arc<Atomic<T>>. Cloning an ArcAtomic clones the shared owner handle, so all clones operate on the same underlying atomic container.

Use Atomic<T> when ownership stays local, and use ArcAtomic<T> when the same atomic value must be shared across threads or components.

§Example

use qubit_atomic::ArcAtomic;

let counter = ArcAtomic::new(0usize);
let shared = counter.clone();

shared.fetch_inc();
assert_eq!(counter.load(), 1);
assert_eq!(counter.strong_count(), 2);

Implementations§

Source§

impl<T> ArcAtomic<T>
where T: AtomicValue,

Source

pub fn new(value: T) -> Self

Creates a new shared atomic value.

§Parameters
  • value - The initial value stored in the atomic container.
§Returns

A shared atomic wrapper initialized to value.

Source

pub fn from_atomic(atomic: Atomic<T>) -> Self

Wraps an existing Atomic<T> in an Arc.

§Parameters
  • atomic - The atomic container to share.
§Returns

A shared atomic wrapper owning atomic.

Source

pub fn from_arc(inner: Arc<Atomic<T>>) -> Self

Wraps an existing shared atomic container.

§Parameters
  • inner - The shared atomic container to wrap.
§Returns

A wrapper around inner.

Source

pub fn as_arc(&self) -> &Arc<Atomic<T>>

Returns the underlying Arc without cloning it.

§Returns

A shared reference to the underlying Arc<Atomic<T>>.

Source

pub fn into_arc(self) -> Arc<Atomic<T>>

Consumes this wrapper and returns the underlying Arc.

§Returns

The underlying Arc<Atomic<T>>.

Source

pub fn strong_count(&self) -> usize

Returns the number of strong Arc owners.

§Returns

The current strong reference count of the shared atomic container.

Methods from Deref<Target = Atomic<T>>§

Source

pub fn load(&self) -> T

Loads the current value.

Uses Acquire ordering by default.

§Returns

The current value.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(7);
assert_eq!(atomic.load(), 7);
Source

pub fn store(&self, value: T)

Stores a new value.

Uses Release ordering by default.

§Parameters
  • value - The new value to store.
§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(1);
atomic.store(2);
assert_eq!(atomic.load(), 2);
Source

pub fn swap(&self, value: T) -> T

Swaps the current value with value.

Unlike store, this returns the value that was in the atomic immediately before the swap, in the same atomic step. Use store when you do not need the previous value.

Uses AcqRel ordering by default.

§Parameters
  • value - The new value to store.
§Returns

The previous value.

§Example
use qubit_atomic::Atomic;

let a = Atomic::new(100);
a.store(200);
// store has no return value; you only see the new value via load().
assert_eq!(a.load(), 200);

let b = Atomic::new(100);
// swap returns the old value and installs the new one atomically.
assert_eq!(b.swap(200), 100);
assert_eq!(b.load(), 200);
Source

pub fn compare_set(&self, current: T, new: T) -> Result<(), T>

Compares the current value with current and stores new on match.

Uses AcqRel ordering on success and Acquire ordering on failure.

§Parameters
  • current - The expected current value.
  • new - The replacement value to store when the comparison matches.
§Returns

Ok(()) when the value was replaced.

§Errors

Returns Err(actual) with the observed value when the comparison fails. In that case, new is not stored.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(1);
assert!(atomic.compare_set(1, 2).is_ok());
assert_eq!(atomic.load(), 2);
assert_eq!(atomic.compare_set(1, 3), Err(2));
Source

pub fn compare_set_weak(&self, current: T, new: T) -> Result<(), T>

Weak version of compare_set.

This operation may fail spuriously and is intended for retry loops.

§Parameters
  • current - The expected current value.
  • new - The replacement value to store when the comparison matches.
§Returns

Ok(()) when the value was replaced.

§Errors

Returns Err(actual) with the observed value when the comparison fails, including possible spurious failures. In that case, new is not stored.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(1);
loop {
    match atomic.compare_set_weak(1, 2) {
        Ok(()) => break,
        Err(actual) => assert_eq!(actual, 1),
    }
}
assert_eq!(atomic.load(), 2);
Source

pub fn compare_and_exchange(&self, current: T, new: T) -> T

Compares and exchanges the value, returning the value seen before the operation.

If the return value equals current, the exchange succeeded.

§Parameters
  • current - The expected current value.
  • new - The replacement value to store when the comparison matches.
§Returns

The value observed before the operation completed. If the returned value equals current, the exchange succeeded; otherwise it is the actual value that prevented the exchange.

For Atomic<f32> and Atomic<f64>, CAS compares raw IEEE-754 bit patterns rather than PartialEq. A returned floating-point value comparing equal to current is therefore not always enough to prove success; use compare_set for an explicit Ok/Err, or compare to_bits values yourself.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(5);
assert_eq!(atomic.compare_and_exchange(5, 10), 5);
assert_eq!(atomic.load(), 10);
assert_eq!(atomic.compare_and_exchange(5, 0), 10);
Source

pub fn compare_and_exchange_weak(&self, current: T, new: T) -> T

Weak version of compare_and_exchange.

This operation may fail spuriously and is intended for retry loops.

§Parameters
  • current - The expected current value.
  • new - The replacement value to store when the comparison matches.
§Returns

The value observed before the operation completed. Because this operation may fail spuriously, a returned value equal to current does not by itself prove that new was stored; use compare_set_weak when the caller needs an explicit success indicator.

For Atomic<f32> and Atomic<f64>, the same caveat applies to raw-bit equality: 0.0 and -0.0 compare equal by PartialEq but are different CAS values. Use compare_set_weak or compare to_bits values when distinguishing success from failure matters.

§Example

Weak CAS may fail spuriously; retry until load shows the expected outcome (or use compare_set_weak which reports success explicitly).

use qubit_atomic::Atomic;

let atomic = Atomic::new(5);
loop {
    let _ = atomic.compare_and_exchange_weak(5, 10);
    if atomic.load() == 10 {
        break;
    }
}
Source

pub fn fetch_update<F>(&self, f: F) -> T
where F: Fn(T) -> T,

Updates the value with a function and returns the previous value.

The update uses a CAS loop until it succeeds. The closure may be called more than once under contention.

§Parameters
  • f - A function that maps the current value to the next value.
§Returns

The value before the successful update.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(3);
assert_eq!(atomic.fetch_update(|x| x * 2), 3);
assert_eq!(atomic.load(), 6);
Source

pub fn try_update<F>(&self, f: F) -> Option<T>
where F: Fn(T) -> Option<T>,

Conditionally updates the value with a function.

The update uses a CAS loop until it succeeds or the closure rejects the observed current value by returning None. The closure may be called more than once under contention.

§Parameters
  • f - A function that maps the current value to Some(next) to update the atomic, or None to leave it unchanged.
§Returns

Some(old_value) with the value before the successful update, or None when f rejects the observed current value.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(3);
assert_eq!(atomic.try_update(|x| (x % 2 == 1).then_some(x + 1)), Some(3));
assert_eq!(atomic.load(), 4);
assert_eq!(atomic.try_update(|x| (x % 2 == 1).then_some(x + 1)), None);
assert_eq!(atomic.load(), 4);
Source

pub fn inner(&self) -> &T::Inner

Returns the raw backend atomic value.

Use this method only when the default orderings are not appropriate and the caller needs direct access to the backend atomic storage.

§Returns

A shared reference to the raw backend atomic value.

§Example
use qubit_atomic::Atomic;
use std::sync::atomic::Ordering;

let atomic = Atomic::<i32>::new(0);
assert_eq!(atomic.inner().load(Ordering::Relaxed), 0);
Source

pub fn fetch_add(&self, delta: T) -> T

Adds delta to the value and returns the previous value.

Integer atomics use relaxed ordering for this operation. Floating-point atomics use a CAS loop. Integer addition wraps on overflow and underflow.

§Parameters
  • delta - The value to add.
§Returns

The value before the addition.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(10);
assert_eq!(atomic.fetch_add(3), 10);
assert_eq!(atomic.load(), 13);
Source

pub fn fetch_sub(&self, delta: T) -> T

Subtracts delta from the value and returns the previous value.

Integer atomics use relaxed ordering for this operation. Floating-point atomics use a CAS loop. Integer subtraction wraps on overflow and underflow.

§Parameters
  • delta - The value to subtract.
§Returns

The value before the subtraction.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(10);
assert_eq!(atomic.fetch_sub(3), 10);
assert_eq!(atomic.load(), 7);
Source

pub fn fetch_mul(&self, factor: T) -> T

Multiplies the value by factor and returns the previous value.

This operation uses a CAS loop. Integer multiplication wraps on overflow and underflow.

§Parameters
  • factor - The value to multiply by.
§Returns

The value before the multiplication.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(3);
assert_eq!(atomic.fetch_mul(4), 3);
assert_eq!(atomic.load(), 12);
Source

pub fn fetch_div(&self, divisor: T) -> T

Divides the value by divisor and returns the previous value.

This operation uses a CAS loop. Integer division uses wrapping semantics; for signed integers, MIN / -1 wraps to MIN.

§Parameters
  • divisor - The value to divide by.
§Returns

The value before the division.

§Panics

For integer specializations, panics if divisor is zero. Floating-point specializations follow IEEE-754 division semantics and do not panic solely because divisor is zero.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(20);
assert_eq!(atomic.fetch_div(4), 20);
assert_eq!(atomic.load(), 5);
Source

pub fn fetch_inc(&self) -> T

Increments the value by one and returns the previous value.

§Returns

The value before the increment.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(0);
assert_eq!(atomic.fetch_inc(), 0);
assert_eq!(atomic.load(), 1);
Source

pub fn fetch_dec(&self) -> T

Decrements the value by one and returns the previous value.

§Returns

The value before the decrement.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(1);
assert_eq!(atomic.fetch_dec(), 1);
assert_eq!(atomic.load(), 0);
Source

pub fn fetch_and(&self, value: T) -> T

Applies bitwise AND and returns the previous value.

§Parameters
  • value - The mask to apply.
§Returns

The value before the operation.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::<u8>::new(0b1111);
assert_eq!(atomic.fetch_and(0b1010), 0b1111);
assert_eq!(atomic.load(), 0b1010);
Source

pub fn fetch_or(&self, value: T) -> T

Applies bitwise OR and returns the previous value.

§Parameters
  • value - The mask to apply.
§Returns

The value before the operation.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::<u8>::new(0b1000);
assert_eq!(atomic.fetch_or(0b0011), 0b1000);
assert_eq!(atomic.load(), 0b1011);
Source

pub fn fetch_xor(&self, value: T) -> T

Applies bitwise XOR and returns the previous value.

§Parameters
  • value - The mask to apply.
§Returns

The value before the operation.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::<u8>::new(0b1111);
assert_eq!(atomic.fetch_xor(0b1010), 0b1111);
assert_eq!(atomic.load(), 0b0101);
Source

pub fn fetch_not(&self) -> T

Flips all bits and returns the previous value.

§Returns

The value before the operation.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::<i32>::new(0);
assert_eq!(atomic.fetch_not(), 0);
assert_eq!(atomic.load(), !0);
Source

pub fn fetch_accumulate<F>(&self, value: T, f: F) -> T
where F: Fn(T, T) -> T,

Updates the value by accumulating it with value.

§Parameters
  • value - The right-hand input to the accumulator.
  • f - A function that combines the current value and value.
§Returns

The value before the successful update.

The closure may be called more than once when concurrent updates cause CAS retries.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(10);
assert_eq!(atomic.fetch_accumulate(5, |a, b| a + b), 10);
assert_eq!(atomic.load(), 15);
Source

pub fn fetch_max(&self, value: T) -> T

Replaces the value with the maximum of the current value and value.

§Parameters
  • value - The value to compare with the current value.
§Returns

The value before the operation.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(3);
assert_eq!(atomic.fetch_max(10), 3);
assert_eq!(atomic.load(), 10);
Source

pub fn fetch_min(&self, value: T) -> T

Replaces the value with the minimum of the current value and value.

§Parameters
  • value - The value to compare with the current value.
§Returns

The value before the operation.

§Example
use qubit_atomic::Atomic;

let atomic = Atomic::new(10);
assert_eq!(atomic.fetch_min(3), 10);
assert_eq!(atomic.load(), 3);

Trait Implementations§

Source§

impl<T> Clone for ArcAtomic<T>
where T: AtomicValue,

Source§

fn clone(&self) -> Self

Clones the shared owner handle.

§Returns

A new wrapper pointing to the same underlying atomic container.

1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for ArcAtomic<T>
where T: AtomicValue + Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the current value and sharing state for debugging.

§Parameters
  • f - The formatter receiving the debug representation.
§Returns

A formatting result from the formatter.

Source§

impl<T> Deref for ArcAtomic<T>
where T: AtomicValue,

Source§

fn deref(&self) -> &Self::Target

Dereferences to the underlying Atomic<T>.

§Returns

A shared reference to the atomic container.

Source§

type Target = Atomic<T>

The resulting type after dereferencing.
Source§

impl<T> Display for ArcAtomic<T>
where T: AtomicValue + Display,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the currently loaded value with display formatting.

§Parameters
  • f - The formatter receiving the displayed value.
§Returns

A formatting result from the formatter.

Source§

impl<T> From<Arc<Atomic<T>>> for ArcAtomic<T>
where T: AtomicValue,

Source§

fn from(inner: Arc<Atomic<T>>) -> Self

Converts an existing shared atomic container into its wrapper.

§Parameters
  • inner - The shared atomic container to wrap.
§Returns

A wrapper around inner.

Source§

impl<T> From<Atomic<T>> for ArcAtomic<T>
where T: AtomicValue,

Source§

fn from(atomic: Atomic<T>) -> Self

Converts an atomic container into a shared atomic wrapper.

§Parameters
  • atomic - The atomic container to share.
§Returns

A shared atomic wrapper owning atomic.

Source§

impl<T> From<T> for ArcAtomic<T>
where T: AtomicValue,

Source§

fn from(value: T) -> Self

Converts an initial value into a shared atomic wrapper.

§Parameters
  • value - The initial value stored in the atomic container.
§Returns

A shared atomic wrapper initialized to value.

Auto Trait Implementations§

§

impl<T> Freeze for ArcAtomic<T>

§

impl<T> RefUnwindSafe for ArcAtomic<T>
where <T as AtomicValue>::Primitive: RefUnwindSafe,

§

impl<T> Send for ArcAtomic<T>
where <T as AtomicValue>::Primitive: Sync + Send,

§

impl<T> Sync for ArcAtomic<T>
where <T as AtomicValue>::Primitive: Sync + Send,

§

impl<T> Unpin for ArcAtomic<T>

§

impl<T> UnsafeUnpin for ArcAtomic<T>

§

impl<T> UnwindSafe for ArcAtomic<T>
where <T as AtomicValue>::Primitive: RefUnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.