-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnapcache.go
More file actions
112 lines (90 loc) · 2.02 KB
/
Copy pathsnapcache.go
File metadata and controls
112 lines (90 loc) · 2.02 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
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
package snapcache
import (
"container/list"
"sync"
)
type SnapCache[K comparable, V any] struct {
mu sync.Mutex
main *list.List
sub *list.List
maxSize int
items map[K]*entry[K, V]
max int
snap uint64
}
type entry[K comparable, V any] struct {
key K
value V
element *list.Element
}
func New[K comparable, V any](maxSize int) *SnapCache[K,V] {
//
snap := uint64(1)
return &SnapCache[K, V]{
main: list.New(),
sub: list.New(),
maxSize: maxSize,
snap: snap,
items: make(map[K]*entry[K, V]),
}
}
func (sc *SnapCache[K, V]) Full() bool {
return sc.main.Len() >= sc.maxSize
}
func (sc *SnapCache[K, V]) Set(key K, value V) {
sc.mu.Lock()
defer sc.mu.Unlock()
e, ok := sc.items[key]
if ok {
e.value = value
return
}
e = &entry[K, V]{
key: key,
value: value,
element: sc.main.PushBack(&entry[K, V]{key: key, value: value}),
}
sc.items[key] = e
}
func (sc *SnapCache[K,V]) Evict() int {
sc.mu.Lock()
defer sc.mu.Unlock()
evictCounter := 0
evictSize := int(sc.snap)
for sc.main.Len() > 0 && evictSize > 0 {
front := sc.main.Front()
if front == nil {
break
}
e, ok := front.Value.(*entry[K, V])
if !ok {
panic("incorrect type in list")
}
sc.main.Remove(front)
delete(sc.items, e.key)
evictCounter++
evictSize--
}
return evictCounter
}
func (sc *SnapCache[K, V]) Get(key K) (V, bool) {
sc.mu.Lock()
defer sc.mu.Unlock()
// 메인 큐에서 항목을 조회합니다.
e, ok := sc.items[key]
if ok && e.element != nil {
return e.value, true
}
var value V
// 키가 존재하지 않는 경우 기본 값과 false를 반환합니다.
return value, false
}
// Purge 메서드 추가: 캐시를 초기화
func (sc *SnapCache[K, V]) Purge() {
sc.mu.Lock()
defer sc.mu.Unlock()
// 캐시 항목 모두 제거
sc.main.Init() // 메인 리스트 초기화
sc.items = make(map[K]*entry[K, V]) // 맵 초기화
sc.max = 0 // 최대 플래그 초기화
}