Debian Codegraph @

src/cache.go

raw
1 package fzf
2
3 import "sync"
4
5 // ChunkBitmap is a bitmap with one bit per item in a chunk.
6 type ChunkBitmap [chunkBitWords]uint64
7
8 // queryCache associates query strings to bitmaps of matching items
9 type queryCache map[string]ChunkBitmap
10
11 // ChunkCache associates Chunk and query string to bitmaps
12 type ChunkCache struct {
13 mutex sync.Mutex
14 cache map[*Chunk]*queryCache
15 }
16
17 // NewChunkCache returns a new ChunkCache
18 func NewChunkCache() *ChunkCache {
19 return &ChunkCache{sync.Mutex{}, make(map[*Chunk]*queryCache)}
20 }
21
22 func (cc *ChunkCache) Clear() {
23 cc.mutex.Lock()
24 cc.cache = make(map[*Chunk]*queryCache)
25 cc.mutex.Unlock()
26 }
27
28 func (cc *ChunkCache) retire(chunk ...*Chunk) {
29 cc.mutex.Lock()
30 for _, c := range chunk {
31 delete(cc.cache, c)
32 }
33 cc.mutex.Unlock()
34 }
35
36 // Add stores the bitmap for the given chunk and key
37 func (cc *ChunkCache) Add(chunk *Chunk, key string, bitmap ChunkBitmap, matchCount int) {
38 if len(key) == 0 || !chunk.IsFull() || matchCount > queryCacheMax {
39 return
40 }
41
42 cc.mutex.Lock()
43 defer cc.mutex.Unlock()
44
45 qc, ok := cc.cache[chunk]
46 if !ok {
47 cc.cache[chunk] = &queryCache{}
48 qc = cc.cache[chunk]
49 }
50 (*qc)[key] = bitmap
51 }
52
53 // Lookup returns the bitmap for the exact key
54 func (cc *ChunkCache) Lookup(chunk *Chunk, key string) *ChunkBitmap {
55 if len(key) == 0 || !chunk.IsFull() {
56 return nil
57 }
58
59 cc.mutex.Lock()
60 defer cc.mutex.Unlock()
61
62 qc, ok := cc.cache[chunk]
63 if ok {
64 if bm, ok := (*qc)[key]; ok {
65 return &bm
66 }
67 }
68 return nil
69 }
70
71 // Search finds the bitmap for the longest prefix or suffix of the key
72 func (cc *ChunkCache) Search(chunk *Chunk, key string) *ChunkBitmap {
73 if len(key) == 0 || !chunk.IsFull() {
74 return nil
75 }
76
77 cc.mutex.Lock()
78 defer cc.mutex.Unlock()
79
80 qc, ok := cc.cache[chunk]
81 if !ok {
82 return nil
83 }
84
85 for idx := 1; idx < len(key); idx++ {
86 // [---------| ] | [ |---------]
87 // [--------| ] | [ |--------]
88 // [-------| ] | [ |-------]
89 prefix := key[:len(key)-idx]
90 suffix := key[idx:]
91 for _, substr := range [2]string{prefix, suffix} {
92 if bm, found := (*qc)[substr]; found {
93 return &bm
94 }
95 }
96 }
97 return nil
98 }