use std::{
fmt::{Debug, Display},
sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard},
};
pub struct State<T: ?Sized>(Arc<RwLock<T>>);
impl<T> State<T> {
pub fn new(value: T) -> Self {
Self(Arc::new(RwLock::new(value)))
}
pub fn read(&self) -> RwLockReadGuard<'_, T> {
self.0.read().unwrap()
}
pub fn write(&self) -> RwLockWriteGuard<'_, T> {
self.0.write().unwrap()
}
}
impl<T: Display> Display for State<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.read().fmt(f)
}
}
impl<T: Debug> Debug for State<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.read().fmt(f)
}
}
impl<T: Default> Default for State<T> {
fn default() -> Self {
Self::new(Default::default())
}
}
impl<T: ?Sized> Clone for State<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}