Skip to content

Commit 8848a72

Browse files
committed
Modify the get function in the Memo structure so that it no longer requires a mutable reference
1 parent 82c6d88 commit 8848a72

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

cache/src/memo.rs

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::cell::RefCell;
2+
13
use crate::{Observable, call_stack, remove_from_cache, store_in_cache, touch};
24

35
/// A memoized reactive computation that caches its result and tracks dependencies.
@@ -19,7 +21,7 @@ where
1921
F: Fn() -> T,
2022
{
2123
f: F,
22-
dependents: Vec<&'static dyn Observable>,
24+
dependents: RefCell<Vec<&'static dyn Observable>>,
2325
}
2426

2527
impl<T, F> Observable for Memo<T, F>
@@ -28,7 +30,7 @@ where
2830
{
2931
fn invalidate(&'static self) {
3032
remove_from_cache(self);
31-
self.dependents.iter().for_each(|d| d.invalidate());
33+
self.dependents.borrow().iter().for_each(|d| d.invalidate());
3234
}
3335
}
3436

@@ -48,7 +50,7 @@ where
4850
pub fn new(f: F) -> Self {
4951
Memo {
5052
f,
51-
dependents: vec![],
53+
dependents: vec![].into(),
5254
}
5355
}
5456

@@ -65,14 +67,18 @@ where
6567
/// static mut MEMO: Lazy<Memo<i32, fn() -> i32>> = Lazy::new(|| Memo::new(|| 5));
6668
/// assert_eq!(unsafe { (*MEMO).get() }, 5);
6769
/// ```
68-
pub fn get(&'static mut self) -> T
70+
pub fn get(&'static self) -> T
6971
where
7072
T: Clone,
7173
{
7274
if let Some(last) = call_stack::last()
73-
&& !self.dependents.iter().any(|d| std::ptr::eq(*d, *last))
75+
&& !self
76+
.dependents
77+
.borrow()
78+
.iter()
79+
.any(|d| std::ptr::eq(*d, *last))
7480
{
75-
self.dependents.push(*last);
81+
self.dependents.borrow_mut().push(*last);
7682
}
7783

7884
call_stack::push(self);

0 commit comments

Comments
 (0)