anchors 0.6.0

async incremental computations
Documentation
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use super::{Anchor, AnchorInner, Engine};
use std::panic::Location;

mod cutoff;
mod map;
mod map_mut;
mod refmap;
mod then;

/// A trait automatically implemented for all Anchors.
/// You'll likely want to `use` this trait in most of your programs, since it can create many
/// useful Anchors that derive their output incrementally from some other Anchors.
///
/// AnchorExt is also implemented for all tuples of up to 9 Anchor references. For example, you can combine three
/// values incrementally into a tuple with:
///
/// ```
/// use anchors::singlethread::Engine;
/// use anchors::expert::{Constant, AnchorExt};
/// let mut engine = Engine::new();
/// let a = Constant::new(1);
/// let b = Constant::new(2);
/// let c = Constant::new("hello");
///
/// // here we use AnchorExt to map three values together:
/// let res = (&a, &b, &c).map(|a_val, b_val, c_val| (*a_val, *b_val, *c_val));
///
/// assert_eq!((1, 2, "hello"), engine.get(&res));
/// ```
pub trait AnchorExt<E: Engine>: Sized {
    type Target;

    /// Creates an Anchor that maps a number of incremental input values to some output value.
    /// The function `f` accepts inputs as references, and must return an owned value.
    /// `f` will always be recalled any time any input value changes.
    /// For example, you can add two numbers together with `map`:
    ///
    /// ```
    /// use anchors::singlethread::Engine;
    /// use anchors::expert::{Constant, AnchorExt, Anchor};
    /// let mut engine = Engine::new();
    /// let a = Constant::new(1);
    /// let b = Constant::new(2);
    ///
    /// // add the two numbers together; types have been added for clarity but are optional:
    /// let res: Anchor<usize, Engine> = (&a, &b).map(|a_val: &usize, b_val: &usize| -> usize {
    ///    *a_val+*b_val
    /// });
    ///
    /// assert_eq!(3, engine.get(&res));
    /// ```
    fn map<F, Out>(self, f: F) -> Anchor<Out, E>
    where
        Out: 'static,
        F: 'static,
        map::Map<Self::Target, F, Out>: AnchorInner<E, Output = Out>;

    fn map_mut<F, Out>(self, initial: Out, f: F) -> Anchor<Out, E>
    where
        Out: 'static,
        F: 'static,
        map_mut::MapMut<Self::Target, F, Out>: AnchorInner<E, Output = Out>;

    /// Creates an Anchor that maps a number of incremental input values to some output Anchor.
    /// With `then`, your computation graph can dynamically select an Anchor to recalculate based
    /// on some other incremental computation..
    /// The function `f` accepts inputs as references, and must return an owned `Anchor`.
    /// `f` will always be recalled any time any input value changes.
    ///
    /// For example, you can select which of two additions gets calculated:
    ///
    /// ```
    /// use anchors::singlethread::Engine;
    /// use anchors::expert::{Constant, AnchorExt, Anchor};
    /// let mut engine = Engine::new();
    /// let decision = Constant::new(true);
    /// let num = Constant::new(1);
    ///
    /// // because of how we're using the `then` below, only one of these two
    /// // additions will actually be run
    /// let a = num.map(|num| *num + 1);
    /// let b = num.map(|num| *num + 2);
    ///
    /// // types have been added for clarity but are optional:
    /// let res: Anchor<usize, Engine> = decision.then(move |decision: &bool| {
    ///     if *decision {
    ///         a.clone()
    ///     } else {
    ///         b.clone()
    ///     }
    /// });
    ///
    /// assert_eq!(2, engine.get(&res));
    /// ```
    fn then<F, Out>(self, f: F) -> Anchor<Out, E>
    where
        F: 'static,
        Out: 'static,
        then::Then<Self::Target, Out, F, E>: AnchorInner<E, Output = Out>;

