Debian Codegraph @

mirrors/lru.go

raw
1 /*
2 Copyright 2012, Google Inc.
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions are
7 met:
8
9 * Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11 * Redistributions in binary form must reproduce the above
12 copyright notice, this list of conditions and the following disclaimer
13 in the documentation and/or other materials provided with the
14 distribution.
15 * Neither the name of Google Inc. nor the names of its
16 contributors may be used to endorse or promote products derived from
17 this software without specific prior written permission.
18
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 package mirrors
33
34 // Implementation of an LRU cache in golang
35
36 import (
37 "container/list"
38 "fmt"
39 "sync"
40 "time"
41 )
42
43 // LRUCache is the internal structure of the cache
44 type LRUCache struct {
45 mu sync.Mutex
46
47 // list & table of *entry objects
48 list *list.List
49 table map[string]*list.Element
50
51 // Our current size, in bytes. Obviously a gross simplification and low-grade
52 // approximation.
53 size uint64
54
55 // How many bytes we are limiting the cache to.
56 capacity uint64
57 }
58
59 // Value that go into LRUCache need to satisfy this interface.
60 type Value interface {
61 Size() int
62 }
63
64 // Item contains the key and value that goes into the cache
65 type Item struct {
66 Key string
67 Value Value
68 }
69
70 type entry struct {
71 key string
72 value Value
73 size int
74 timeAccessed time.Time
75 }
76
77 // NewLRUCache return a new instance of the cache
78 func NewLRUCache(capacity uint64) *LRUCache {
79 return &LRUCache{
80 list: list.New(),
81 table: make(map[string]*list.Element),
82 capacity: capacity,
83 }
84 }
85
86 // Get a value from cache
87 func (lru *LRUCache) Get(key string) (v Value, ok bool) {
88 lru.mu.Lock()
89 defer lru.mu.Unlock()
90
91 element := lru.table[key]
92 if element == nil {
93 return nil, false
94 }
95 lru.moveToFront(element)
96 return element.Value.(*entry).value, true
97 }
98
99 // Set a key and associated value into the cache
100 func (lru *LRUCache) Set(key string, value Value) {
101 lru.mu.Lock()
102 defer lru.mu.Unlock()
103
104 if element := lru.table[key]; element != nil {
105 lru.updateInplace(element, value)
106 } else {
107 lru.addNew(key, value)
108 }
109 }
110
111 // SetIfAbsent sets a key into the cache only if it doesn't exist yet
112 func (lru *LRUCache) SetIfAbsent(key string, value Value) {
113 lru.mu.Lock()
114 defer lru.mu.Unlock()
115
116 if element := lru.table[key]; element != nil {
117 lru.moveToFront(element)
118 } else {
119 lru.addNew(key, value)
120 }
121 }
122
123 // Delete the key and associated value from the cache
124 func (lru *LRUCache) Delete(key string) bool {
125 lru.mu.Lock()
126 defer lru.mu.Unlock()
127
128 element := lru.table[key]
129 if element == nil {
130 return false
131 }
132
133 lru.list.Remove(element)
134 delete(lru.table, key)
135 lru.size -= uint64(element.Value.(*entry).size)
136 return true
137 }
138
139 // Clear the cache
140 func (lru *LRUCache) Clear() {
141 lru.mu.Lock()
142 defer lru.mu.Unlock()
143
144 lru.list.Init()
145 lru.table = make(map[string]*list.Element)
146 lru.size = 0
147 }
148
149 // SetCapacity sets the capacity of the cache
150 func (lru *LRUCache) SetCapacity(capacity uint64) {
151 lru.mu.Lock()
152 defer lru.mu.Unlock()
153
154 lru.capacity = capacity
155 lru.checkCapacity()
156 }
157
158 // Stats return stats about the caching structure
159 func (lru *LRUCache) Stats() (length, size, capacity uint64, oldest time.Time) {
160 lru.mu.Lock()
161 defer lru.mu.Unlock()
162 if lastElem := lru.list.Back(); lastElem != nil {
163 oldest = lastElem.Value.(*entry).timeAccessed
164 }
165 return uint64(lru.list.Len()), lru.size, lru.capacity, oldest
166 }
167
168 // StatsJSON returns the stats as JSON
169 func (lru *LRUCache) StatsJSON() string {
170 if lru == nil {
171 return "{}"
172 }
173 l, s, c, o := lru.Stats()
174 return fmt.Sprintf("{\"Length\": %v, \"Size\": %v, \"Capacity\": %v, \"OldestAccess\": \"%v\"}", l, s, c, o)
175 }
176
177 // Keys returns all the keys available in the cache
178 func (lru *LRUCache) Keys() []string {
179 lru.mu.Lock()
180 defer lru.mu.Unlock()
181
182 keys := make([]string, 0, lru.list.Len())
183 for e := lru.list.Front(); e != nil; e = e.Next() {
184 keys = append(keys, e.Value.(*entry).key)
185 }
186 return keys
187 }
188
189 // Items returns all the items available in the cache
190 func (lru *LRUCache) Items() []Item {
191 lru.mu.Lock()
192 defer lru.mu.Unlock()
193
194 items := make([]Item, 0, lru.list.Len())
195 for e := lru.list.Front(); e != nil; e = e.Next() {
196 v := e.Value.(*entry)
197 items = append(items, Item{Key: v.key, Value: v.value})
198 }
199 return items
200 }
201
202 func (lru *LRUCache) updateInplace(element *list.Element, value Value) {
203 valueSize := value.Size()
204 sizeDiff := valueSize - element.Value.(*entry).size
205 element.Value.(*entry).value = value
206 element.Value.(*entry).size = valueSize
207 lru.size += uint64(sizeDiff)
208 lru.moveToFront(element)
209 lru.checkCapacity()
210 }
211
212 func (lru *LRUCache) moveToFront(element *list.Element) {
213 lru.list.MoveToFront(element)
214 element.Value.(*entry).timeAccessed = time.Now()
215 }
216
217 func (lru *LRUCache) addNew(key string, value Value) {
218 newEntry := &entry{key, value, value.Size(), time.Now()}
219 element := lru.list.PushFront(newEntry)
220 lru.table[key] = element
221 lru.size += uint64(newEntry.size)
222 lru.checkCapacity()
223 }
224
225 func (lru *LRUCache) checkCapacity() {
226 // Partially duplicated from Delete
227 for lru.size > lru.capacity {
228 delElem := lru.list.Back()
229 delValue := delElem.Value.(*entry)
230 lru.list.Remove(delElem)
231 delete(lru.table, delValue.key)
232 lru.size -= uint64(delValue.size)
233 }
234 }