read.rs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. use std::{mem::MaybeUninit, ops::Index, rc::Rc};
  2. use generational_box::AnyStorage;
  3. use crate::MappedSignal;
  4. /// A reference to a value that can be read from.
  5. #[allow(type_alias_bounds)]
  6. pub type ReadableRef<'a, T: Readable, O = <T as Readable>::Target> =
  7. <T::Storage as AnyStorage>::Ref<'a, O>;
  8. /// A trait for states that can be read from like [`crate::Signal`], [`crate::GlobalSignal`], or [`crate::ReadOnlySignal`]. You may choose to accept this trait as a parameter instead of the concrete type to allow for more flexibility in your API. For example, instead of creating two functions, one that accepts a [`crate::Signal`] and one that accepts a [`crate::GlobalSignal`], you can create one function that accepts a [`Readable`] type.
  9. pub trait Readable {
  10. /// The target type of the reference.
  11. type Target: ?Sized + 'static;
  12. /// The type of the storage this readable uses.
  13. type Storage: AnyStorage;
  14. /// Map the readable type to a new type.
  15. fn map<O>(self, f: impl Fn(&Self::Target) -> &O + 'static) -> MappedSignal<O, Self::Storage>
  16. where
  17. Self: Clone + Sized + 'static,
  18. {
  19. let mapping = Rc::new(f);
  20. let try_read = Rc::new({
  21. let self_ = self.clone();
  22. let mapping = mapping.clone();
  23. move || {
  24. self_
  25. .try_read_unchecked()
  26. .map(|ref_| <Self::Storage as AnyStorage>::map(ref_, |r| mapping(r)))
  27. }
  28. })
  29. as Rc<
  30. dyn Fn() -> Result<ReadableRef<'static, Self, O>, generational_box::BorrowError>
  31. + 'static,
  32. >;
  33. let peek = Rc::new(move || {
  34. <Self::Storage as AnyStorage>::map(self.peek_unchecked(), |r| mapping(r))
  35. }) as Rc<dyn Fn() -> ReadableRef<'static, Self, O> + 'static>;
  36. MappedSignal::new(try_read, peek)
  37. }
  38. /// Get the current value of the state. If this is a signal, this will subscribe the current scope to the signal.
  39. /// If the value has been dropped, this will panic. Calling this on a Signal is the same as
  40. /// using the signal() syntax to read and subscribe to its value
  41. #[track_caller]
  42. fn read(&self) -> ReadableRef<Self> {
  43. self.try_read().unwrap()
  44. }
  45. /// Try to get the current value of the state. If this is a signal, this will subscribe the current scope to the signal.
  46. #[track_caller]
  47. fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
  48. self.try_read_unchecked().map(Self::Storage::downcast_ref)
  49. }
  50. /// Try to get a reference to the value without checking the lifetime.
  51. ///
  52. /// NOTE: This method is completely safe because borrow checking is done at runtime.
  53. fn try_read_unchecked(
  54. &self,
  55. ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError>;
  56. /// Tet a reference to the value without checking the lifetime.
  57. ///
  58. /// NOTE: This method is completely safe because borrow checking is done at runtime.
  59. fn read_unchecked(&self) -> ReadableRef<'static, Self> {
  60. self.try_read_unchecked().unwrap()
  61. }
  62. /// Get the current value of the signal without checking the lifetime. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.**
  63. ///
  64. /// If the signal has been dropped, this will panic.
  65. ///
  66. /// NOTE: This method is completely safe because borrow checking is done at runtime.
  67. fn peek_unchecked(&self) -> ReadableRef<'static, Self>;
  68. /// Get the current value of the state without subscribing to updates. If the value has been dropped, this will panic.
  69. #[track_caller]
  70. fn peek(&self) -> ReadableRef<Self> {
  71. Self::Storage::downcast_ref(self.peek_unchecked())
  72. }
  73. /// Clone the inner value and return it. If the value has been dropped, this will panic.
  74. #[track_caller]
  75. fn cloned(&self) -> Self::Target
  76. where
  77. Self::Target: Clone,
  78. {
  79. self.read().clone()
  80. }
  81. /// Run a function with a reference to the value. If the value has been dropped, this will panic.
  82. #[track_caller]
  83. fn with<O>(&self, f: impl FnOnce(&Self::Target) -> O) -> O {
  84. f(&*self.read())
  85. }
  86. /// Run a function with a reference to the value. If the value has been dropped, this will panic.
  87. #[track_caller]
  88. fn with_peek<O>(&self, f: impl FnOnce(&Self::Target) -> O) -> O {
  89. f(&*self.peek())
  90. }
  91. /// Index into the inner value and return a reference to the result. If the value has been dropped or the index is invalid, this will panic.
  92. #[track_caller]
  93. fn index<I>(&self, index: I) -> ReadableRef<Self, <Self::Target as std::ops::Index<I>>::Output>
  94. where
  95. Self::Target: std::ops::Index<I>,
  96. {
  97. <Self::Storage as AnyStorage>::map(self.read(), |v| v.index(index))
  98. }
  99. #[doc(hidden)]
  100. fn deref_impl<'a>(&self) -> &'a dyn Fn() -> Self::Target
  101. where
  102. Self: Sized + 'a,
  103. Self::Target: Clone,
  104. {
  105. // https://github.com/dtolnay/case-studies/tree/master/callable-types
  106. // First we create a closure that captures something with the Same in memory layout as Self (MaybeUninit<Self>).
  107. let uninit_callable = MaybeUninit::<Self>::uninit();
  108. // Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
  109. let uninit_closure = move || Self::read(unsafe { &*uninit_callable.as_ptr() }).clone();
  110. // 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.
  111. let size_of_closure = std::mem::size_of_val(&uninit_closure);
  112. assert_eq!(size_of_closure, std::mem::size_of::<Self>());
  113. // Then cast the lifetime of the closure to the lifetime of &self.
  114. fn cast_lifetime<'a, T>(_a: &T, b: &'a T) -> &'a T {
  115. b
  116. }
  117. let reference_to_closure = cast_lifetime(
  118. {
  119. // The real closure that we will never use.
  120. &uninit_closure
  121. },
  122. // 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.
  123. unsafe { std::mem::transmute(self) },
  124. );
  125. // Cast the closure to a trait object.
  126. reference_to_closure as &_
  127. }
  128. }
  129. /// An extension trait for Readable<Vec<T>> that provides some convenience methods.
  130. pub trait ReadableVecExt<T: 'static>: Readable<Target = Vec<T>> {
  131. /// Returns the length of the inner vector.
  132. #[track_caller]
  133. fn len(&self) -> usize {
  134. self.with(|v| v.len())
  135. }
  136. /// Returns true if the inner vector is empty.
  137. #[track_caller]
  138. fn is_empty(&self) -> bool {
  139. self.with(|v| v.is_empty())
  140. }
  141. /// Get the first element of the inner vector.
  142. #[track_caller]
  143. fn first(&self) -> Option<ReadableRef<Self, T>> {
  144. <Self::Storage as AnyStorage>::try_map(self.read(), |v| v.first())
  145. }
  146. /// Get the last element of the inner vector.
  147. #[track_caller]
  148. fn last(&self) -> Option<ReadableRef<Self, T>> {
  149. <Self::Storage as AnyStorage>::try_map(self.read(), |v| v.last())
  150. }
  151. /// Get the element at the given index of the inner vector.
  152. #[track_caller]
  153. fn get(&self, index: usize) -> Option<ReadableRef<Self, T>> {
  154. <Self::Storage as AnyStorage>::try_map(self.read(), |v| v.get(index))
  155. }
  156. /// Get an iterator over the values of the inner vector.
  157. #[track_caller]
  158. fn iter(&self) -> ReadableValueIterator<'_, Self>
  159. where
  160. Self: Sized,
  161. {
  162. ReadableValueIterator {
  163. index: 0,
  164. value: self,
  165. }
  166. }
  167. }
  168. /// An iterator over the values of a `Readable<Vec<T>>`.
  169. pub struct ReadableValueIterator<'a, R> {
  170. index: usize,
  171. value: &'a R,
  172. }
  173. impl<'a, T: 'static, R: Readable<Target = Vec<T>>> Iterator for ReadableValueIterator<'a, R> {
  174. type Item = ReadableRef<'a, R, T>;
  175. fn next(&mut self) -> Option<Self::Item> {
  176. let index = self.index;
  177. self.index += 1;
  178. self.value.get(index)
  179. }
  180. }
  181. impl<T, R> ReadableVecExt<T> for R
  182. where
  183. T: 'static,
  184. R: Readable<Target = Vec<T>>,
  185. {
  186. }
  187. /// An extension trait for Readable<Option<T>> that provides some convenience methods.
  188. pub trait ReadableOptionExt<T: 'static>: Readable<Target = Option<T>> {
  189. /// Unwraps the inner value and clones it.
  190. #[track_caller]
  191. fn unwrap(&self) -> T
  192. where
  193. T: Clone,
  194. {
  195. self.as_ref().unwrap().clone()
  196. }
  197. /// Attempts to read the inner value of the Option.
  198. #[track_caller]
  199. fn as_ref(&self) -> Option<ReadableRef<Self, T>> {
  200. <Self::Storage as AnyStorage>::try_map(self.read(), |v| v.as_ref())
  201. }
  202. }
  203. impl<T, R> ReadableOptionExt<T> for R
  204. where
  205. T: 'static,
  206. R: Readable<Target = Option<T>>,
  207. {
  208. }