diff options
Diffstat (limited to 'src/cache')
-rw-r--r-- | src/cache/cache.go | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/src/cache/cache.go b/src/cache/cache.go new file mode 100644 index 0000000..ade286a --- /dev/null +++ b/src/cache/cache.go @@ -0,0 +1,49 @@ +// Package cache implements a simple LRU cache which can be completely purged +// whenever needed. +package cache + +import ( + lru "github.com/hashicorp/golang-lru" +) + +// Cache describes an in-memory cache for arbitrary objects, which has a Purge +// method for clearing everything at once. +type Cache interface { + Get(key string) interface{} + Set(key string, value interface{}) + Purge() +} + +type cache struct { + cache *lru.Cache +} + +// New instantiates and returns a new Cache which can hold up to the given +// number of entries. +func New(size int) Cache { + c, err := lru.New(size) + + // instantiating the lru cache can't realistically fail + if err != nil { + panic(err) + } + + return &cache{c} +} + +func (c *cache) Get(key string) interface{} { + value, ok := c.cache.Get(key) + if !ok { + return nil + } + + return value +} + +func (c *cache) Set(key string, value interface{}) { + c.cache.Add(key, value) +} + +func (c *cache) Purge() { + c.cache.Purge() +} |