-
Notifications
You must be signed in to change notification settings - Fork 113
/
lru.go
96 lines (85 loc) · 1.51 KB
/
lru.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
package database
import (
lru "github.com/hashicorp/golang-lru"
"github.com/iost-official/go-iost/core/version"
)
// LRU lru cache
type LRU struct {
cache *lru.Cache
db database
}
// NewLRU make a new lru
func NewLRU(length int, db database) *LRU {
if length <= 0 {
return &LRU{
cache: nil,
db: db,
}
}
c, err := lru.New(length)
if err != nil {
panic(err)
}
return &LRU{
cache: c,
db: db,
}
}
// Rules get rules of db
func (m *LRU) Rules() *version.Rules {
return m.db.Rules()
}
// Get get from cache
func (m *LRU) Get(key string) (value string) {
if m.cache == nil {
return m.db.Get(key)
}
v, ok := m.cache.Get(key)
if !ok {
value = m.db.Get(key)
if value != "" && value != "n" {
m.cache.Add(key, value)
}
return value
}
return v.(string)
}
// Put put kv to cache
func (m *LRU) Put(key, value string) {
if m.cache != nil && m.cache.Contains(key) {
m.cache.Add(key, value)
}
m.db.Put(key, value)
}
// Has if key exist
func (m *LRU) Has(key string) bool {
if m.cache == nil {
return m.db.Has(key)
}
ok := m.cache.Contains(key)
if !ok {
ok = m.db.Has(key)
if ok {
v := m.db.Get(key)
m.cache.Add(key, v)
}
}
return ok
}
// Keys list keys under prefix, do nothing
//func (m *LRU) Keys(prefix string) []string {
// return m.db.Keys(prefix)
//}
// Del delete key from cache
func (m *LRU) Del(key string) {
if m.cache != nil {
m.cache.Remove(key)
}
m.db.Del(key)
}
// Purge delete all keys
func (m *LRU) Purge() {
if m.cache != nil {
m.cache.Purge()
}
}