use std::sync::Arc;
use tokio::sync::{watch, RwLock};
#[derive(Debug)]
pub struct StateCell<T: Clone + Send + Sync + 'static> {
state: Arc<RwLock<T>>,
changes_tx: watch::Sender<T>,
}
impl<T: Clone + Send + Sync + 'static> Clone for StateCell<T> {
fn clone(&self) -> Self {
Self {
state: Arc::clone(&self.state),
changes_tx: self.changes_tx.clone(),
}
}
}
impl<T: Clone + Send + Sync + 'static> StateCell<T> {
pub fn new(initial: T) -> Self {
let (changes_tx, _) = watch::channel(initial.clone());
Self {
state: Arc::new(RwLock::new(initial)),
changes_tx,
}
}
pub async fn current(&self) -> T {
self.state.read().await.clone()
}
pub fn changes(&self) -> watch::Receiver<T> {
self.changes_tx.subscribe()
}
pub async fn apply<F, E>(&self, f: F) -> Result<(), E>
where
F: FnOnce(T) -> Result<T, E>,
{
let mut guard = self.state.write().await;
let prev = guard.clone();
let next = f(prev)?;
*guard = next.clone();
drop(guard);
let _ = self.changes_tx.send(next);
Ok(())
}
pub async fn set(&self, value: T) {
let mut guard = self.state.write().await;
*guard = value.clone();
drop(guard);
let _ = self.changes_tx.send(value);
}
pub fn receiver_count(&self) -> usize {
self.changes_tx.receiver_count()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn current_returns_initial() {
let cell = StateCell::new(7u32);
assert_eq!(cell.current().await, 7);
}
#[tokio::test]
async fn apply_advances_and_broadcasts() {
let cell = StateCell::new(7u32);
let mut rx = cell.changes();
let _ = rx.borrow_and_update();
cell.apply::<_, ()>(|v| Ok(v + 1)).await.unwrap();
rx.changed().await.unwrap();
assert_eq!(*rx.borrow(), 8);
}
#[tokio::test]
async fn apply_preserves_state_on_error() {
let cell = StateCell::new(7u32);
let result: Result<(), &str> = cell.apply(|_| Err("nope")).await;
assert!(result.is_err());
assert_eq!(cell.current().await, 7);
}
#[tokio::test]
async fn set_replaces_unconditionally() {
let cell = StateCell::new(7u32);
cell.set(99).await;
assert_eq!(cell.current().await, 99);
}
#[tokio::test]
async fn clones_share_state() {
let cell = StateCell::new(7u32);
let other = cell.clone();
cell.set(99).await;
assert_eq!(other.current().await, 99);
}
}