2 Copyright 2013 Google Inc.
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
17 // Package lru implements an LRU cache.
20 import "container/list"
22 // Cache is an LRU cache. It is not safe for concurrent access.
24 // MaxEntries is the maximum number of cache entries before
25 // an item is evicted. Zero means no limit.
28 // OnEvicted optionally specificies a callback function to be
29 // executed when an entry is purged from the cache.
30 OnEvicted func(key Key, value interface{})
33 cache map[interface{}]*list.Element
36 // A Key may be any value that is comparable. See http://golang.org/ref/spec#Comparison_operators
44 // New creates a new Cache.
45 // If maxEntries is zero, the cache has no limit and it's assumed
46 // that eviction is done by the caller.
47 func New(maxEntries int) *Cache {
49 MaxEntries: maxEntries,
51 cache: make(map[interface{}]*list.Element),
55 // Add adds a value to the cache.
56 func (c *Cache) Add(key Key, value interface{}) {
58 c.cache = make(map[interface{}]*list.Element)
61 if ee, ok := c.cache[key]; ok {
63 ee.Value.(*entry).value = value
66 ele := c.ll.PushFront(&entry{key, value})
68 if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries {
73 // Get looks up a key's value from the cache.
74 func (c *Cache) Get(key Key) (value interface{}, ok bool) {
78 if ele, hit := c.cache[key]; hit {
80 return ele.Value.(*entry).value, true
85 // Remove removes the provided key from the cache.
86 func (c *Cache) Remove(key Key) {
90 if ele, hit := c.cache[key]; hit {
95 // RemoveOldest removes the oldest item from the cache.
96 func (c *Cache) RemoveOldest() {
106 func (c *Cache) removeElement(e *list.Element) {
108 kv := e.Value.(*entry)
109 delete(c.cache, kv.key)
110 if c.OnEvicted != nil {
111 c.OnEvicted(kv.key, kv.value)
115 // Len returns the number of items in the cache.
116 func (c *Cache) Len() int {
123 // Clear purges all stored items from the cache.
124 func (c *Cache) Clear() {
125 if c.OnEvicted != nil {
126 for _, e := range c.cache {
127 kv := e.Value.(*entry)
128 c.OnEvicted(kv.key, kv.value)