impls.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. use crate::rt::CopyValue;
  2. use crate::signal::{ReadOnlySignal, Signal, Write};
  3. use crate::SignalData;
  4. use generational_box::Mappable;
  5. use generational_box::{MappableMut, Storage};
  6. use std::{
  7. fmt::{Debug, Display},
  8. ops::{Add, Div, Mul, Sub},
  9. };
  10. macro_rules! read_impls {
  11. ($ty:ident, $bound:path) => {
  12. impl<T: Default + 'static, S: $bound> Default for $ty<T, S> {
  13. fn default() -> Self {
  14. Self::new_maybe_sync(Default::default())
  15. }
  16. }
  17. impl<T, S: $bound> std::clone::Clone for $ty<T, S> {
  18. fn clone(&self) -> Self {
  19. *self
  20. }
  21. }
  22. impl<T, S: $bound + Copy> Copy for $ty<T, S> {}
  23. impl<T: Display + 'static, S: $bound> Display for $ty<T, S> {
  24. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  25. self.with(|v| Display::fmt(v, f))
  26. }
  27. }
  28. impl<T: Debug + 'static, S: $bound> Debug for $ty<T, S> {
  29. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  30. self.with(|v| Debug::fmt(v, f))
  31. }
  32. }
  33. };
  34. }
  35. macro_rules! write_impls {
  36. ($ty:ident, $bound:path, $vec_bound:path) => {
  37. impl<T: Add<Output = T> + Copy + 'static, S: $bound> std::ops::Add<T> for $ty<T, S> {
  38. type Output = T;
  39. fn add(self, rhs: T) -> Self::Output {
  40. self.with(|v| *v + rhs)
  41. }
  42. }
  43. impl<T: Add<Output = T> + Copy + 'static, S: $bound> std::ops::AddAssign<T> for $ty<T, S> {
  44. fn add_assign(&mut self, rhs: T) {
  45. self.with_mut(|v| *v = *v + rhs)
  46. }
  47. }
  48. impl<T: Sub<Output = T> + Copy + 'static, S: $bound> std::ops::SubAssign<T> for $ty<T, S> {
  49. fn sub_assign(&mut self, rhs: T) {
  50. self.with_mut(|v| *v = *v - rhs)
  51. }
  52. }
  53. impl<T: Sub<Output = T> + Copy + 'static, S: $bound> std::ops::Sub<T> for $ty<T, S> {
  54. type Output = T;
  55. fn sub(self, rhs: T) -> Self::Output {
  56. self.with(|v| *v - rhs)
  57. }
  58. }
  59. impl<T: Mul<Output = T> + Copy + 'static, S: $bound> std::ops::MulAssign<T> for $ty<T, S> {
  60. fn mul_assign(&mut self, rhs: T) {
  61. self.with_mut(|v| *v = *v * rhs)
  62. }
  63. }
  64. impl<T: Mul<Output = T> + Copy + 'static, S: $bound> std::ops::Mul<T> for $ty<T, S> {
  65. type Output = T;
  66. fn mul(self, rhs: T) -> Self::Output {
  67. self.with(|v| *v * rhs)
  68. }
  69. }
  70. impl<T: Div<Output = T> + Copy + 'static, S: $bound> std::ops::DivAssign<T> for $ty<T, S> {
  71. fn div_assign(&mut self, rhs: T) {
  72. self.with_mut(|v| *v = *v / rhs)
  73. }
  74. }
  75. impl<T: Div<Output = T> + Copy + 'static, S: $bound> std::ops::Div<T> for $ty<T, S> {
  76. type Output = T;
  77. fn div(self, rhs: T) -> Self::Output {
  78. self.with(|v| *v / rhs)
  79. }
  80. }
  81. impl<T: 'static, S: $vec_bound> $ty<Vec<T>, S> {
  82. /// Pushes a new value to the end of the vector.
  83. pub fn push(&self, value: T) {
  84. self.with_mut(|v| v.push(value))
  85. }
  86. /// Pops the last value from the vector.
  87. pub fn pop(&self) -> Option<T> {
  88. self.with_mut(|v| v.pop())
  89. }
  90. /// Inserts a new value at the given index.
  91. pub fn insert(&self, index: usize, value: T) {
  92. self.with_mut(|v| v.insert(index, value))
  93. }
  94. /// Removes the value at the given index.
  95. pub fn remove(&self, index: usize) -> T {
  96. self.with_mut(|v| v.remove(index))
  97. }
  98. /// Clears the vector, removing all values.
  99. pub fn clear(&self) {
  100. self.with_mut(|v| v.clear())
  101. }
  102. /// Extends the vector with the given iterator.
  103. pub fn extend(&self, iter: impl IntoIterator<Item = T>) {
  104. self.with_mut(|v| v.extend(iter))
  105. }
  106. /// Truncates the vector to the given length.
  107. pub fn truncate(&self, len: usize) {
  108. self.with_mut(|v| v.truncate(len))
  109. }
  110. /// Swaps two values in the vector.
  111. pub fn swap_remove(&self, index: usize) -> T {
  112. self.with_mut(|v| v.swap_remove(index))
  113. }
  114. /// Retains only the values that match the given predicate.
  115. pub fn retain(&self, f: impl FnMut(&T) -> bool) {
  116. self.with_mut(|v| v.retain(f))
  117. }
  118. /// Splits the vector into two at the given index.
  119. pub fn split_off(&self, at: usize) -> Vec<T> {
  120. self.with_mut(|v| v.split_off(at))
  121. }
  122. }
  123. };
  124. }
  125. read_impls!(CopyValue, Storage<T>);
  126. impl<T: 'static, S: Storage<Vec<T>>> CopyValue<Vec<T>, S> {
  127. /// Read a value from the inner vector.
  128. pub fn get(&self, index: usize) -> Option<<S::Ref as Mappable<Vec<T>>>::Mapped<T>> {
  129. S::Ref::try_map(self.read(), move |v| v.get(index))
  130. }
  131. }
  132. impl<T: 'static, S: Storage<Option<T>>> CopyValue<Option<T>, S> {
  133. /// Unwraps the inner value and clones it.
  134. pub fn unwrap(&self) -> T
  135. where
  136. T: Clone,
  137. {
  138. self.with(|v| v.clone()).unwrap()
  139. }
  140. /// Attempts to read the inner value of the Option.
  141. pub fn as_ref(&self) -> Option<<S::Ref as Mappable<Option<T>>>::Mapped<T>> {
  142. S::Ref::try_map(self.read(), |v| v.as_ref())
  143. }
  144. }
  145. write_impls!(CopyValue, Storage<T>, Storage<Vec<T>>);
  146. impl<T: 'static, S: Storage<Option<T>>> CopyValue<Option<T>, S> {
  147. /// Takes the value out of the Option.
  148. pub fn take(&self) -> Option<T> {
  149. self.with_mut(|v| v.take())
  150. }
  151. /// Replace the value in the Option.
  152. pub fn replace(&self, value: T) -> Option<T> {
  153. self.with_mut(|v| v.replace(value))
  154. }
  155. /// Gets the value out of the Option, or inserts the given value if the Option is empty.
  156. pub fn get_or_insert(&self, default: T) -> <S::Ref as Mappable<Option<T>>>::Mapped<T> {
  157. self.get_or_insert_with(|| default)
  158. }
  159. /// Gets the value out of the Option, or inserts the value returned by the given function if the Option is empty.
  160. pub fn get_or_insert_with(
  161. &self,
  162. default: impl FnOnce() -> T,
  163. ) -> <S::Ref as Mappable<Option<T>>>::Mapped<T> {
  164. let borrow = self.read();
  165. if borrow.is_none() {
  166. drop(borrow);
  167. self.with_mut(|v| *v = Some(default()));
  168. S::Ref::map(self.read(), |v| v.as_ref().unwrap())
  169. } else {
  170. S::Ref::map(borrow, |v| v.as_ref().unwrap())
  171. }
  172. }
  173. }
  174. read_impls!(Signal, Storage<SignalData<T>>);
  175. impl<T: 'static, S: Storage<SignalData<Vec<T>>>> Signal<Vec<T>, S> {
  176. /// Read a value from the inner vector.
  177. pub fn get(
  178. &self,
  179. index: usize,
  180. ) -> Option<
  181. <<<S as Storage<SignalData<Vec<T>>>>::Ref as Mappable<SignalData<Vec<T>>>>::Mapped<Vec<T>> as Mappable<
  182. Vec<T>,
  183. >>::Mapped<T>,
  184. >{
  185. <<S as Storage<SignalData<Vec<T>>>>::Ref as Mappable<SignalData<Vec<T>>>>::Mapped::<Vec<T>>::try_map(self.read(), move |v| v.get(index))
  186. }
  187. }
  188. impl<T: 'static, S: Storage<SignalData<Option<T>>>> Signal<Option<T>, S> {
  189. /// Unwraps the inner value and clones it.
  190. pub fn unwrap(&self) -> T
  191. where
  192. T: Clone,
  193. {
  194. self.with(|v| v.clone()).unwrap()
  195. }
  196. /// Attempts to read the inner value of the Option.
  197. pub fn as_ref(
  198. &self,
  199. ) -> Option<
  200. <<<S as Storage<SignalData<Option<T>>>>::Ref as Mappable<SignalData<Option<T>>>>::Mapped<
  201. Option<T>,
  202. > as Mappable<Option<T>>>::Mapped<T>,
  203. > {
  204. <<S as Storage<SignalData<Option<T>>>>::Ref as Mappable<SignalData<Option<T>>>>::Mapped::<
  205. Option<T>,
  206. >::try_map(self.read(), |v| v.as_ref())
  207. }
  208. }
  209. write_impls!(Signal, Storage<SignalData<T>>, Storage<SignalData<Vec<T>>>);
  210. impl<T: 'static, S: Storage<SignalData<Option<T>>>> Signal<Option<T>, S> {
  211. /// Takes the value out of the Option.
  212. pub fn take(&self) -> Option<T> {
  213. self.with_mut(|v| v.take())
  214. }
  215. /// Replace the value in the Option.
  216. pub fn replace(&self, value: T) -> Option<T> {
  217. self.with_mut(|v| v.replace(value))
  218. }
  219. /// Gets the value out of the Option, or inserts the given value if the Option is empty.
  220. pub fn get_or_insert(&self, default: T) -> <<S::Ref as Mappable<SignalData<Option<T>>>>::Mapped<Option<T>> as Mappable<Option<T>>>::Mapped<T>{
  221. self.get_or_insert_with(|| default)
  222. }
  223. /// Gets the value out of the Option, or inserts the value returned by the given function if the Option is empty.
  224. pub fn get_or_insert_with(
  225. &self,
  226. default: impl FnOnce() -> T,
  227. ) -><<S::Ref as Mappable<SignalData<Option<T>>>>::Mapped<Option<T>> as Mappable<Option<T>>>::Mapped<T>{
  228. let borrow = self.read();
  229. if borrow.is_none() {
  230. drop(borrow);
  231. self.with_mut(|v| *v = Some(default()));
  232. <S::Ref as Mappable<SignalData<Option<T>>>>::Mapped::<Option<T>>::map(
  233. self.read(),
  234. |v| v.as_ref().unwrap(),
  235. )
  236. } else {
  237. <S::Ref as Mappable<SignalData<Option<T>>>>::Mapped::<Option<T>>::map(borrow, |v| {
  238. v.as_ref().unwrap()
  239. })
  240. }
  241. }
  242. }
  243. read_impls!(ReadOnlySignal, Storage<SignalData<T>>);
  244. /// An iterator over the values of a `CopyValue<Vec<T>>`.
  245. pub struct CopyValueIterator<T: 'static, S: Storage<Vec<T>>> {
  246. index: usize,
  247. value: CopyValue<Vec<T>, S>,
  248. }
  249. impl<T: Clone, S: Storage<Vec<T>>> Iterator for CopyValueIterator<T, S> {
  250. type Item = T;
  251. fn next(&mut self) -> Option<Self::Item> {
  252. let index = self.index;
  253. self.index += 1;
  254. self.value.get(index).map(|v| v.clone())
  255. }
  256. }
  257. impl<T: Clone + 'static, S: Storage<Vec<T>>> IntoIterator for CopyValue<Vec<T>, S> {
  258. type IntoIter = CopyValueIterator<T, S>;
  259. type Item = T;
  260. fn into_iter(self) -> Self::IntoIter {
  261. CopyValueIterator {
  262. index: 0,
  263. value: self,
  264. }
  265. }
  266. }
  267. impl<T: 'static, S: Storage<Vec<T>>> CopyValue<Vec<T>, S> {
  268. /// Write to an element in the inner vector.
  269. pub fn get_mut(&self, index: usize) -> Option<<S::Mut as MappableMut<Vec<T>>>::Mapped<T>> {
  270. S::Mut::try_map(self.write(), |v: &mut Vec<T>| v.get_mut(index))
  271. }
  272. }
  273. impl<T: 'static, S: Storage<Option<T>>> CopyValue<Option<T>, S> {
  274. /// Deref the inner value mutably.
  275. pub fn as_mut(
  276. &self,
  277. ) -> Option<<<S as Storage<Option<T>>>::Mut as MappableMut<Option<T>>>::Mapped<T>> {
  278. S::Mut::try_map(self.write(), |v: &mut Option<T>| v.as_mut())
  279. }
  280. }
  281. /// An iterator over items in a `Signal<Vec<T>>`.
  282. pub struct SignalIterator<T: 'static, S: Storage<SignalData<Vec<T>>>> {
  283. index: usize,
  284. value: Signal<Vec<T>, S>,
  285. }
  286. impl<T: Clone, S: Storage<SignalData<Vec<T>>>> Iterator for SignalIterator<T, S> {
  287. type Item = T;
  288. fn next(&mut self) -> Option<Self::Item> {
  289. let index = self.index;
  290. self.index += 1;
  291. self.value.get(index).map(|v| v.clone())
  292. }
  293. }
  294. impl<T: Clone + 'static, S: Storage<SignalData<Vec<T>>>> IntoIterator for Signal<Vec<T>, S> {
  295. type IntoIter = SignalIterator<T, S>;
  296. type Item = T;
  297. fn into_iter(self) -> Self::IntoIter {
  298. SignalIterator {
  299. index: 0,
  300. value: self,
  301. }
  302. }
  303. }
  304. impl<T: 'static, S: Storage<SignalData<Vec<T>>>> Signal<Vec<T>, S>
  305. where
  306. <<S as Storage<SignalData<std::vec::Vec<T>>>>::Mut as MappableMut<
  307. SignalData<std::vec::Vec<T>>,
  308. >>::Mapped<std::vec::Vec<T>>: MappableMut<std::vec::Vec<T>>,
  309. {
  310. /// Returns a reference to an element or `None` if out of bounds.
  311. pub fn get_mut(
  312. &self,
  313. index: usize,
  314. ) -> Option<
  315. Write<
  316. T,
  317. <<<S as Storage<SignalData<Vec<T>>>>::Mut as MappableMut<SignalData<Vec<T>>>>::Mapped<
  318. Vec<T>,
  319. > as MappableMut<Vec<T>>>::Mapped<T>,
  320. S,
  321. Vec<T>,
  322. >,
  323. > {
  324. Write::filter_map(self.write(), |v| v.get_mut(index))
  325. }
  326. }
  327. impl<T: 'static, S: Storage<SignalData<Option<T>>>> Signal<Option<T>, S> {
  328. /// Returns a reference to an element or `None` if out of bounds.
  329. pub fn as_mut(&self) -> Option<Write<T, <<<S as Storage<SignalData<Option<T>>>>::Mut as MappableMut<SignalData<Option<T>>>>::Mapped<Option<T>> as MappableMut<Option<T>>>::Mapped<T>, S, Option<T>>>{
  330. Write::filter_map(self.write(), |v| v.as_mut())
  331. }
  332. }