github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/util/genericlru/generic_lru.go (about) 1 package genericlru 2 3 import ( 4 "github.com/hashicorp/golang-lru/simplelru" 5 ) 6 7 type GenericLRU[K any, V any] struct { 8 lru *simplelru.LRU 9 } 10 11 type EvictCallback[K any, V any] func(k K, v *V) 12 13 func NewGenericLRU[K any, V any](sz int, evict EvictCallback[K, V]) (*GenericLRU[K, V], error) { 14 lru, err := simplelru.NewLRU(sz, func(key interface{}, value interface{}) { 15 evict(key.(K), value.(*V)) 16 }) 17 if err != nil { 18 return nil, err 19 } 20 return &GenericLRU[K, V]{lru}, nil 21 } 22 23 func (l *GenericLRU[K, V]) Get(k K) (*V, bool) { 24 v, ok := l.lru.Get(k) 25 if ok { 26 return v.(*V), ok 27 } 28 return nil, ok 29 } 30 31 func (l *GenericLRU[K, V]) Add(k K, v *V) (evicted bool) { 32 return l.lru.Add(k, v) 33 } 34 35 func (l *GenericLRU[K, V]) Remove(k K) (present bool) { 36 return l.lru.Remove(k) 37 } 38 39 func (l *GenericLRU[K, V]) Keys() (keys []K) { 40 for _, key := range l.lru.Keys() { 41 keys = append(keys, key.(K)) 42 } 43 return keys 44 } 45 46 func (l *GenericLRU[K, V]) Len() int { 47 return l.lru.Len() 48 }