diff --git a/src/main.rs b/src/main.rs index 66af92d..003086f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -29,20 +29,20 @@ fn init(states: &Arc) { fn app(states: &Arc, screen: &mut Screen) { screen.events.set_state_manager(states.clone()); - let count = states.use_state(0); + let mut count = states.use_state(0); screen .draw(Rect(0xffffff)) .component(Transform::center().dimensions(30, 3)); screen - .draw(format!("Count: {}", count.get())) + .draw(format!("Count: {count}")) .component(Transform::center()); screen.events.on( move |events: &Arc, event: &KeyEvent| match event.code { crossterm::event::KeyCode::Enter => { - count.set(count.get() + 1); + count += 1; } _ => { events.close(); diff --git a/src/state.rs b/src/state.rs index 1d1b4c2..45c500c 100644 --- a/src/state.rs +++ b/src/state.rs @@ -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 State { +impl State { 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 Display for State { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.manager.store.lock().unwrap()[&self.id] .downcast_ref::>() .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::>() - .unwrap() - .lock() - .unwrap() = val; - } +impl Add for State { + type Output = ::Output; + + fn add(self, rhs: S) -> Self::Output { + self.manager.store.lock().unwrap()[&self.id] + .downcast_ref::>() + .unwrap() + .lock() + .unwrap() + .clone() + .add(rhs) + } +} + +impl Sub for State { + type Output = ::Output; + + fn sub(self, rhs: S) -> Self::Output { + self.manager.store.lock().unwrap()[&self.id] + .downcast_ref::>() + .unwrap() + .lock() + .unwrap() + .clone() + .sub(rhs) + } +} + +impl Div for State { + type Output = ::Output; + + fn div(self, rhs: S) -> Self::Output { + self.manager.store.lock().unwrap()[&self.id] + .downcast_ref::>() + .unwrap() + .lock() + .unwrap() + .clone() + .div(rhs) + } +} + +impl AddAssign for State { + fn add_assign(&mut self, rhs: S) { + self.manager.store.lock().unwrap()[&self.id] + .downcast_ref::>() + .unwrap() + .lock() + .unwrap() + .add_assign(rhs); self.dirty(); } } + +impl SubAssign for State { + fn sub_assign(&mut self, rhs: S) { + self.manager.store.lock().unwrap()[&self.id] + .downcast_ref::>() + .unwrap() + .lock() + .unwrap() + .sub_assign(rhs); + self.dirty(); + } +} + +impl + 'static> PartialEq for State { + fn eq(&self, other: &S) -> bool { + self.manager.store.lock().unwrap()[&self.id] + .downcast_ref::>() + .unwrap() + .lock() + .unwrap() + .eq(other) + } +}