forked from viney-shih/go-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
key.go
74 lines (59 loc) · 1.45 KB
/
key.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
package cache
import (
"strings"
"sync"
)
const (
packageKey = "ca"
topicKey = "tp"
// delimiters
cacheDelim = ":"
topicDelim = "#"
)
var (
regPkgKey = packageKey
// regKeyOnce limits key registeration happening once
regKeyOnce = sync.Once{}
)
func registerKey(pkgKey string) {
regKeyOnce.Do(func() {
regPkgKey = pkgKey
})
}
func customKey(delimiter string, components ...string) string {
return strings.Join(components, delimiter)
}
func getTopic(topic string) string {
return customKey(topicDelim, regPkgKey, topicKey, topic)
}
func getCacheKey(pfx, key string) string {
if regPkgKey == "" {
return customKey(cacheDelim, pfx, key)
}
return customKey(cacheDelim, regPkgKey, pfx, key)
}
func getCacheKeys(pfx string, keys []string) []string {
cacheKeys := make([]string, len(keys))
for i, k := range keys {
cacheKeys[i] = getCacheKey(pfx, k)
}
return cacheKeys
}
func getPrefixAndKey(cacheKey string) (string, string) {
// 1) cacheKey = regPkgKey + prefix + key (normal case)
// 2) cacheKey = prefix + key (if customized package key is empty)
idx := strings.Index(cacheKey, cacheDelim)
if idx < 0 {
return cacheKey, "" // should not happen
}
if regPkgKey == "" {
return cacheKey[:idx], cacheKey[idx+len(cacheDelim):]
}
// mixedKey = prefix + key
mixedKey := cacheKey[idx+len(cacheDelim):]
idx = strings.Index(mixedKey, cacheDelim)
if idx < 0 {
return mixedKey, ""
}
return mixedKey[:idx], mixedKey[idx+len(cacheDelim):]
}