Skip to content
Myr

cache.go

This file

Path

src/cache.go

98 lines · 2.1 KiB · Go

Last changed by

Not known.

History of this file

Take it

1package fzf23import "sync"45// ChunkBitmap is a bitmap with one bit per item in a chunk.6type ChunkBitmap [chunkBitWords]uint6478// queryCache associates query strings to bitmaps of matching items9type queryCache map[string]ChunkBitmap1011// ChunkCache associates Chunk and query string to bitmaps12type ChunkCache struct {13	mutex sync.Mutex14	cache map[*Chunk]*queryCache15}1617// NewChunkCache returns a new ChunkCache18func NewChunkCache() *ChunkCache {19	return &ChunkCache{sync.Mutex{}, make(map[*Chunk]*queryCache)}20}2122func (cc *ChunkCache) Clear() {23	cc.mutex.Lock()24	cc.cache = make(map[*Chunk]*queryCache)25	cc.mutex.Unlock()26}2728func (cc *ChunkCache) retire(chunk ...*Chunk) {29	cc.mutex.Lock()30	for _, c := range chunk {31		delete(cc.cache, c)32	}33	cc.mutex.Unlock()34}3536// Add stores the bitmap for the given chunk and key37func (cc *ChunkCache) Add(chunk *Chunk, key string, bitmap ChunkBitmap, matchCount int) {38	if len(key) == 0 || !chunk.IsFull() || matchCount > queryCacheMax {39		return40	}4142	cc.mutex.Lock()43	defer cc.mutex.Unlock()4445	qc, ok := cc.cache[chunk]46	if !ok {47		cc.cache[chunk] = &queryCache{}48		qc = cc.cache[chunk]49	}50	(*qc)[key] = bitmap51}5253// Lookup returns the bitmap for the exact key54func (cc *ChunkCache) Lookup(chunk *Chunk, key string) *ChunkBitmap {55	if len(key) == 0 || !chunk.IsFull() {56		return nil57	}5859	cc.mutex.Lock()60	defer cc.mutex.Unlock()6162	qc, ok := cc.cache[chunk]63	if ok {64		if bm, ok := (*qc)[key]; ok {65			return &bm66		}67	}68	return nil69}7071// Search finds the bitmap for the longest prefix or suffix of the key72func (cc *ChunkCache) Search(chunk *Chunk, key string) *ChunkBitmap {73	if len(key) == 0 || !chunk.IsFull() {74		return nil75	}7677	cc.mutex.Lock()78	defer cc.mutex.Unlock()7980	qc, ok := cc.cache[chunk]81	if !ok {82		return nil83	}8485	for idx := 1; idx < len(key); idx++ {86		// [---------| ] | [ |---------]87		// [--------|  ] | [  |--------]88		// [-------|   ] | [   |-------]89		prefix := key[:len(key)-idx]90		suffix := key[idx:]91		for _, substr := range [2]string{prefix, suffix} {92			if bm, found := (*qc)[substr]; found {93				return &bm94			}95		}96	}97	return nil98}