2015-01-01 14:49:30 -05:00
|
|
|
package fzf
|
|
|
|
|
|
|
|
import "sync"
|
|
|
|
|
2015-04-17 09:23:52 -04:00
|
|
|
// queryCache associates strings to lists of items
|
|
|
|
type queryCache map[string][]*Item
|
2015-01-11 13:01:24 -05:00
|
|
|
|
|
|
|
// ChunkCache associates Chunk and query string to lists of items
|
2015-01-01 14:49:30 -05:00
|
|
|
type ChunkCache struct {
|
|
|
|
mutex sync.Mutex
|
2015-04-17 09:23:52 -04:00
|
|
|
cache map[*Chunk]*queryCache
|
2015-01-01 14:49:30 -05:00
|
|
|
}
|
|
|
|
|
2015-01-11 13:01:24 -05:00
|
|
|
// NewChunkCache returns a new ChunkCache
|
2015-01-01 14:49:30 -05:00
|
|
|
func NewChunkCache() ChunkCache {
|
2015-04-17 09:23:52 -04:00
|
|
|
return ChunkCache{sync.Mutex{}, make(map[*Chunk]*queryCache)}
|
2015-01-01 14:49:30 -05:00
|
|
|
}
|
|
|
|
|
2015-01-11 13:01:24 -05:00
|
|
|
// Add adds the list to the cache
|
2015-01-01 14:49:30 -05:00
|
|
|
func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Item) {
|
2015-04-17 09:23:52 -04:00
|
|
|
if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {
|
2015-01-01 14:49:30 -05:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
cc.mutex.Lock()
|
|
|
|
defer cc.mutex.Unlock()
|
|
|
|
|
|
|
|
qc, ok := cc.cache[chunk]
|
|
|
|
if !ok {
|
2015-04-17 09:23:52 -04:00
|
|
|
cc.cache[chunk] = &queryCache{}
|
2015-01-01 14:49:30 -05:00
|
|
|
qc = cc.cache[chunk]
|
|
|
|
}
|
|
|
|
(*qc)[key] = list
|
|
|
|
}
|
|
|
|
|
2015-01-11 13:01:24 -05:00
|
|
|
// Find is called to lookup ChunkCache
|
2015-01-01 14:49:30 -05:00
|
|
|
func (cc *ChunkCache) Find(chunk *Chunk, key string) ([]*Item, bool) {
|
|
|
|
if len(key) == 0 || !chunk.IsFull() {
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
|
|
|
cc.mutex.Lock()
|
|
|
|
defer cc.mutex.Unlock()
|
|
|
|
|
|
|
|
qc, ok := cc.cache[chunk]
|
|
|
|
if ok {
|
|
|
|
list, ok := (*qc)[key]
|
|
|
|
if ok {
|
|
|
|
return list, true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, false
|
|
|
|
}
|