github.com/avicd/go-utilx@v0.1.0/bufx/cache.go (about) 1 package bufx 2 3 import ( 4 "sync" 5 ) 6 7 type Cache[K comparable, V any] interface { 8 Get(key K) (V, bool) 9 Put(key K, val V) 10 Remove(key K) bool 11 Len() int 12 Clear() 13 } 14 15 type Entry[K comparable, V any] struct { 16 Key K 17 Value V 18 } 19 20 type SimpleCache[K comparable, V any] struct { 21 Size int 22 mutex sync.RWMutex 23 store map[K]*Entry[K, V] 24 keys []K 25 } 26 27 func (it *SimpleCache[K, V]) Get(key K) (V, bool) { 28 var ret V 29 var exist bool 30 it.mutex.RLock() 31 if entry, ok := it.store[key]; ok { 32 ret = entry.Value 33 exist = true 34 } 35 it.mutex.RUnlock() 36 return ret, exist 37 } 38 39 func (it *SimpleCache[K, V]) Put(key K, val V) { 40 it.mutex.Lock() 41 if it.store == nil { 42 it.store = map[K]*Entry[K, V]{} 43 } 44 entry := it.store[key] 45 if entry == nil { 46 if it.Size > 0 && len(it.store)+1 > it.Size { 47 delete(it.store, it.keys[0]) 48 it.keys = it.keys[1:] 49 } 50 entry = &Entry[K, V]{Key: key} 51 } 52 entry.Value = val 53 it.store[key] = entry 54 it.keys = append(it.keys, key) 55 it.mutex.Unlock() 56 } 57 58 func (it *SimpleCache[K, V]) Remove(key K) bool { 59 var ret bool 60 it.mutex.Lock() 61 if _, ok := it.store[key]; ok { 62 delete(it.store, key) 63 ret = true 64 } 65 it.mutex.Unlock() 66 return ret 67 } 68 69 func (it *SimpleCache[K, V]) Len() int { 70 return len(it.store) 71 } 72 73 func (it *SimpleCache[K, V]) Clear() { 74 it.mutex.Lock() 75 it.store = map[K]*Entry[K, V]{} 76 it.mutex.Unlock() 77 }