github.com/saintwish/kv@v1.0.4/ccmap/ccmap.go (about) 1 package ccmap 2 3 import ( 4 "fmt" 5 "sync" 6 "encoding/json" 7 ) 8 9 type Cache[K comparable, V any] struct { 10 Map map[K]V //cached items 11 OnEvicted func(K, V) //function that's called when cached item is deleted automatically 12 13 *sync.RWMutex //mutex 14 } 15 16 func New[K comparable, V any]() *Cache[K, V] { 17 return &Cache[K, V] { 18 Map: make(map[K]V, 0), 19 RWMutex: &sync.RWMutex{}, 20 } 21 } 22 23 func (c *Cache[K, V]) SetOnEvicted(f func(K, V)) { 24 c.OnEvicted = f 25 } 26 27 func (c *Cache[K, V]) Get(key K) (data V) { 28 c.RLock() 29 30 data,_ = c.Map[key] 31 32 c.RUnlock() 33 return 34 } 35 36 func (c *Cache[K, V]) GetHas(key K) (data V, ok bool) { 37 c.RLock() 38 39 data, ok = c.Map[key] 40 41 c.RUnlock() 42 return 43 } 44 45 func (c *Cache[K, V]) Has(key K) (ok bool) { 46 c.RLock() 47 48 _, ok = c.Map[key]; 49 50 c.RUnlock() 51 return 52 } 53 54 func (c *Cache[K, V]) Set(key K, val V) { 55 c.Lock() 56 57 c.Map[key] = val 58 59 c.Unlock() 60 } 61 62 func (c *Cache[K, V]) Add(key K, val V) error { 63 if c.Has(key) { 64 return fmt.Errorf("ccmap: Data already exists with given key %T", key) 65 } 66 67 c.Set(key, val) 68 69 return nil 70 } 71 72 func (c *Cache[K, V]) Update(key K, val V) error { 73 if !c.Has(key) { 74 return fmt.Errorf("ccmap: Data doesn't exists with given key %T", key) 75 } 76 77 c.Set(key, val) 78 79 return nil 80 } 81 82 func (c *Cache[K, V]) Delete(key K) { 83 if c.Has(key) { 84 delete(c.Map, key) 85 } 86 } 87 88 func (c *Cache[K, V]) Flush() { 89 for k,v := range c.Map { 90 c.OnEvicted(k, v) 91 delete(c.Map, k) 92 } 93 } 94 95 func (c *Cache[K, V]) LoadFromJSON(b []byte) (err error) { 96 c.Lock() 97 98 err = json.Unmarshal(b, &c.Map) 99 100 c.Unlock() 101 return 102 }