1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//! All the types and traits needed for storing and updating lazily computed
//! variables.
//!
//! The key type in this module is [`ComputedVar`](struct.ComputedVar.html).
//! Everything else only exists to be used within it.

use std::cell::{RefCell, Ref};
use std::fmt;
use std::marker::PhantomData;
use crate::{Variable, Node};

pub use crate::system::ComputationHandle;

/// A trait implemented by any item which can be wrapped in a `ComputedVar`.
pub trait ComputedValue {
    /// The value visible within the `ComputedVar`.
    type Value;

    /// The context used by the update function.
    type Context;

    /// Recompute the value of this item.
    fn update(&mut self, ctx: &mut Self::Context, comp: &ComputationHandle);

    /// Cheaply get a reference to the value of this item. This function is free
    /// to panic if `update` has never been called.
    fn read(&self) -> &Self::Value;
}

impl<'a, T, C> ComputedValue for Box<dyn ComputedValue<Value=T, Context=C> + 'a> {
    type Value = T;
    type Context = C;

    fn update(&mut self, ctx: &mut C, comp: &ComputationHandle) {
        ComputedValue::update(&mut **self, ctx, comp)
    }

    fn read(&self) -> &T {
        ComputedValue::read(&**self)
    }
}

/// A computed `T` which is produced by some function `F`.
///
/// Created by the [`ComputedVar::new`](struct.ComputedVar.html#method.new)
/// function or [`computed`](../macro.computed.html) macro.
pub struct FunctionComputed<T, F, C> {
    state: Option<T>,
    update: F,
    context: PhantomData<C>,
}

impl<T, F, C> FunctionComputed<T, F, C> where F: FnMut(&mut C) -> T {
    /// Creates the computed `T`.
    pub fn new(func: F) -> Self {
        FunctionComputed {
            state: None,
            update: func,
            context: PhantomData,
        }
    }
}

static UNUPDATED_VAR_MSG: &str = "computed var has never been updated";

impl<T, F, C> ComputedValue for FunctionComputed<T, F, C>
    where F: FnMut(&mut C) -> T
{
    type Value = T;
    type Context = C;

    fn update(&mut self, ctx: &mut C, _comp: &ComputationHandle) {
        self.state = Some((self.update)(ctx));
    }

    fn read(&self) -> &T {
        self.state.as_ref().expect(UNUPDATED_VAR_MSG)
    }
}

/// A computed `T` which is initialized to some default and then mutated by some
/// function `F`.
///
/// Created by the
/// [`ComputedVar::new_mutate`](struct.ComputedVar.html#method.new_mutate)
/// function or [`computed`](../macro.computed.html) macro.
pub struct MutatorComputed<T, F, C> {
    state: T,
    update: F,
    context: PhantomData<C>,
}

impl<T, F, C> MutatorComputed<T, F, C> where F: FnMut(&mut T, &mut C) {
    /// Creates the computed `T`.
    pub fn new(initial: T, func: F) -> Self {
        MutatorComputed {
            state: initial,
            update: func,
            context: PhantomData,
        }
    }
}

impl<T, F, C> ComputedValue for MutatorComputed<T, F, C>
    where F: FnMut(&mut T, &mut C)
{
    type Value = T;
    type Context = C;

    fn update(&mut self, ctx: &mut C, _comp: &ComputationHandle) {
        (self.update)(&mut self.state, ctx);
    }

    fn read(&self) -> &T {
        &self.state
    }
}

/// A computed `T` which is produced by some function `F` using the value of
/// `V`.
///
/// Created by the
/// [`Variable::map_mutate`](../trait.Variable.html#tymethod.map_mutate)
/// method.
pub struct FunctionMapped<V, T, F> {
    pub(crate) inner: V,
    pub(crate) state: Option<T>,
    pub(crate) update: F,
}

impl<V, T, F> ComputedValue for FunctionMapped<V, T, F>
where
    V: Variable,
    F: FnMut(&V::Value) -> T
{
    type Value = T;
    type Context = ();

    fn update(&mut self, _ctx: &mut (), comp: &ComputationHandle) {
        let mapped = self.inner.get();
        comp.set_reactive_area(false);
        self.state = Some((self.update)(&*mapped));
    }

    fn read(&self) -> &T {
        self.state.as_ref().expect(UNUPDATED_VAR_MSG)
    }
}

/// A computed `T` which is initalized to some default and then mutated by some
/// function `F` which also takes the value of `V`.
///
/// Created by the
/// [`Variable::map_mutate`](../trait.Variable.html#tymethod.map_mutate)
/// method.
pub struct MutatorMapped<V, T, F> {
    pub(crate) inner: V,
    pub(crate) state: T,
    pub(crate) update: F,
}

