forked from ravendb/ravendb-go-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazy.go
64 lines (52 loc) · 1.17 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
58
59
60
61
62
63
64
package ravendb
import "sync"
// Lazy represents a lazy operation
type Lazy struct {
// function which, when called, executes lazy operation
valueFactory func(interface{}) error
err error
valueCreated bool
Value interface{}
mu sync.Mutex
}
func newLazy(valueFactory func(interface{}) error) *Lazy {
return &Lazy{
valueFactory: valueFactory,
}
}
// IsValueCreated returns true if lazy value has been created
func (l *Lazy) IsValueCreated() bool {
l.mu.Lock()
defer l.mu.Unlock()
if l.err != nil {
return false
}
return l.valueCreated
}
// GetValue executes lazy operation and ensures the Value is set in result variable
// provided in NewLazy()
func (l *Lazy) GetValue(result interface{}) error {
if result == nil {
return newIllegalArgumentError("result cannot be nil")
}
l.mu.Lock()
defer l.mu.Unlock()
if !l.valueCreated {
l.err = l.valueFactory(result)
l.valueCreated = true
if l.err != nil {
l.Value = result
}
}
if l.err != nil {
return l.err
}
if l.Value == nil {
return nil
}
// can call with nil to force evaluation of lazy operations
if result != nil {
setInterfaceToValue(result, l.Value)
}
return nil
}