fork of https://github.com/sourcegraph/zoekt
0

Configure Feed

Select the types of activity you want to include in your feed.

at main 1.4 kB View raw
1package index 2 3import ( 4 "os" 5 "strconv" 6 "sync" 7) 8 9// docMatchTreeCache is a cache for docMatchTrees with random eviction. 10type docMatchTreeCache struct { 11 maxEntries int 12 cache map[docMatchTreeCacheKey]*docMatchTree 13 mu sync.RWMutex 14} 15 16type docMatchTreeCacheKey struct { 17 field string 18 value string 19} 20 21// newDocMatchTreeCache creates a new docMatchTreeCache. 22// If cacheSize is 0, the value from the ZOEKT_DOCMATCHTREE_CACHE environment 23// variable will be used if it is present. 24func newDocMatchTreeCache(cacheSize int) *docMatchTreeCache { 25 if v := os.Getenv("ZOEKT_DOCMATCHTREE_CACHE"); cacheSize == 0 && v != "" { 26 var err error 27 cacheSize, err = strconv.Atoi(v) 28 if err != nil { 29 cacheSize = 0 30 } 31 } 32 return &docMatchTreeCache{ 33 maxEntries: cacheSize, 34 cache: make(map[docMatchTreeCacheKey]*docMatchTree), 35 } 36} 37 38func (c *docMatchTreeCache) Get(field, value string) (*docMatchTree, bool) { 39 c.mu.RLock() 40 defer c.mu.RUnlock() 41 k := docMatchTreeCacheKey{field, value} 42 mt, ok := c.cache[k] 43 return mt, ok 44} 45 46func (c *docMatchTreeCache) Add(field, value string, mt *docMatchTree) { 47 if c.maxEntries == 0 { 48 return 49 } 50 c.mu.Lock() 51 defer c.mu.Unlock() 52 k := docMatchTreeCacheKey{field, value} 53 c.cache[k] = mt 54 if len(c.cache) > c.maxEntries { 55 c.evictRandom() 56 } 57} 58 59func (c *docMatchTreeCache) evictRandom() { 60 for k := range c.cache { 61 delete(c.cache, k) 62 break 63 } 64}