impl<V, T, F> ComputedValue for MutatorMapped<V, T, F>
where
    V: Variable,
    F: FnMut(&V::Value, &mut T)
{
    type Value = T;
    type Context = ();

    fn update(&mut self, _ctx: &mut (), comp: &ComputationHandle) {
        let mapped = self.inner.get();
        comp.set_reactive_area(false);
        (self.update)(&*mapped, &mut self.state);
    }

    fn read(&self) -> &T {
        &self.state
    }
}

/// A lazily computed variable that is tracked by the reax runtime.
#[must_use]
pub struct ComputedVar<C> {
    node: Node,
    cell: RefCell<C>,
}

impl<C> ComputedVar<C> {
    /// Constructs a computed variable around the given
    /// [`ComputedValue`](trait.ComputedValue.html). The dependencies of the
    /// variable will be determined from the accesses made by the
    /// [`update`](trait.ComputedValue.html#tymethod.update) function. Note
    /// that `update` will not be executed until someone retrieves the value of
    /// this cell.
    pub fn new_raw(value: C) -> Self {
        ComputedVar {
            node: Node::next(),
            cell: RefCell::new(value),
        }
    }
    
    /// Returns a handle to this computation's node in the dependency graph.
    pub fn node(&self) -> &Node {
        &self.node
    }
}

impl<T, F, C> ComputedVar<FunctionComputed<T, F, C>>
    where F: FnMut(&mut C) -> T
{
    /// Constructs a computed variable. The value of the variable will be the
    /// set by the given function when needed. The dependencies of the variable
    /// will be determined from the accesses made by the given function. Note
    /// that the function will not be executed until someone retrieves the value
    /// of this cell.
    ///
    /// To reuse buffers from past executions, use
    /// [`new_mutate`](#method.new_mutate).
    pub fn new(func: F) -> Self {
        Self::new_raw(FunctionComputed::new(func))
    }
}

impl<T, F, C> ComputedVar<MutatorComputed<T, F, C>>
    where F: FnMut(&mut T, &mut C)
{
    /// Constructs a computed variable. This is identical to
    /// [`new`](#method.new) except the value of the variable will be *mutated*
    /// by the given function when needed, not created from scratch.
    pub fn new_mutate(initial: T, func: F) -> Self {
        Self::new_raw(MutatorComputed::new(initial, func))
    }
}

/// A computed cell which is implementation agnostic. The value of the cell and
/// captures of the cell's `update` function are heap-allocated.
pub type BoxedComputedVar<'a, T, C = ()> = ComputedVar<Box<
    dyn ComputedValue<Value=T, Context = C> + 'a
>>;

impl<C: ComputedValue> ComputedVar<C> {
    /// Identical to [`Variable::get`](../trait.Variable#tymethod.get) but
    /// requires the update context.
    pub fn get_contextual(&self, ctx: &mut C::Context) -> Ref<C::Value> {
        self.check(ctx);
        self.node().on_read();
        Ref::map(self.cell.borrow(), |inner| inner.read())
    }

    /// Identical to
    /// [`Variable::get_non_reactive`](../trait.Variable#tymethod.get_non_reactive)
    /// but requires the update context.
    pub fn get_contextual_non_reactive(&self, ctx: &mut C::Context) -> Ref<C::Value> {
        self.check(ctx);
        Ref::map(self.cell.borrow(), |inner| inner.read())
    }

    /// Creates a boxed version of this cell who's type does not depend on how
    /// the cell is updated.
    pub fn boxed<'a>(self) -> BoxedComputedVar<'a, C::Value, C::Context> where Self: 'a {
        ComputedVar {
            node: self.node,
            cell: RefCell::new(Box::new(self.cell.into_inner()) as Box<_>)
        }
    }

    /// Forces the variable to re-compute no matter its current dirty status.
    pub fn force(&self, ctx: &mut C::Context) {
        // Do nothing if already computing.
        if let Ok(mut inner) = self.cell.try_borrow_mut() {
            self.node.on_write(false);
            self.node.computation(|comp| inner.update(ctx, comp));
        }
    }

    /// If changes to upstream variables have made this variable dirty,
    /// re-compute it. Otherwise, do nothing.
    pub fn check(&self, ctx: &mut C::Context) {
        if self.node.is_dirty() {
            self.force(ctx);
        }
    }
}

impl<C: ComputedValue<Context=()>> Variable for ComputedVar<C> {
    type Value = C::Value;

    #[inline(always)]
    fn node(&self) -> &Node { &self.node }

    fn get(&self) -> Ref<C::Value> {
        self.get_contextual(&mut ())
    }

    fn get_non_reactive(&self) -> Ref<C::Value> {
        self.get_contextual_non_reactive(&mut ())
    }
}

impl<C: ComputedValue<Context=()>> fmt::Debug for ComputedVar<C>
    where C::Value: fmt::Debug
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let val = self.get();
        f.debug_struct("Cell")
            .field("id", self.node())
            .field("value", &*val)
            .finish()
    }
}