-
Notifications
You must be signed in to change notification settings - Fork 1
/
backend.go
78 lines (64 loc) · 1.72 KB
/
backend.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
package sc
import (
"github.com/motoki317/sc/lru"
"github.com/motoki317/sc/tq"
)
// backend represents a cache backend.
// Backend implementations does NOT need to be goroutine-safe.
type backend[K comparable, V any] interface {
// Get the value for key.
Get(key K) (v V, ok bool)
// Set the value for key.
Set(key K, v V)
// Delete the value for key.
Delete(key K)
// DeleteIf deletes all values that match the predicate.
DeleteIf(predicate func(key K, value V) bool)
// Purge all values.
Purge()
// Size returns the number of items currently stored.
Size() int
// Capacity returns the maximum number of items that can be stored.
Capacity() int
}
type mapBackend[K comparable, V any] map[K]V
func newMapBackend[K comparable, V any](cap int) backend[K, V] {
return mapBackend[K, V](make(map[K]V, cap))
}
func (m mapBackend[K, V]) Get(key K) (v V, ok bool) {
v, ok = m[key]
return
}
func (m mapBackend[K, V]) Set(key K, v V) {
m[key] = v
}
func (m mapBackend[K, V]) Delete(key K) {
delete(m, key)
}
func (m mapBackend[K, V]) DeleteIf(predicate func(key K, value V) bool) {
for k, v := range m {
if predicate(k, v) {
delete(m, k)
}
}
}
func (m mapBackend[K, V]) Purge() {
// This form is optimized by the Go-compiler; it calls faster internal mapclear() instead of looping, and avoids
// allocating new memory.
// https://go.dev/doc/go1.11#performance
for key := range m {
delete(m, key)
}
}
func (m mapBackend[K, V]) Size() int {
return len(m)
}
func (m mapBackend[K, V]) Capacity() int {
return -1
}
func newLRUBackend[K comparable, V any](cap int) backend[K, V] {
return lru.New[K, V](lru.WithCapacity(cap))
}
func new2QBackend[K comparable, V any](cap int) backend[K, V] {
return tq.New[K, V](cap)
}