forked from qjfoidnh/BaiduPCS-Go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cacheunit.go
81 lines (71 loc) · 1.86 KB
/
cacheunit.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
package cachemap
import (
"github.com/qjfoidnh/BaiduPCS-Go/baidupcs/expires"
"sync"
)
type (
CacheUnit interface {
Delete(key interface{})
Load(key interface{}) (value expires.DataExpires, ok bool)
LoadOrStore(key interface{}, value expires.DataExpires) (actual expires.DataExpires, loaded bool)
Range(f func(key interface{}, value expires.DataExpires) bool)
Store(key interface{}, value expires.DataExpires)
LockKey(key interface{})
UnlockKey(key interface{})
}
cacheUnit struct {
unit sync.Map
keyMap sync.Map
}
)
func (cu *cacheUnit) Delete(key interface{}) {
cu.unit.Delete(key)
cu.keyMap.Delete(key)
}
func (cu *cacheUnit) Load(key interface{}) (value expires.DataExpires, ok bool) {
val, ok := cu.unit.Load(key)
if !ok {
return nil, ok
}
exp := val.(expires.DataExpires)
if exp.IsExpires() {
cu.unit.Delete(key)
return nil, false
}
return exp, ok
}
func (cu *cacheUnit) Range(f func(key interface{}, value expires.DataExpires) bool) {
cu.unit.Range(func(k, val interface{}) bool {
exp := val.(expires.DataExpires)
if exp.IsExpires() {
cu.unit.Delete(k)
return true
}
return f(k, val.(expires.DataExpires))
})
}
func (cu *cacheUnit) LoadOrStore(key interface{}, value expires.DataExpires) (actual expires.DataExpires, loaded bool) {
ac, loaded := cu.unit.LoadOrStore(key, value)
exp := ac.(expires.DataExpires)
if exp.IsExpires() {
cu.unit.Delete(key)
return nil, false
}
return exp, loaded
}
func (cu *cacheUnit) Store(key interface{}, value expires.DataExpires) {
if value.IsExpires() {
return
}
cu.unit.Store(key, value)
}
func (cu *cacheUnit) LockKey(key interface{}) {
muItf, _ := cu.keyMap.LoadOrStore(key, &sync.Mutex{})
mu := muItf.(*sync.Mutex)
mu.Lock()
}
func (cu *cacheUnit) UnlockKey(key interface{}) {
muItf, _ := cu.keyMap.LoadOrStore(key, &sync.Mutex{})
mu := muItf.(*sync.Mutex)
mu.Unlock()
}