-
Notifications
You must be signed in to change notification settings - Fork 4
/
ttl_map.go
79 lines (58 loc) · 1.19 KB
/
ttl_map.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 gorabbit
import (
"sync"
"time"
)
type ttlMapValue[V any] struct {
value V
createdAt time.Time
}
type ttlMap[K comparable, V any] struct {
m map[K]ttlMapValue[V]
l sync.Mutex
}
func newTTLMap[K comparable, V any](ln uint64, maxTTL time.Duration) *ttlMap[K, V] {
m := &ttlMap[K, V]{m: make(map[K]ttlMapValue[V], ln)}
go func() {
const tickFraction = 3
for now := range time.Tick(maxTTL / tickFraction) {
m.l.Lock()
for k := range m.m {
issueDate := m.m[k].createdAt
if now.Sub(issueDate) >= maxTTL {
delete(m.m, k)
}
}
m.l.Unlock()
}
}()
return m
}
func (m *ttlMap[K, V]) Len() int {
return len(m.m)
}
func (m *ttlMap[K, V]) Put(k K, v V) {
m.l.Lock()
defer m.l.Unlock()
if _, ok := m.m[k]; !ok {
m.m[k] = ttlMapValue[V]{value: v, createdAt: time.Now()}
}
}
func (m *ttlMap[K, V]) Get(k K) (V, bool) {
m.l.Lock()
defer m.l.Unlock()
v, found := m.m[k]
innerVal := v.value
return innerVal, found
}
func (m *ttlMap[K, V]) ForEach(process func(k K, v V)) {
for key, value := range m.m {
innerVal := value.value
process(key, innerVal)
}
}
func (m *ttlMap[K, V]) Delete(k K) {
m.l.Lock()
defer m.l.Unlock()
delete(m.m, k)
}