-
Notifications
You must be signed in to change notification settings - Fork 1
/
var.go
92 lines (78 loc) · 2.25 KB
/
var.go
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
package incr
import (
"context"
"fmt"
"sync/atomic"
)
// Var returns a new var node.
//
// [Var] nodes are special nodes in incremental as they let you input data
// into a computation, and specifically change data between stabilization passes.
//
// [Var] nodes include a method [Var.Set] that let you update the value after the initial
// construction. Calling [Var.Set] will mark the [Var] node stale, as well any of the nodes that
// take the [Var] node as an input (i.e. the [Var] node's children).
func Var[T any](scope Scope, t T) VarIncr[T] {
return WithinScope(scope, &varIncr[T]{
n: NewNode("var"),
value: t,
})
}
// VarIncr is a graph node type that implements an incremental variable.
type VarIncr[T any] interface {
Incr[T]
// Set sets the var value.
//
// Calling [Set] will invalidate any nodes that reference this variable.
Set(T)
}
var (
_ VarIncr[string] = (*varIncr[string])(nil)
_ IShouldBeInvalidated = (*varIncr[string])(nil)
_ IStale = (*varIncr[string])(nil)
_ IStabilize = (*varIncr[string])(nil)
_ fmt.Stringer = (*varIncr[string])(nil)
)
type varIncr[T any] struct {
n *Node
setAt uint64
value T
setDuringStabilizationValue T
setDuringStabilization bool
}
func (vn *varIncr[T]) Stale() bool {
return vn.setAt > vn.n.recomputedAt
}
func (vn *varIncr[T]) ShouldBeInvalidated() bool {
return false
}
func (vn *varIncr[T]) Set(v T) {
graph := GraphForNode(vn)
if atomic.LoadInt32(&graph.status) == StatusStabilizing {
vn.setDuringStabilizationValue = v
vn.setDuringStabilization = true
graph.setDuringStabilizationMu.Lock()
graph.setDuringStabilization[vn.Node().id] = vn
graph.setDuringStabilizationMu.Unlock()
return
}
vn.value = v
if vn.n.isNecessary() {
graph.SetStale(vn)
}
}
func (vn *varIncr[T]) Node() *Node { return vn.n }
func (vn *varIncr[T]) Value() T { return vn.value }
func (vn *varIncr[T]) Stabilize(ctx context.Context) error {
if vn.setDuringStabilization {
var zero T
vn.value = vn.setDuringStabilizationValue
vn.setDuringStabilizationValue = zero
vn.setDuringStabilization = false
return nil
}
return nil
}
func (vn *varIncr[T]) String() string {
return vn.n.String()
}