-
Notifications
You must be signed in to change notification settings - Fork 2
/
mcache.go
292 lines (253 loc) · 6.37 KB
/
mcache.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package incache
import (
"sync"
"time"
)
type MCache[K comparable, V any] struct {
mu sync.RWMutex
size uint
m map[K]valueWithTimeout[V] // where the key-value pairs are stored
stopCh chan struct{} // Channel to signal timeout goroutine to stop
timeInterval time.Duration // Time interval to sleep the goroutine that checks for expired keys
}
type valueWithTimeout[V any] struct {
value V
expireAt *time.Time
}
// New creates a new cache instance with optional configuration provided by the specified options.
// The database starts a background goroutine to periodically check for expired keys based on the configured time interval.
func NewManual[K comparable, V any](size uint, timeInterval time.Duration) *MCache[K, V] {
c := &MCache[K, V]{
m: make(map[K]valueWithTimeout[V]),
stopCh: make(chan struct{}),
size: size,
timeInterval: timeInterval,
}
if c.timeInterval > 0 {
go c.expireKeys()
}
return c
}
// Set adds or updates a key-value pair in the database without setting an expiration time.
// If the key already exists, its value will be overwritten with the new value.
// This function is safe for concurrent use.
func (c *MCache[K, V]) Set(k K, v V) {
if c.size == 0 {
return
}
c.mu.Lock()
defer c.mu.Unlock()
if len(c.m) == int(c.size) {
c.evict(1)
}
c.m[k] = valueWithTimeout[V]{
value: v,
expireAt: nil,
}
}
// NotFoundSet adds a key-value pair to the database if the key does not already exist and returns true. Otherwise, it does nothing and returns false.
func (c *MCache[K, V]) NotFoundSet(k K, v V) bool {
if c.size == 0 {
return false
}
c.mu.Lock()
defer c.mu.Unlock()
_, ok := c.m[k]
if !ok {
if len(c.m) == int(c.size) {
c.evict(1)
}
c.m[k] = valueWithTimeout[V]{
value: v,
expireAt: nil,
}
}
return !ok
}
// SetWithTimeout adds or updates a key-value pair in the database with an expiration time.
// If the timeout duration is zero or negative, the key-value pair will not have an expiration time.
// This function is safe for concurrent use.
func (c *MCache[K, V]) SetWithTimeout(k K, v V, timeout time.Duration) {
if c.size == 0 {
return
}
if timeout > 0 {
c.mu.Lock()
defer c.mu.Unlock()
if len(c.m) == int(c.size) {
c.evict(1)
}
now := time.Now().Add(timeout)
c.m[k] = valueWithTimeout[V]{
value: v,
expireAt: &now,
}
} else {
c.Set(k, v)
}
}
// NotFoundSetWithTimeout adds a key-value pair to the database with an expiration time if the key does not already exist and returns true. Otherwise, it does nothing and returns false.
// If the timeout is zero or negative, the key-value pair will not have an expiration time.
// If expiry is disabled, it behaves like NotFoundSet.
func (c *MCache[K, V]) NotFoundSetWithTimeout(k K, v V, timeout time.Duration) bool {
if c.size == 0 {
return false
}
c.mu.Lock()
defer c.mu.Unlock()
var ok bool
if timeout > 0 {
now := time.Now().Add(timeout)
_, ok = c.m[k]
if !ok {
if len(c.m) == int(c.size) {
c.evict(1)
}
c.m[k] = valueWithTimeout[V]{
value: v,
expireAt: &now,
}
}
} else {
_, ok = c.m[k]
if !ok {
if len(c.m) == int(c.size) {
c.evict(1)
}
c.m[k] = valueWithTimeout[V]{
value: v,
expireAt: nil,
}
}
}
return !ok
}
func (c *MCache[K, V]) Get(k K) (v V, b bool) {
c.mu.Lock()
defer c.mu.Unlock()
val, ok := c.m[k]
if !ok {
return
}
if val.expireAt != nil && val.expireAt.Before(time.Now()) {
delete(c.m, k)
return
}
return val.value, ok
}
func (c *MCache[K, V]) GetAll() map[K]V {
c.mu.RLock()
defer c.mu.RUnlock()
m := make(map[K]V)
for k, v := range c.m {
if v.expireAt == nil || !v.expireAt.Before(time.Now()) {
m[k] = v.value
}
}
return m
}
func (c *MCache[K, V]) Delete(k K) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.m, k)
}
// TransferTo transfers all key-value pairs from the source cache to the provided destination cache.
//
// The source cache and the destination cache are locked during the entire operation.
// The function is safe to call concurrently with other operations on any of the source cache or destination cache.
func (src *MCache[K, V]) TransferTo(dst *MCache[K, V]) {
all := src.GetAll()
src.mu.Lock()
src.m = make(map[K]valueWithTimeout[V])
src.mu.Unlock()
for k, v := range all {
dst.Set(k, v)
}
}
// CopyTo copies all key-value pairs from the source cache to the provided destination cache.
//
// The source cache are the destination cache are locked during the entire operation.
// The function is safe to call concurrently with other operations on any of the source cache or Destination cache.
func (src *MCache[K, V]) CopyTo(dst *MCache[K, V]) {
all := src.GetAll()
for k, v := range all {
dst.Set(k, v)
}
}
func (c *MCache[K, V]) Keys() []K {
c.mu.RLock()
defer c.mu.RUnlock()
keys := make([]K, 0, c.Count())
for k, v := range c.m {
if v.expireAt == nil || !v.expireAt.Before(time.Now()) {
keys = append(keys, k)
}
}
return keys
}
// expireKeys is a background goroutine that periodically checks for expired keys and removes them from the database.
// It runs until the Close method is callec.
// This function is not intended to be called directly by users.
func (c *MCache[K, V]) expireKeys() {
ticker := time.NewTicker(c.timeInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
for k, v := range c.m {
if v.expireAt != nil && v.expireAt.Before(time.Now()) {
c.mu.Lock()
delete(c.m, k)
c.mu.Unlock()
}
}
case <-c.stopCh:
return
}
}
}
func (c *MCache[K, V]) Purge() {
if c.timeInterval > 0 {
c.stopCh <- struct{}{} // Signal the expiration goroutine to stop
close(c.stopCh)
}
c.m = nil
}
// Count returns the number of key-value pairs in the database.
func (c *MCache[K, V]) Count() int {
c.mu.RLock()
defer c.mu.RUnlock()
var count int
for _, v := range c.m {
if v.expireAt == nil || !v.expireAt.Before(time.Now()) {
count++
}
}
return count
}
func (c *MCache[K, V]) Len() int {
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.m)
}
func (c *MCache[K, V]) evict(i int) {
var counter int
for k, v := range c.m {
if counter == i {
break
}
if v.expireAt != nil && !v.expireAt.After(time.Now()) {
delete(c.m, k)
counter++
}
}
if i > len(c.m) {
i = len(c.m)
}
for ; counter < i; counter++ {
for k := range c.m {
delete(c.m, k)
break
}
}
}