    /// Creates an Anchor that outputs its input. However, even if a value changes
    /// you may not want to recompute downstream nodes unless the value changes substantially.
    /// The function `f` accepts inputs as references, and must return true if Anchors that derive
    /// values from this cutoff should recalculate, or false if derivative Anchors should not recalculate.
    /// If this is the first calculation, `f` will be called, but return values of `false` will be ignored.
    /// `f` will always be recalled any time the input value changes.
    /// For example, you can only perform an addition if an input changes by more than 10:
    ///
    /// ```
    /// use anchors::singlethread::Engine;
    /// use anchors::expert::{Anchor, Var, AnchorExt};
    /// let mut engine = Engine::new();
    /// let (num, set_num) = Var::new(1i32);
    /// let cutoff = {
    ///     let mut old_num_opt: Option<i32> = None;
    ///     num.cutoff(move |num| {
    ///         if let Some(old_num) = old_num_opt {
    ///             if (old_num - *num).abs() < 10 {
    ///                 return false;
    ///             }
    ///         }
    ///         old_num_opt = Some(*num);
    ///         true
    ///     })
    /// };
    /// let res = cutoff.map(|cutoff| *cutoff + 1);
    ///
    /// assert_eq!(2, engine.get(&res));
    ///
    /// // small changes don't cause recalculations
    /// set_num.set(5);
    /// assert_eq!(2, engine.get(&res));
    ///
    /// // but big changes do
    /// set_num.set(11);
    /// assert_eq!(12, engine.get(&res));
    /// ```
    fn cutoff<F, Out>(self, _f: F) -> Anchor<Out, E>
    where
        Out: 'static,
        F: 'static,
        cutoff::Cutoff<Self::Target, F>: AnchorInner<E, Output = Out>;

    /// Creates an Anchor that maps some input reference to some output reference.
    /// Performance is critical here: `f` will always be recalled any time any downstream node
    /// requests the value of this Anchor, *not* just when an input value changes.
    /// It's also critical to note that due to constraints
    /// with Rust's lifetime system, these output references can not be owned values, and must
    /// live exactly as long as the input reference.
    /// For example, you can lookup a particular value inside a tuple without cloning:
    ///
    /// ```
    /// use anchors::singlethread::Engine;
    /// use anchors::expert::{Anchor, Constant, AnchorExt};
    /// struct CantClone {val: usize};
    /// let mut engine = Engine::new();
    /// let tuple = Constant::new((CantClone{val: 1}, CantClone{val: 2}));
    ///
    /// // lookup the first value inside the tuple; types have been added for clarity but are optional:
    /// let res: Anchor<CantClone, Engine> = tuple.refmap(|tuple: &(CantClone, CantClone)| -> &CantClone {
    ///    &tuple.0
    /// });
    ///
    /// // check if the cantclone value is correct:
    /// let is_one = res.map(|tuple: &CantClone| -> bool {
    ///    tuple.val == 1
    /// });
    ///
    /// assert_eq!(true, engine.get(&is_one));
    /// ```
    fn refmap<F, Out>(self, _f: F) -> Anchor<Out, E>
    where
        Out: 'static,
        F: 'static,
        refmap::RefMap<Self::Target, F>: AnchorInner<E, Output = Out>;
}

pub trait AnchorSplit<E: Engine>: Sized {
    type Target;
    fn split(&self) -> Self::Target;
}

impl<O1, E> AnchorExt<E> for &Anchor<O1, E>
where
    O1: 'static,
    E: Engine,
{
    type Target = (Anchor<O1, E>,);

    #[track_caller]
    fn map<F, Out>(self, f: F) -> Anchor<Out, E>
    where
        Out: 'static,
        F: 'static,
        map::Map<Self::Target, F, Out>: AnchorInner<E, Output = Out>,
    {
        E::mount(map::Map {
            anchors: (self.clone(),),
            f,
            output: None,
            output_stale: true,
            location: Location::caller(),
        })
    }

    #[track_caller]
    fn map_mut<F, Out>(self, initial: Out, f: F) -> Anchor<Out, E>
    where
        Out: 'static,
        F: 'static,
        map_mut::MapMut<Self::Target, F, Out>: AnchorInner<E, Output = Out>,
    {
        E::mount(map_mut::MapMut {
            anchors: (self.clone(),),
            f,
            output: initial,
            output_stale: true,
            location: Location::caller(),
        })
    }

    #[track_caller]
    fn then<F, Out>(self, f: F) -> Anchor<Out, E>
    where
        F: 'static,
        Out: 'static,
        then::Then<Self::Target, Out, F, E>: AnchorInner<E, Output = Out>,
    {
        E::mount(then::Then {
            anchors: (self.clone(),),
            f,
            f_anchor: None,
            location: Location::caller(),
            lhs_stale: true,
        })
    }

    #[track_caller]
    fn refmap<F, Out>(self, f: F) -> Anchor<Out, E>
    where
        Out: 'static,
        F: 'static,
        refmap::RefMap<Self::Target, F>: AnchorInner<E, Output = Out>,
    {
        E::mount(refmap::RefMap {
            anchors: (self.clone(),),
            f,
            location: Location::caller(),
        })
    }

    #[track_caller]
    fn cutoff<F, Out>(self, f: F) -> Anchor<Out, E>
    where
        Out: 'static,
        F: 'static,
        cutoff::Cutoff<Self::Target, F>: AnchorInner<E, Output = Out>,
    {
        E::mount(cutoff::Cutoff {
            anchors: (self.clone(),),
            f,
            location: Location::caller(),
        })
    }
}

