memo.rs 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. use crate::{read::Readable, ReadableRef};
  2. use dioxus_core::prelude::{IntoAttributeValue, ScopeId};
  3. use generational_box::UnsyncStorage;
  4. use std::{mem::MaybeUninit, ops::Deref};
  5. use crate::{ReadOnlySignal, Signal};
  6. use super::get_global_context;
  7. /// A signal that can be accessed from anywhere in the application and created in a static
  8. pub struct GlobalMemo<T: 'static> {
  9. selector: fn() -> T,
  10. }
  11. impl<T: PartialEq + 'static> GlobalMemo<T> {
  12. /// Create a new global signal
  13. pub const fn new(selector: fn() -> T) -> GlobalMemo<T>
  14. where
  15. T: PartialEq,
  16. {
  17. GlobalMemo { selector }
  18. }
  19. /// Get the signal that backs this global.
  20. pub fn signal(&self) -> ReadOnlySignal<T> {
  21. let key = self as *const _ as *const ();
  22. let context = get_global_context();
  23. let read = context.signal.borrow();
  24. match read.get(&key) {
  25. Some(signal) => *signal.downcast_ref::<ReadOnlySignal<T>>().unwrap(),
  26. None => {
  27. drop(read);
  28. // Constructors are always run in the root scope
  29. let signal = ScopeId::ROOT.in_runtime(|| Signal::memo(self.selector));
  30. context.signal.borrow_mut().insert(key, Box::new(signal));
  31. signal
  32. }
  33. }
  34. }
  35. /// Get the scope the signal was created in.
  36. pub fn origin_scope(&self) -> ScopeId {
  37. ScopeId::ROOT
  38. }
  39. /// Get the generational id of the signal.
  40. pub fn id(&self) -> generational_box::GenerationalBoxId {
  41. self.signal().id()
  42. }
  43. }
  44. impl<T: PartialEq + 'static> Readable for GlobalMemo<T> {
  45. type Target = T;
  46. type Storage = UnsyncStorage;
  47. #[track_caller]
  48. fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
  49. self.signal().try_read()
  50. }
  51. #[track_caller]
  52. fn peek(&self) -> ReadableRef<Self> {
  53. self.signal().peek()
  54. }
  55. }
  56. impl<T: PartialEq + 'static> IntoAttributeValue for GlobalMemo<T>
  57. where
  58. T: Clone + IntoAttributeValue,
  59. {
  60. fn into_value(self) -> dioxus_core::AttributeValue {
  61. self.signal().into_value()
  62. }
  63. }
  64. impl<T: PartialEq + 'static> PartialEq for GlobalMemo<T> {
  65. fn eq(&self, other: &Self) -> bool {
  66. std::ptr::eq(self, other)
  67. }
  68. }
  69. /// Allow calling a signal with signal() syntax
  70. ///
  71. /// Currently only limited to copy types, though could probably specialize for string/arc/rc
  72. impl<T: PartialEq + Clone + 'static> Deref for GlobalMemo<T> {
  73. type Target = dyn Fn() -> T;
  74. fn deref(&self) -> &Self::Target {
  75. // https://github.com/dtolnay/case-studies/tree/master/callable-types
  76. // First we create a closure that captures something with the Same in memory layout as Self (MaybeUninit<Self>).
  77. let uninit_callable = MaybeUninit::<Self>::uninit();
  78. // Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
  79. let uninit_closure = move || Self::read(unsafe { &*uninit_callable.as_ptr() }).clone();
  80. // Check that the size of the closure is the same as the size of Self in case the compiler changed the layout of the closure.
  81. let size_of_closure = std::mem::size_of_val(&uninit_closure);
  82. assert_eq!(size_of_closure, std::mem::size_of::<Self>());
  83. // Then cast the lifetime of the closure to the lifetime of &self.
  84. fn cast_lifetime<'a, T>(_a: &T, b: &'a T) -> &'a T {
  85. b
  86. }
  87. let reference_to_closure = cast_lifetime(
  88. {
  89. // The real closure that we will never use.
  90. &uninit_closure
  91. },
  92. // We transmute self into a reference to the closure. This is safe because we know that the closure has the same memory layout as Self so &Closure == &self.
  93. unsafe { std::mem::transmute(self) },
  94. );
  95. // Cast the closure to a trait object.
  96. reference_to_closure as &Self::Target
  97. }
  98. }