1package fzf23import "sync"45// queryCache associates strings to lists of items6type queryCache map[string][]Result78// ChunkCache associates Chunk and query string to lists of items9type ChunkCache struct {10 mutex sync.Mutex11 cache map[*Chunk]*queryCache12}1314// NewChunkCache returns a new ChunkCache15func NewChunkCache() *ChunkCache {16 return &ChunkCache{sync.Mutex{}, make(map[*Chunk]*queryCache)}17}1819func (cc *ChunkCache) Clear() {20 cc.mutex.Lock()21 cc.cache = make(map[*Chunk]*queryCache)22 cc.mutex.Unlock()23}2425func (cc *ChunkCache) retire(chunk ...*Chunk) {26 cc.mutex.Lock()27 for _, c := range chunk {28 delete(cc.cache, c)29 }30 cc.mutex.Unlock()31}3233// Add adds the list to the cache34func (cc *ChunkCache) Add(chunk *Chunk, key string, list []Result) {35 if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {36 return37 }3839 cc.mutex.Lock()40 defer cc.mutex.Unlock()4142 qc, ok := cc.cache[chunk]43 if !ok {44 cc.cache[chunk] = &queryCache{}45 qc = cc.cache[chunk]46 }47 (*qc)[key] = list48}4950// Lookup is called to lookup ChunkCache51func (cc *ChunkCache) Lookup(chunk *Chunk, key string) []Result {52 if len(key) == 0 || !chunk.IsFull() {53 return nil54 }5556 cc.mutex.Lock()57 defer cc.mutex.Unlock()5859 qc, ok := cc.cache[chunk]60 if ok {61 list, ok := (*qc)[key]62 if ok {63 return list64 }65 }66 return nil67}6869func (cc *ChunkCache) Search(chunk *Chunk, key string) []Result {70 if len(key) == 0 || !chunk.IsFull() {71 return nil72 }7374 cc.mutex.Lock()75 defer cc.mutex.Unlock()7677 qc, ok := cc.cache[chunk]78 if !ok {79 return nil80 }8182 for idx := 1; idx < len(key); idx++ {83 // [---------| ] | [ |---------]84 // [--------| ] | [ |--------]85 // [-------| ] | [ |-------]86 prefix := key[:len(key)-idx]87 suffix := key[idx:]88 for _, substr := range [2]string{prefix, suffix} {89 if cached, found := (*qc)[substr]; found {90 return cached91 }92 }93 }94 return nil95}