Skip to content
Myr

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 file

Take it

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}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}