forked from OneOfOne/genh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timed.go
111 lines (98 loc) · 2.07 KB
/
timed.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package genh
import (
"sync"
"sync/atomic"
"time"
)
type tmEle[V any] struct {
sync.RWMutex
la atomic.Int64 // last access / read
v V
t *time.Timer
ttl time.Duration
}
func (e *tmEle[V]) expired() bool {
if e.ttl < 1 {
return false
}
return time.Since(time.Unix(0, e.la.Load())) > e.ttl
}
type TimedMap[K comparable, V any] struct {
m LMap[K, *tmEle[V]]
}
func (tm *TimedMap[K, V]) Set(k K, v V, timeout time.Duration) {
ele := &tmEle[V]{v: v, ttl: timeout}
ele.la.Store(time.Now().UnixNano())
if timeout > 0 {
ele.t = time.AfterFunc(timeout, func() { tm.deleteEle(k, ele) })
}
tm.m.Set(k, ele)
}
func (tm *TimedMap[K, V]) SetUpdateFn(k K, vfn func() V, updateEvery time.Duration) {
tm.SetUpdateExpireFn(k, vfn, updateEvery, -1)
}
func (tm *TimedMap[K, V]) SetUpdateExpireFn(k K, vfn func() V, updateEvery, expireIfNotAccessedFor time.Duration) {
if updateEvery < time.Millisecond {
panic("every must be >= time.Millisecond")
}
ele := &tmEle[V]{ttl: expireIfNotAccessedFor}
ele.la.Store(time.Now().UnixNano())
var upfn func()
upfn = func() {
if ele.expired() {
tm.deleteEle(k, ele)
return
}
v := vfn()
ele.Lock()
if ele.t != nil {
ele.t.Stop()
}
ele.v = v
ele.t = time.AfterFunc(updateEvery, upfn)
ele.Unlock()
}
upfn()
tm.m.Set(k, ele)
}
func (tm *TimedMap[K, V]) Get(k K) (v V) {
v, _ = tm.GetOk(k)
return
}
func (tm *TimedMap[K, V]) GetOk(k K) (v V, ok bool) {
ele := tm.m.Get(k)
if ok = ele != nil && !ele.expired(); ok {
now := time.Now().UnixNano()
ele.RLock()
defer ele.RUnlock()
v = ele.v
ele.la.Store(now)
}
return
}
func (tm *TimedMap[K, V]) DeleteGet(k K) (v V, ok bool) {
ele := tm.m.DeleteGet(k)
if ok = ele != nil && !ele.expired(); ok {
ele.RLock()
defer ele.RUnlock()
v = ele.v
if ele.t != nil {
ele.t.Stop()
}
}
return
}
func (tm *TimedMap[K, V]) Delete(k K) {
if ele := tm.m.DeleteGet(k); ele != nil {
if ele.t != nil {
ele.t.Stop()
}
}
}
func (tm *TimedMap[K, V]) deleteEle(k K, ele *tmEle[V]) {
tm.m.Update(func(m map[K]*tmEle[V]) {
if m[k] == ele {
delete(m, k)
}
})
}