Skip to content

Commit 88f2463

Browse files
committed
let's have cells and epochs and the cell caches a value...!
NOPE, then you can't return anything from a compute cell
1 parent 90527c7 commit 88f2463

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

exercises/react/example.rs

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,26 @@
11
// TODO: For now, lib is symlinked to example to ease local development.
22
// But the final plan is to provide a stub file once we know what the interface will be.
33

4+
5+
use std::cell::Cell as MutCell;
6+
47
pub trait Cell<T> {
58
fn value(&self) -> &T;
9+
fn epoch(&self) -> usize;
610
}
711

812
pub struct Reactor;
913

1014
pub struct InputCell<T> {
1115
val: T,
16+
epoch: usize,
1217
}
1318

14-
pub struct Compute1Cell<'a, T: 'a, U, F: Fn(&T) -> U> {
19+
pub struct Compute1Cell<'a, T: 'a, U: Copy, F: Fn(&T) -> U> {
1520
compute: F,
1621
cell: &'a Cell<T>,
17-
val: U,
22+
epoch: MutCell<usize>,
23+
val: MutCell<U>,
1824
}
1925

2026
impl Reactor {
@@ -25,14 +31,15 @@ impl Reactor {
2531
pub fn create_input<T>(&self, initial: T) -> InputCell<T> {
2632
InputCell {
2733
val: initial,
34+
epoch: 0,
2835
}
2936
}
3037

31-
pub fn create_compute1<'a, T, U, F>(&self, cell: &'a Cell<T>, compute: F) -> Compute1Cell<'a, T, U, F>
32-
where F: Fn(&T) -> U {
38+
pub fn create_compute1<'a, T, U: Copy, F: Fn(&T) -> U>(&self, cell: &'a Cell<T>, compute: F) -> Compute1Cell<'a, T, U, F> {
3339
Compute1Cell {
34-
val: compute(cell.value()),
40+
val: MutCell::new(compute(cell.value())),
3541
cell: cell,
42+
epoch: MutCell::new(cell.epoch()),
3643
compute: compute,
3744
}
3845
}
@@ -42,6 +49,10 @@ impl <T> Cell<T> for InputCell<T> {
4249
fn value(&self) -> &T {
4350
&self.val
4451
}
52+
53+
fn epoch(&self) -> usize {
54+
self.epoch
55+
}
4556
}
4657

4758
impl <T> InputCell<T> {
@@ -50,8 +61,16 @@ impl <T> InputCell<T> {
5061
}
5162
}
5263

53-
impl <'a, T, U, F: Fn(&T) -> U> Cell<U> for Compute1Cell<'a, T, U, F> {
64+
impl <'a, T, U: Copy, F: Fn(&T) -> U> Cell<U> for Compute1Cell<'a, T, U, F> {
5465
fn value(&self) -> &U {
55-
&self.val
66+
if self.epoch() < self.cell.epoch() {
67+
self.epoch.set(self.cell.epoch());
68+
self.val.set((self.compute)(self.cell.value()));
69+
}
70+
&self.val.get().clone()
71+
}
72+
73+
fn epoch(&self) -> usize {
74+
self.epoch.get()
5675
}
5776
}

0 commit comments

Comments
 (0)