-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcache.go
60 lines (48 loc) · 1.17 KB
/
cache.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
package main
import (
"hash/fnv"
"strconv"
"sync"
)
type cacheBank struct {
sync.RWMutex
data map[uint64][]ParseMatch
}
var cacheBanks []cacheBank
func InitCache(bankCount uint) {
banks := make([]cacheBank, bankCount)
for i := range banks {
banks[i].data = make(map[uint64][]ParseMatch)
}
cacheBanks = banks
}
func FinalizeCache() {
cacheBanks = nil
}
func getCacheHash(text, nonterminal string, hypothesesLimit uint) uint64 {
hash := fnv.New64()
hash.Write([]byte(text))
hash.Write([]byte(nonterminal))
hash.Write([]byte(strconv.Itoa(int(hypothesesLimit))))
return hash.Sum64()
}
func FindInCache(text, nonterminal string,
hypothesesLimit uint) ([]ParseMatch, bool) {
hash := getCacheHash(text, nonterminal, hypothesesLimit)
bank := &cacheBanks[hash%uint64(len(cacheBanks))]
bank.RLock()
matches, ok := bank.data[hash]
bank.RUnlock()
return matches, ok
}
func AddToCache(text, nonterminal string,
hypothesesLimit uint, matches []ParseMatch) {
hash := getCacheHash(text, nonterminal, hypothesesLimit)
bank := &cacheBanks[hash%uint64(len(cacheBanks))]
bank.Lock()
bank.data[hash] = matches
bank.Unlock()
}
func ClearCache() {
InitCache(uint(len(cacheBanks)))
}