-
Notifications
You must be signed in to change notification settings - Fork 1
/
lazy_initer.go
79 lines (67 loc) · 1.91 KB
/
lazy_initer.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
package gg
import "sync"
/*
Shortcut for type inference. The following is equivalent:
NewLazyIniter[Val]()
new(LazyIniter[Val, Ptr])
*/
func NewLazyIniter[Val any, Ptr IniterPtr[Val]]() *LazyIniter[Val, Ptr] {
return new(LazyIniter[Val, Ptr])
}
/*
Encapsulates a lazily-initializable value. The first call to `.Get` or `.Ptr`
initializes the underlying value by calling its `.Init` method. Initialization
is performed exactly once. Access is synchronized. All methods are
concurrency-safe. Designed to be embeddable. A zero value is ready to use. When
using this as a struct field, you don't need to explicitly initialize the
field. Contains a mutex and must not be copied.
*/
type LazyIniter[Val any, Ptr IniterPtr[Val]] struct {
val Opt[Val]
lock sync.RWMutex
}
// Returns the underlying value, lazily initializing it on the first call.
func (self *LazyIniter[Val, _]) Get() Val {
out, ok := self.got()
if ok {
return out
}
return self.get()
}
/*
Clears the underlying value. After this call, the next call to `LazyIniter.Get`
or `LazyIniter.Ptr` will reinitialize by invoking the `.Init` method of the
underlying value.
*/
func (self *LazyIniter[_, _]) Clear() {
self.lock.Lock()
defer self.lock.Unlock()
self.val.Clear()
}
/*
Resets the underlying value to the given input. After this call, the underlying
value is considered to be initialized. Further calls to `LazyIniter.Get` or
`LazyIniter.Ptr` will NOT reinitialize until `.Clear` is called.
*/
func (self *LazyIniter[Val, _]) Reset(src Val) {
self.lock.Lock()
defer self.lock.Unlock()
self.val.Set(src)
}
func (self *LazyIniter[Val, _]) got() (_ Val, _ bool) {
self.lock.RLock()
defer self.lock.RUnlock()
if self.val.IsNotNull() {
return self.val.Val, true
}
return
}
func (self *LazyIniter[Val, Ptr]) get() Val {
self.lock.Lock()
defer self.lock.Unlock()
if self.val.IsNull() {
Ptr(&self.val.Val).Init()
self.val.Ok = true
}
return self.val.Val
}