owned.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. use std::{
  2. cell::{Cell, Ref, RefCell, RefMut},
  3. fmt::{Debug, Display},
  4. rc::Rc,
  5. };
  6. pub struct UseStateOwned<T: 'static> {
  7. // this will always be outdated
  8. pub(crate) current_val: Rc<T>,
  9. pub(crate) wip: Rc<RefCell<Option<T>>>,
  10. pub(crate) update_callback: Rc<dyn Fn()>,
  11. pub(crate) update_scheuled: Cell<bool>,
  12. }
  13. impl<T> UseStateOwned<T> {
  14. pub fn get(&self) -> Ref<Option<T>> {
  15. self.wip.borrow()
  16. }
  17. pub fn set(&self, new_val: T) {
  18. *self.wip.borrow_mut() = Some(new_val);
  19. (self.update_callback)();
  20. }
  21. pub fn modify(&self) -> RefMut<Option<T>> {
  22. (self.update_callback)();
  23. self.wip.borrow_mut()
  24. }
  25. }
  26. use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
  27. impl<T: Debug> Debug for UseStateOwned<T> {
  28. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  29. write!(f, "{:?}", self.current_val)
  30. }
  31. }
  32. // enable displaty for the handle
  33. impl<'a, T: 'static + Display> std::fmt::Display for UseStateOwned<T> {
  34. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  35. write!(f, "{}", self.current_val)
  36. }
  37. }
  38. impl<'a, T: Copy + Add<T, Output = T>> Add<T> for UseStateOwned<T> {
  39. type Output = T;
  40. fn add(self, rhs: T) -> Self::Output {
  41. self.current_val.add(rhs)
  42. }
  43. }
  44. impl<'a, T: Copy + Add<T, Output = T>> AddAssign<T> for UseStateOwned<T> {
  45. fn add_assign(&mut self, rhs: T) {
  46. self.set(self.current_val.add(rhs));
  47. }
  48. }
  49. /// Sub
  50. impl<'a, T: Copy + Sub<T, Output = T>> Sub<T> for UseStateOwned<T> {
  51. type Output = T;
  52. fn sub(self, rhs: T) -> Self::Output {
  53. self.current_val.sub(rhs)
  54. }
  55. }
  56. impl<'a, T: Copy + Sub<T, Output = T>> SubAssign<T> for UseStateOwned<T> {
  57. fn sub_assign(&mut self, rhs: T) {
  58. self.set(self.current_val.sub(rhs));
  59. }
  60. }
  61. /// MUL
  62. impl<'a, T: Copy + Mul<T, Output = T>> Mul<T> for UseStateOwned<T> {
  63. type Output = T;
  64. fn mul(self, rhs: T) -> Self::Output {
  65. self.current_val.mul(rhs)
  66. }
  67. }
  68. impl<'a, T: Copy + Mul<T, Output = T>> MulAssign<T> for UseStateOwned<T> {
  69. fn mul_assign(&mut self, rhs: T) {
  70. self.set(self.current_val.mul(rhs));
  71. }
  72. }
  73. /// DIV
  74. impl<'a, T: Copy + Div<T, Output = T>> Div<T> for UseStateOwned<T> {
  75. type Output = T;
  76. fn div(self, rhs: T) -> Self::Output {
  77. self.current_val.div(rhs)
  78. }
  79. }
  80. impl<'a, T: Copy + Div<T, Output = T>> DivAssign<T> for UseStateOwned<T> {
  81. fn div_assign(&mut self, rhs: T) {
  82. self.set(self.current_val.div(rhs));
  83. }
  84. }