6 "github.com/hashicorp/golang-lru/simplelru"
9 // Cache is a thread-safe fixed size LRU cache.
11 lru simplelru.LRUCache
15 // New creates an LRU of the given size.
16 func New(size int) (*Cache, error) {
17 return NewWithEvict(size, nil)
20 // NewWithEvict constructs a fixed size cache with the given eviction
22 func NewWithEvict(size int, onEvicted func(key interface{}, value interface{})) (*Cache, error) {
23 lru, err := simplelru.NewLRU(size, simplelru.EvictCallback(onEvicted))
33 // Purge is used to completely clear the cache.
34 func (c *Cache) Purge() {
40 // Add adds a value to the cache. Returns true if an eviction occurred.
41 func (c *Cache) Add(key, value interface{}) (evicted bool) {
44 return c.lru.Add(key, value)
47 // Get looks up a key's value from the cache.
48 func (c *Cache) Get(key interface{}) (value interface{}, ok bool) {
54 // Contains checks if a key is in the cache, without updating the
55 // recent-ness or deleting it for being stale.
56 func (c *Cache) Contains(key interface{}) bool {
58 defer c.lock.RUnlock()
59 return c.lru.Contains(key)
62 // Peek returns the key value (or undefined if not found) without updating
63 // the "recently used"-ness of the key.
64 func (c *Cache) Peek(key interface{}) (value interface{}, ok bool) {
66 defer c.lock.RUnlock()
67 return c.lru.Peek(key)
70 // ContainsOrAdd checks if a key is in the cache without updating the
71 // recent-ness or deleting it for being stale, and if not, adds the value.
72 // Returns whether found and whether an eviction occurred.
73 func (c *Cache) ContainsOrAdd(key, value interface{}) (ok, evicted bool) {
77 if c.lru.Contains(key) {
80 evicted = c.lru.Add(key, value)
84 // Remove removes the provided key from the cache.
85 func (c *Cache) Remove(key interface{}) {
91 // RemoveOldest removes the oldest item from the cache.
92 func (c *Cache) RemoveOldest() {
98 // Keys returns a slice of the keys in the cache, from oldest to newest.
99 func (c *Cache) Keys() []interface{} {
101 defer c.lock.RUnlock()
105 // Len returns the number of items in the cache.
106 func (c *Cache) Len() int {
108 defer c.lock.RUnlock()