cache.go
This file
Path
src/cache.go
87 lines · 1.7 KiB · Go
Last changed by
Refactor the code so that fzf can be used as a library (#3769)Junegunn Choibefore adoptione8405f4
History of this fileTake it
The walk stopped after 200 commits: lines older than d75bb5c point at it.
Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c
lines 1–14why, one step back1package 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 ChunkCacheRefactor the code so that fzf can be used as a library (#3769)Junegunn Choibefore adoptione8405f4
lines 15–22why, one step back15func 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()Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c
lines 23–87why, one step back23}2425// Add adds the list to the cache26func (cc *ChunkCache) Add(chunk *Chunk, key string, list []Result) {27 if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {28 return29 }3031 cc.mutex.Lock()32 defer cc.mutex.Unlock()3334 qc, ok := cc.cache[chunk]35 if !ok {36 cc.cache[chunk] = &queryCache{}37 qc = cc.cache[chunk]38 }39 (*qc)[key] = list40}4142// Lookup is called to lookup ChunkCache43func (cc *ChunkCache) Lookup(chunk *Chunk, key string) []Result {44 if len(key) == 0 || !chunk.IsFull() {45 return nil46 }4748 cc.mutex.Lock()49 defer cc.mutex.Unlock()5051 qc, ok := cc.cache[chunk]52 if ok {53 list, ok := (*qc)[key]54 if ok {55 return list56 }57 }58 return nil59}6061func (cc *ChunkCache) Search(chunk *Chunk, key string) []Result {62 if len(key) == 0 || !chunk.IsFull() {63 return nil64 }6566 cc.mutex.Lock()67 defer cc.mutex.Unlock()6869 qc, ok := cc.cache[chunk]70 if !ok {71 return nil72 }7374 for idx := 1; idx < len(key); idx++ {75 // [---------| ] | [ |---------]76 // [--------| ] | [ |--------]77 // [-------| ] | [ |-------]78 prefix := key[:len(key)-idx]79 suffix := key[idx:]80 for _, substr := range [2]string{prefix, suffix} {81 if cached, found := (*qc)[substr]; found {82 return cached83 }84 }85 }86 return nil87}