mirror of
https://github.com/Llewellynvdm/fzf.git
synced 2024-11-13 17:06:28 +00:00
37dc273148
- Make structs smaller - Introduce Result struct and use it to represent matched items instead of reusing Item struct for that purpose - Avoid unnecessary memory allocation - Avoid growing slice from the initial capacity - Code cleanup
54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
package fzf
|
|
|
|
import "sync"
|
|
|
|
// queryCache associates strings to lists of items
|
|
type queryCache map[string][]*Result
|
|
|
|
// ChunkCache associates Chunk and query string to lists of items
|
|
type ChunkCache struct {
|
|
mutex sync.Mutex
|
|
cache map[*Chunk]*queryCache
|
|
}
|
|
|
|
// NewChunkCache returns a new ChunkCache
|
|
func NewChunkCache() ChunkCache {
|
|
return ChunkCache{sync.Mutex{}, make(map[*Chunk]*queryCache)}
|
|
}
|
|
|
|
// Add adds the list to the cache
|
|
func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Result) {
|
|
if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {
|
|
return
|
|
}
|
|
|
|
cc.mutex.Lock()
|
|
defer cc.mutex.Unlock()
|
|
|
|
qc, ok := cc.cache[chunk]
|
|
if !ok {
|
|
cc.cache[chunk] = &queryCache{}
|
|
qc = cc.cache[chunk]
|
|
}
|
|
(*qc)[key] = list
|
|
}
|
|
|
|
// Find is called to lookup ChunkCache
|
|
func (cc *ChunkCache) Find(chunk *Chunk, key string) ([]*Result, 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
|
|
}
|