pub struct AtomicRef<T>(/* private fields */);
Expand description
Atomic reference holding a value, that’s supposed to be shared - potentially between multiple threads. Internally this value is hidden behind Arc reference, which is returned during AtomicRef::get method. This cell doesn’t allow to return &mut references to stored object. Instead updates can be performed as lock-free operation mutating function passed over during AtomicRef::update call.
Example:
use yrs::atomic::AtomicRef;
let atom = AtomicRef::new(vec!["John"]);
atom.update(|users| {
let mut users_copy = users.cloned().unwrap_or_else(Vec::default);
users_copy.push("Susan");
users_copy
});
let users = atom.get(); // John, Susan
Important note: since AtomicRef::update may call provided function multiple times (in scenarios, when another thread intercepted update with its own update call), provided function should be idempotent and preferably quick to execute.
Implementations§
source§impl<T> AtomicRef<T>
impl<T> AtomicRef<T>
sourcepub fn new(value: T) -> Self
pub fn new(value: T) -> Self
Creates a new instance of AtomicRef. This call boxes provided value
and allocates it
on a heap.
sourcepub fn get(&self) -> Option<Arc<T>>
pub fn get(&self) -> Option<Arc<T>>
Returns a reference to current state hold by the AtomicRef. Keep in mind that after acquiring it, it may not present the current view of the state, but instead be changed by the concurrent AtomicRef::update call.
sourcepub fn swap(&self, value: T) -> Option<Arc<T>>
pub fn swap(&self, value: T) -> Option<Arc<T>>
Atomically replaces currently stored value with a new one, returning the last stored value.
sourcepub fn take(&self) -> Option<Arc<T>>
pub fn take(&self) -> Option<Arc<T>>
Atomically replaces currently stored value with a null, returning the last stored value.
sourcepub fn update<F>(&self, f: F)
pub fn update<F>(&self, f: F)
Updates stored value in place using provided function f
, which takes read-only refrence
to the most recently known state and producing new state in the result.
Important note: since AtomicRef::update may call provided function multiple times (in scenarios, when another thread intercepted update with its own update call), provided function should be idempotent and preferably quick to execute.