macro_rules! impl_tuple_ext {
    ($([$output_type:ident, $num:tt])+) => {
        impl <$($output_type,)+ E> AnchorSplit<E> for Anchor<($($output_type,)+), E>
        where
            $(
                $output_type: Clone + PartialEq + 'static,
            )+
            E: Engine,
        {
            type Target = ($(Anchor<$output_type, E>,)+);

            fn split(&self) -> Self::Target {
                ($(
                    self.refmap(|v| &v.$num),
                )+)
            }
        }

        impl<$($output_type,)+ E> AnchorExt<E> for ($(&Anchor<$output_type, E>,)+)
        where
            $(
                $output_type: 'static,
            )+
            E: Engine,
        {
            type Target = ($(Anchor<$output_type, E>,)+);

            #[track_caller]
            fn map<F, Out>(self, f: F) -> Anchor<Out, E>
            where
                Out: 'static,
                F: 'static,
                map::Map<Self::Target, F, Out>: AnchorInner<E, Output=Out>,
            {
                E::mount(map::Map {
                    anchors: ($(self.$num.clone(),)+),
                    f,
                    output: None,
                    output_stale: true,
                    location: Location::caller(),
                })
            }

            #[track_caller]
            fn map_mut<F, Out>(self, initial: Out, f: F) -> Anchor<Out, E>
            where
                Out: 'static,
                F: 'static,
                map_mut::MapMut<Self::Target, F, Out>: AnchorInner<E, Output=Out>,
            {
                E::mount(map_mut::MapMut {
                    anchors: ($(self.$num.clone(),)+),
                    f,
                    output: initial,
                    output_stale: true,
                    location: Location::caller(),
                })
            }

            #[track_caller]
            fn then<F, Out>(self, f: F) -> Anchor<Out, E>
            where
                F: 'static,
                Out: 'static,
                then::Then<Self::Target, Out, F, E>: AnchorInner<E, Output=Out>,
            {
                E::mount(then::Then {
                    anchors: ($(self.$num.clone(),)+),
                    f,
                    f_anchor: None,
                    location: Location::caller(),
                    lhs_stale: true,
                })
            }

            #[track_caller]
            fn refmap<F, Out>(self, f: F) -> Anchor<Out, E>
            where
                Out: 'static,
                F: 'static,
                refmap::RefMap<Self::Target, F>: AnchorInner<E, Output = Out>,
            {
                E::mount(refmap::RefMap {
                    anchors: ($(self.$num.clone(),)+),
                    f,
                    location: Location::caller(),
                })
            }

            #[track_caller]
            fn cutoff<F, Out>(self, f: F) -> Anchor<Out, E>
            where
                Out: 'static,
                F: 'static,
                cutoff::Cutoff<Self::Target, F>: AnchorInner<E, Output = Out>,
            {
                E::mount(cutoff::Cutoff {
                    anchors: ($(self.$num.clone(),)+),
                    f,
                    location: Location::caller(),
                })
            }
        }
    }
}

impl_tuple_ext! {
    [O0, 0]
}

impl_tuple_ext! {
    [O0, 0]
    [O1, 1]
}

impl_tuple_ext! {
    [O0, 0]
    [O1, 1]
    [O2, 2]
}

impl_tuple_ext! {
    [O0, 0]
    [O1, 1]
    [O2, 2]
    [O3, 3]
}

impl_tuple_ext! {
    [O0, 0]
    [O1, 1]
    [O2, 2]
    [O3, 3]
    [O4, 4]
}

impl_tuple_ext! {
    [O0, 0]
    [O1, 1]
    [O2, 2]
    [O3, 3]
    [O4, 4]
    [O5, 5]
}

impl_tuple_ext! {
    [O0, 0]
    [O1, 1]
    [O2, 2]
    [O3, 3]
    [O4, 4]
    [O5, 5]
    [O6, 6]
}

impl_tuple_ext! {
    [O0, 0]
    [O1, 1]
    [O2, 2]
    [O3, 3]
    [O4, 4]
    [O5, 5]
    [O6, 6]
    [O7, 7]
}

impl_tuple_ext! {
    [O0, 0]
    [O1, 1]
    [O2, 2]
    [O3, 3]
    [O4, 4]
    [O5, 5]
    [O6, 6]
    [O7, 7]
    [O8, 8]
}