improved state management

This commit is contained in:
2025-06-28 11:30:09 -05:00
parent fd73514a7b
commit bb0ef3adc4
2 changed files with 85 additions and 18 deletions
+82 -15
View File
@@ -1,7 +1,9 @@
use std::{
any::Any,
collections::HashMap,
fmt::Display,
marker::PhantomData,
ops::{Add, AddAssign, Div, Sub, SubAssign},
sync::{Arc, Mutex},
};
@@ -61,31 +63,96 @@ impl StateManager {
}
}
impl<S: 'static + Clone + Send + Sync> State<S> {
impl<S: 'static> State<S> {
pub fn dirty(&self) {
*self.manager.dirty.lock().unwrap() = true;
}
}
pub fn get(&self) -> S {
let store = self.manager.store.lock().unwrap();
let x = store[&self.id]
impl<S: Display + 'static> Display for State<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.manager.store.lock().unwrap()[&self.id]
.downcast_ref::<Mutex<S>>()
.unwrap()
.lock()
.unwrap()
.clone();
x
.fmt(f)
}
}
pub fn set(&self, val: S) {
{
let store = self.manager.store.lock().unwrap();
*store[&self.id]
.downcast_ref::<Mutex<S>>()
.unwrap()
.lock()
.unwrap() = val;
}
impl<S: Add + Clone + 'static> Add<S> for State<S> {
type Output = <S as Add>::Output;
fn add(self, rhs: S) -> Self::Output {
self.manager.store.lock().unwrap()[&self.id]
.downcast_ref::<Mutex<S>>()
.unwrap()
.lock()
.unwrap()
.clone()
.add(rhs)
}
}
impl<S: Sub + Clone + 'static> Sub<S> for State<S> {
type Output = <S as Sub>::Output;
fn sub(self, rhs: S) -> Self::Output {
self.manager.store.lock().unwrap()[&self.id]
.downcast_ref::<Mutex<S>>()
.unwrap()
.lock()
.unwrap()
.clone()
.sub(rhs)
}
}
impl<S: Div + Clone + 'static> Div<S> for State<S> {
type Output = <S as Div>::Output;
fn div(self, rhs: S) -> Self::Output {
self.manager.store.lock().unwrap()[&self.id]
.downcast_ref::<Mutex<S>>()
.unwrap()
.lock()
.unwrap()
.clone()
.div(rhs)
}
}
impl<S: AddAssign + 'static> AddAssign<S> for State<S> {
fn add_assign(&mut self, rhs: S) {
self.manager.store.lock().unwrap()[&self.id]
.downcast_ref::<Mutex<S>>()
.unwrap()
.lock()
.unwrap()
.add_assign(rhs);
self.dirty();
}
}
impl<S: SubAssign + 'static> SubAssign<S> for State<S> {
fn sub_assign(&mut self, rhs: S) {
self.manager.store.lock().unwrap()[&self.id]
.downcast_ref::<Mutex<S>>()
.unwrap()
.lock()
.unwrap()
.sub_assign(rhs);
self.dirty();
}
}
impl<S: PartialEq<S> + 'static> PartialEq<S> for State<S> {
fn eq(&self, other: &S) -> bool {
self.manager.store.lock().unwrap()[&self.id]
.downcast_ref::<Mutex<S>>()
.unwrap()
.lock()
.unwrap()
.eq(other)
}
}