-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
90 lines (79 loc) · 1.42 KB
/
cache.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
package epcache
import (
"sync"
"sync/atomic"
"github.com/EndlessParadox1/epcache/lru"
)
type cache struct {
mu sync.RWMutex
nbytes int64
lru *lru.Cache
nhit, nget int64
nevict int64
}
type CacheStats struct {
Bytes int64
Items int64
Hits int64
Gets int64
Evicts int64
}
func (c *cache) stats() CacheStats {
c.mu.RLock()
defer c.mu.RUnlock()
return CacheStats{
Bytes: c.nbytes,
Items: c.items(),
Hits: c.nhit,
Gets: c.nget,
Evicts: c.nevict,
}
}
func (c *cache) items() int64 {
if c.lru == nil {
return 0
}
return int64(c.lru.Len())
}
func (c *cache) add(key string, value ByteView) {
c.mu.Lock()
defer c.mu.Unlock()
if c.lru == nil {
c.lru = lru.New(func(key string, value any) {
c.nbytes -= int64(len(key) + value.(ByteView).Len())
c.nevict++
})
} // lazy init
c.lru.Add(key, value)
c.nbytes += int64(len(key) + value.Len())
}
func (c *cache) get(key string) (value ByteView, ok bool) {
atomic.AddInt64(&c.nget, 1)
c.mu.RLock()
if c.lru == nil {
c.mu.RUnlock()
return
}
val, hit := c.lru.Get(key)
c.mu.RUnlock()
if !hit {
return
}
atomic.AddInt64(&c.nhit, 1)
return val.(ByteView), true
}
func (c *cache) remove(key string) {
c.mu.Lock()
c.lru.Remove(key)
c.mu.Unlock()
}
func (c *cache) removeOldest() {
c.mu.Lock()
c.lru.RemoveOldest()
c.mu.Unlock()
}
func (c *cache) bytes() int64 {
c.mu.RLock()
defer c.mu.RUnlock()
return c.nbytes
}