use std::sync::{Arc, Mutex};
use super::waiters::lock;
use crate::kernel::{Effect, suspend, sync};
pub struct Ref<A> {
cell: Arc<Mutex<A>>,
}
impl<A> Clone for Ref<A> {
fn clone(&self) -> Self {
Self {
cell: Arc::clone(&self.cell),
}
}
}
impl<A: std::fmt::Debug> std::fmt::Debug for Ref<A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Ref").field(&*lock(&self.cell)).finish()
}
}
impl<A: Send + 'static> Ref<A> {
pub fn new(value: A) -> Self {
Self {
cell: Arc::new(Mutex::new(value)),
}
}
pub fn get<E, R>(&self) -> Effect<A, E, R>
where
A: Clone,
{
let cell = Arc::clone(&self.cell);
sync(move || lock(&cell).clone())
}
pub fn set<E, R>(&self, value: A) -> Effect<(), E, R> {
let cell = Arc::clone(&self.cell);
sync(move || *lock(&cell) = value)
}
pub fn update<E, R>(&self, f: impl FnOnce(A) -> A + Send + 'static) -> Effect<(), E, R>
where
A: Clone,
{
let cell = Arc::clone(&self.cell);
sync(move || {
let mut g = lock(&cell);
*g = f(g.clone());
})
}
pub fn update_and_get<E, R>(&self, f: impl FnOnce(A) -> A + Send + 'static) -> Effect<A, E, R>
where
A: Clone,
{
let cell = Arc::clone(&self.cell);
sync(move || {
let mut g = lock(&cell);
*g = f(g.clone());
g.clone()
})
}
pub fn get_and_update<E, R>(&self, f: impl FnOnce(A) -> A + Send + 'static) -> Effect<A, E, R>
where
A: Clone,
{
let cell = Arc::clone(&self.cell);
sync(move || {
let mut g = lock(&cell);
let old = g.clone();
*g = f(old.clone());
old
})
}
pub fn modify<B, E, R>(&self, f: impl FnOnce(A) -> (B, A) + Send + 'static) -> Effect<B, E, R>
where
A: Clone,
{
let cell = Arc::clone(&self.cell);
sync(move || {
let mut g = lock(&cell);
let (b, new) = f(g.clone());
*g = new;
b
})
}
pub fn get_and_set<E, R>(&self, value: A) -> Effect<A, E, R> {
let cell = Arc::clone(&self.cell);
sync(move || std::mem::replace(&mut *lock(&cell), value))
}
pub fn set_and_get<E, R>(&self, value: A) -> Effect<A, E, R>
where
A: Clone,
{
let cell = Arc::clone(&self.cell);
sync(move || {
*lock(&cell) = value.clone();
value
})
}
pub fn modify_effect<B, E, R>(
&self,
f: impl FnOnce(A) -> Effect<(B, A), E, R> + Send + 'static,
) -> Effect<B, E, R>
where
A: Clone,
B: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
let cell = Arc::clone(&self.cell);
suspend(move || {
let old = lock(&cell).clone();
f(old).map(move |(b, new)| {
*lock(&cell) = new;
b
})
})
}
}