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) {
43 evicted = c.lru.Add(key, value)
48 // Get looks up a key's value from the cache.
49 func (c *Cache) Get(key interface{}) (value interface{}, ok bool) {
51 value, ok = c.lru.Get(key)
56 // Contains checks if a key is in the cache, without updating the
57 // recent-ness or deleting it for being stale.
58 func (c *Cache) Contains(key interface{}) bool {
60 containKey := c.lru.Contains(key)
65 // Peek returns the key value (or undefined if not found) without updating
66 // the "recently used"-ness of the key.
67 func (c *Cache) Peek(key interface{}) (value interface{}, ok bool) {
69 value, ok = c.lru.Peek(key)
74 // ContainsOrAdd checks if a key is in the cache without updating the
75 // recent-ness or deleting it for being stale, and if not, adds the value.
76 // Returns whether found and whether an eviction occurred.
77 func (c *Cache) ContainsOrAdd(key, value interface{}) (ok, evicted bool) {
81 if c.lru.Contains(key) {
84 evicted = c.lru.Add(key, value)
88 // Remove removes the provided key from the cache.
89 func (c *Cache) Remove(key interface{}) {
95 // RemoveOldest removes the oldest item from the cache.
96 func (c *Cache) RemoveOldest() {
102 // Keys returns a slice of the keys in the cache, from oldest to newest.
103 func (c *Cache) Keys() []interface{} {
110 // Len returns the number of items in the cache.
111 func (c *Cache) Len() int {
113 length := c.lru.Len()