-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathlazy.go
57 lines (47 loc) · 1.04 KB
/
lazy.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
package booklit
import "sync"
type Lazy struct {
Block bool
fn func() (Content, error)
result Content
err error
once *sync.Once
}
func LazyFlow(fn func() (Content, error)) *Lazy {
return &Lazy{
Block: false,
fn: fn,
once: &sync.Once{},
}
}
func LazyBlock(fn func() (Content, error)) *Lazy {
return &Lazy{
Block: true,
fn: fn,
once: &sync.Once{},
}
}
// IsFlow returns the value of Block and never delegates to the deferred
// content, i.e. this property must always be known ahead of time.
func (lazy *Lazy) IsFlow() bool {
return !lazy.Block
}
// String returns the string value.
func (lazy *Lazy) String() string {
if lazy.Block {
return "<lazy block>"
} else {
return "<lazy flow>"
}
}
// Visit calls VisitString.
func (lazy *Lazy) Visit(visitor Visitor) error {
return visitor.VisitLazy(lazy)
}
// Force generates the deferred content if needed and returns it.
func (lazy *Lazy) Force() (Content, error) {
lazy.once.Do(func() {
lazy.result, lazy.err = lazy.fn()
})
return lazy.result, lazy.err
}