-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmemo.go
79 lines (64 loc) · 1.38 KB
/
memo.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 memo
import (
"sync"
"time"
)
type (
Memo struct {
f Func
mu sync.Mutex //guards cache
cache *entry
cacheDur time.Duration
lastCache time.Time
}
Func func() (interface{}, error)
)
type (
entry struct {
res result
ready chan struct{} // close when res is read
}
result struct {
value interface{}
err error
}
)
func New(f Func, cd time.Duration) *Memo {
return &Memo{
f: f,
cacheDur: cd,
}
}
// Invalidate resets the cache to nil if the memo's given cache duration has
// elapsed, and returns true if the cache was actually invalidated.
func (memo *Memo) Invalidate() bool {
defer memo.mu.Unlock()
memo.mu.Lock()
if memo.cache != nil && time.Now().Sub(memo.lastCache) > memo.cacheDur {
memo.cache = nil
memo.lastCache = time.Now()
return true
}
return false
}
func (memo *Memo) Get() (value interface{}, err error) {
memo.mu.Lock()
if memo.cache == nil {
memo.cache = &entry{ready: make(chan struct{})}
memo.mu.Unlock()
memo.cache.res.value, memo.cache.res.err = memo.f()
close(memo.cache.ready)
} else {
memo.mu.Unlock()
<-memo.cache.ready
}
return memo.cache.res.value, memo.cache.res.err
}
// Reset forcibly resets the cache to nil without checking if the cache
// duration has elapsed.
func (memo *Memo) Reset() {
defer memo.mu.Unlock()
memo.mu.Lock()
memo.cache = nil
memo.lastCache = time.Now()
}