Debian Codegraph @

lru.go

raw symbols SCIP
1 package gcache
2
3 import (
4 "container/list"
5 "time"
6 )
7
8 // Discards the least recently used items first.
9 type LRUCache struct {
10 baseCache
11 items map[interface{}]*list.Element
12 evictList *list.List
13 }
14
15 func newLRUCache(cb *CacheBuilder) *LRUCache {
16 c := &LRUCache{}
17 buildCache(&c.baseCache, cb)
18
19 c.init()
20 c.loadGroup.cache = c
21 return c
22 }
23
24 func (c *LRUCache) init() {
25 c.evictList = list.New()
26 c.items = make(map[interface{}]*list.Element, c.size+1)
27 }
28
29 func (c *LRUCache) set(key, value interface{}) (interface{}, error) {
30 var err error
31 if c.serializeFunc != nil {
32 value, err = c.serializeFunc(key, value)
33 if err != nil {
34 return nil, err
35 }
36 }
37
38 // Check for existing item
39 var item *lruItem
40 if it, ok := c.items[key]; ok {
41 c.evictList.MoveToFront(it)
42 item = it.Value.(*lruItem)
43 item.value = value
44 } else {
45 // Verify size not exceeded
46 if c.evictList.Len() >= c.size {
47 c.evict(1)
48 }
49 item = &lruItem{
50 clock: c.clock,
51 key: key,
52 value: value,
53 }
54 c.items[key] = c.evictList.PushFront(item)
55 }
56
57 if c.expiration != nil {
58 t := c.clock.Now().Add(*c.expiration)
59 item.expiration = &t
60 }
61
62 if c.addedFunc != nil {
63 c.addedFunc(key, value)
64 }
65
66 return item, nil
67 }
68
69 // set a new key-value pair
70 func (c *LRUCache) Set(key, value interface{}) error {
71 c.mu.Lock()
72 defer c.mu.Unlock()
73 _, err := c.set(key, value)
74 return err
75 }
76
77 // Set a new key-value pair with an expiration time
78 func (c *LRUCache) SetWithExpire(key, value interface{}, expiration time.Duration) error {
79 c.mu.Lock()
80 defer c.mu.Unlock()
81 item, err := c.set(key, value)
82 if err != nil {
83 return err
84 }
85
86 t := c.clock.Now().Add(expiration)
87 item.(*lruItem).expiration = &t
88 return nil
89 }
90
91 // Get a value from cache pool using key if it exists.
92 // If it dose not exists key and has LoaderFunc,
93 // generate a value using `LoaderFunc` method returns value.
94 func (c *LRUCache) Get(key interface{}) (interface{}, error) {
95 v, err := c.get(key, false)
96 if err == KeyNotFoundError {
97 return c.getWithLoader(key, true)
98 }
99 return v, err
100 }
101
102 // GetIFPresent gets a value from cache pool using key if it exists.
103 // If it dose not exists key, returns KeyNotFoundError.
104 // And send a request which refresh value for specified key if cache object has LoaderFunc.
105 func (c *LRUCache) GetIFPresent(key interface{}) (interface{}, error) {
106 v, err := c.get(key, false)
107 if err == KeyNotFoundError {
108 return c.getWithLoader(key, false)
109 }
110 return v, err
111 }
112
113 func (c *LRUCache) get(key interface{}, onLoad bool) (interface{}, error) {
114 v, err := c.getValue(key, onLoad)
115 if err != nil {
116 return nil, err
117 }
118 if c.deserializeFunc != nil {
119 return c.deserializeFunc(key, v)
120 }
121 return v, nil
122 }
123
124 func (c *LRUCache) getValue(key interface{}, onLoad bool) (interface{}, error) {
125 c.mu.Lock()
126 item, ok := c.items[key]
127 if ok {
128 it := item.Value.(*lruItem)
129 if !it.IsExpired(nil) {
130 c.evictList.MoveToFront(item)
131 v := it.value
132 c.mu.Unlock()
133 if !onLoad {
134 c.stats.IncrHitCount()
135 }
136 return v, nil
137 }
138 c.removeElement(item)
139 }
140 c.mu.Unlock()
141 if !onLoad {
142 c.stats.IncrMissCount()
143 }
144 return nil, KeyNotFoundError
145 }
146
147 func (c *LRUCache) getWithLoader(key interface{}, isWait bool) (interface{}, error) {
148 if c.loaderExpireFunc == nil {
149 return nil, KeyNotFoundError
150 }
151 value, _, err := c.load(key, func(v interface{}, expiration *time.Duration, e error) (interface{}, error) {
152 if e != nil {
153 return nil, e
154 }
155 c.mu.Lock()
156 defer c.mu.Unlock()
157 item, err := c.set(key, v)
158 if err != nil {
159 return nil, err
160 }
161 if expiration != nil {
162 t := c.clock.Now().Add(*expiration)
163 item.(*lruItem).expiration = &t
164 }
165 return v, nil
166 }, isWait)
167 if err != nil {
168 return nil, err
169 }
170 return value, nil
171 }
172
173 // evict removes the oldest item from the cache.
174 func (c *LRUCache) evict(count int) {
175 for i := 0; i < count; i++ {
176 ent := c.evictList.Back()
177 if ent == nil {
178 return
179 } else {
180 c.removeElement(ent)
181 }
182 }
183 }
184
185 // Has checks if key exists in cache
186 func (c *LRUCache) Has(key interface{}) bool {
187 c.mu.RLock()
188 defer c.mu.RUnlock()
189 now := time.Now()
190 return c.has(key, &now)
191 }
192
193 func (c *LRUCache) has(key interface{}, now *time.Time) bool {
194 item, ok := c.items[key]
195 if !ok {
196 return false
197 }
198 return !item.Value.(*lruItem).IsExpired(now)
199 }
200
201 // Remove removes the provided key from the cache.
202 func (c *LRUCache) Remove(key interface{}) bool {
203 c.mu.Lock()
204 defer c.mu.Unlock()
205
206 return c.remove(key)
207 }
208
209 func (c *LRUCache) remove(key interface{}) bool {
210 if ent, ok := c.items[key]; ok {
211 c.removeElement(ent)
212 return true
213 }
214 return false
215 }
216
217 func (c *LRUCache) removeElement(e *list.Element) {
218 c.evictList.Remove(e)
219 entry := e.Value.(*lruItem)
220 delete(c.items, entry.key)
221 if c.evictedFunc != nil {
222 entry := e.Value.(*lruItem)
223 c.evictedFunc(entry.key, entry.value)
224 }
225 }
226
227 func (c *LRUCache) keys() []interface{} {
228 c.mu.RLock()
229 defer c.mu.RUnlock()
230 keys := make([]interface{}, len(c.items))
231 var i = 0
232 for k := range c.items {
233 keys[i] = k
234 i++
235 }
236 return keys
237 }
238
239 // GetALL returns all key-value pairs in the cache.
240 func (c *LRUCache) GetALL(checkExpired bool) map[interface{}]interface{} {
241 c.mu.RLock()
242 defer c.mu.RUnlock()
243 items := make(map[interface{}]interface{}, len(c.items))
244 now := time.Now()
245 for k, item := range c.items {
246 if !checkExpired || c.has(k, &now) {
247 items[k] = item.Value.(*lruItem).value
248 }
249 }
250 return items
251 }
252
253 // Keys returns a slice of the keys in the cache.
254 func (c *LRUCache) Keys(checkExpired bool) []interface{} {
255 c.mu.RLock()
256 defer c.mu.RUnlock()
257 keys := make([]interface{}, 0, len(c.items))
258 now := time.Now()
259 for k := range c.items {
260 if !checkExpired || c.has(k, &now) {
261 keys = append(keys, k)
262 }
263 }
264 return keys
265 }
266
267 // Len returns the number of items in the cache.
268 func (c *LRUCache) Len(checkExpired bool) int {
269 c.mu.RLock()
270 defer c.mu.RUnlock()
271 if !checkExpired {
272 return len(c.items)
273 }
274 var length int
275 now := time.Now()
276 for k := range c.items {
277 if c.has(k, &now) {
278 length++
279 }
280 }
281 return length
282 }
283
284 // Completely clear the cache
285 func (c *LRUCache) Purge() {
286 c.mu.Lock()
287 defer c.mu.Unlock()
288
289 if c.purgeVisitorFunc != nil {
290 for key, item := range c.items {
291 it := item.Value.(*lruItem)
292 v := it.value
293 c.purgeVisitorFunc(key, v)
294 }
295 }
296
297 c.init()
298 }
299
300 type lruItem struct {
301 clock Clock
302 key interface{}
303 value interface{}
304 expiration *time.Time
305 }
306
307 // IsExpired returns boolean value whether this item is expired or not.
308 func (it *lruItem) IsExpired(now *time.Time) bool {
309 if it.expiration == nil {
310 return false
311 }
312 if now == nil {
313 t := it.clock.Now()
314 now = &t
315 }
316 return it.expiration.Before(*now)
317 }