use std::{ cell::{Cell, Ref, RefCell, RefMut}, fmt::{Debug, Display}, rc::Rc, }; pub struct UseStateOwned { // this will always be outdated pub(crate) current_val: Rc, pub(crate) wip: Rc>>, pub(crate) update_callback: Rc, pub(crate) update_scheuled: Cell, } impl UseStateOwned { pub fn get(&self) -> Ref> { self.wip.borrow() } pub fn set(&self, new_val: T) { *self.wip.borrow_mut() = Some(new_val); (self.update_callback)(); } pub fn modify(&self) -> RefMut> { (self.update_callback)(); self.wip.borrow_mut() } } use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; impl Debug for UseStateOwned { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self.current_val) } } // enable displaty for the handle impl<'a, T: 'static + Display> std::fmt::Display for UseStateOwned { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.current_val) } } impl<'a, T: Copy + Add> Add for UseStateOwned { type Output = T; fn add(self, rhs: T) -> Self::Output { self.current_val.add(rhs) } } impl<'a, T: Copy + Add> AddAssign for UseStateOwned { fn add_assign(&mut self, rhs: T) { self.set(self.current_val.add(rhs)); } } /// Sub impl<'a, T: Copy + Sub> Sub for UseStateOwned { type Output = T; fn sub(self, rhs: T) -> Self::Output { self.current_val.sub(rhs) } } impl<'a, T: Copy + Sub> SubAssign for UseStateOwned { fn sub_assign(&mut self, rhs: T) { self.set(self.current_val.sub(rhs)); } } /// MUL impl<'a, T: Copy + Mul> Mul for UseStateOwned { type Output = T; fn mul(self, rhs: T) -> Self::Output { self.current_val.mul(rhs) } } impl<'a, T: Copy + Mul> MulAssign for UseStateOwned { fn mul_assign(&mut self, rhs: T) { self.set(self.current_val.mul(rhs)); } } /// DIV impl<'a, T: Copy + Div> Div for UseStateOwned { type Output = T; fn div(self, rhs: T) -> Self::Output { self.current_val.div(rhs) } } impl<'a, T: Copy + Div> DivAssign for UseStateOwned { fn div_assign(&mut self, rhs: T) { self.set(self.current_val.div(rhs)); } }