-
Notifications
You must be signed in to change notification settings - Fork 6
/
ttlMap.go
133 lines (115 loc) · 2.56 KB
/
ttlMap.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
TtlMap.go
-John Taylor
2023-10-21
TtlMap is a "time-to-live" map such that after a given amount of time, items
in the map are deleted.
When a Put() occurs, the lastAccess time is set to time.Now().Unix()
When a Get() occurs, the lastAccess time is updated to time.Now().Unix()
Therefore, only items that are not called by Get() will be deleted after the TTL occurs.
A GetNoUpdate() can be used in which case the lastAccess time will NOT be updated.
Adopted from: https://stackoverflow.com/a/25487392/452281
*/
package TtlMap
import (
"maps"
"sync"
"time"
)
const version string = "1.5.1"
type CustomKeyType interface {
comparable
}
type item struct {
Value interface{}
lastAccess int64
}
type TtlMap[T CustomKeyType] struct {
m map[T]*item
l sync.Mutex
refresh bool
stop chan bool
}
func New[T CustomKeyType](maxTTL time.Duration, ln int, pruneInterval time.Duration, refreshLastAccessOnGet bool) (m *TtlMap[T]) {
// if pruneInterval > maxTTL {
// print("WARNING: TtlMap: pruneInterval > maxTTL\n")
// }
m = &TtlMap[T]{m: make(map[T]*item, ln), stop: make(chan bool)}
m.refresh = refreshLastAccessOnGet
maxTTL /= 1000000000
// print("maxTTL: ", maxTTL, "\n")
go func() {
for {
select {
case <-m.stop:
return
case now := <-time.Tick(pruneInterval):
currentTime := now.Unix()
m.l.Lock()
for k, v := range m.m {
// print("TICK:", currentTime, " ", v.lastAccess, " ", currentTime-v.lastAccess, " ", maxTTL, " ", k, "\n")
if currentTime-v.lastAccess >= int64(maxTTL) {
delete(m.m, k)
// print("deleting: ", k, "\n")
}
}
// print("----\n")
m.l.Unlock()
}
}
}()
return
}
func (m *TtlMap[T]) Len() int {
return len(m.m)
}
func (m *TtlMap[T]) Put(k T, v interface{}) {
m.l.Lock()
m.m[k] = &item{Value: v, lastAccess: time.Now().Unix()}
m.l.Unlock()
}
func (m *TtlMap[T]) Get(k T) (v interface{}) {
m.l.Lock()
if it, ok := m.m[k]; ok {
v = it.Value
if m.refresh {
m.m[k].lastAccess = time.Now().Unix()
}
}
m.l.Unlock()
return
}
func (m *TtlMap[T]) GetNoUpdate(k T) (v interface{}) {
m.l.Lock()
if it, ok := m.m[k]; ok {
v = it.Value
}
m.l.Unlock()
return
}
func (m *TtlMap[T]) Delete(k T) bool {
m.l.Lock()
_, ok := m.m[k]
if !ok {
m.l.Unlock()
return false
}
delete(m.m, k)
m.l.Unlock()
return true
}
func (m *TtlMap[T]) Clear() {
m.l.Lock()
clear(m.m)
m.l.Unlock()
}
func (m *TtlMap[T]) All() map[T]*item {
m.l.Lock()
dst := make(map[T]*item, len(m.m))
maps.Copy(dst, m.m)
m.l.Unlock()
return dst
}
func (m *TtlMap[T]) Close() {
m.stop <- true
}