-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
84 lines (76 loc) · 1.95 KB
/
Copy pathcache.go
File metadata and controls
84 lines (76 loc) · 1.95 KB
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
package gocache
import "sync"
type Cacher[K comparable, V any] interface {
Add(key K, value V) (K, bool) // 添加值, 如果返回 k, true 说明有删除值,并返回删除的key
Remove(key K) // 移除k
Len() int // 长度
OrderPrint() // 顺序打印
Get(key K) (V, bool) // 获取值
LastKey() K // 获取最先要删除的key
Resize(int) // 重新定义大小
}
type Algorithm int
const (
LRU Algorithm = iota
LFU
ALFU
SIMPLE
)
// size: max length of cache
// claddingSize: only use for lfu or alfu, The number of visits and step size are merged into one layer in order to reduce the level, default 1
func NewCache[K comparable, V any](size int, t Algorithm, claddingSize ...int) Cacher[K, V] {
// 内存足够的话, 可以设置很大, 所有计算都是O(1)
if size <= 0 {
size = 2 << 10
}
switch t {
case SIMPLE:
return &SimpleCache[K, V]{
cache: make(map[K]V),
order: make([]K, size),
mu: sync.RWMutex{},
size: size,
}
case LRU:
return &Lru[K, V]{
lru: make(map[K]*element[K, V]),
size: size,
lock: sync.RWMutex{},
root: &element[K, V]{},
last: &element[K, V]{},
}
case LFU:
cs := 1
if len(claddingSize) > 0 && claddingSize[0] > 1 {
cs = claddingSize[0]
}
return &Lfu[K, V]{
layer: make(map[int]*Lru[K, V]),
// 这里是根据key来查询在那一层
cache: make(map[K]int),
mu: sync.RWMutex{},
size: size,
claddingSize: cs,
}
case ALFU:
cs := 1
if len(claddingSize) > 0 && claddingSize[0] > 1 {
cs = claddingSize[0]
}
alfu := &Alfu[K, V]{
&Lfu[K, V]{
layer: make(map[int]*Lru[K, V]),
// 这里是根据key来查询在那一层
cache: make(map[K]int),
mu: sync.RWMutex{},
size: size,
claddingSize: cs,
},
}
go alfu.auto()
return alfu
default:
return nil
}
}
const DEFAULTCOUNT = 2 << 10