| 1 | package gocache |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "reflect" |
| 6 | "sync" |
| 7 | "time" |
| 8 | ) |
| 9 | |
| 10 | var ( |
| 11 | Debug = false |
| 12 | ) |
| 13 | |
| 14 | const ( |
| 15 | // NoMaxSize means that the cache has no maximum number of entries in the cache |
| 16 | // Setting Cache.maxSize to this value also means there will be no eviction |
| 17 | NoMaxSize = 0 |
| 18 | |
| 19 | // NoMaxMemoryUsage means that the cache has no maximum number of entries in the cache |
| 20 | NoMaxMemoryUsage = 0 |
| 21 | |
| 22 | // DefaultMaxSize is the max size set if no max size is specified |
| 23 | DefaultMaxSize = 100000 |
| 24 | |
| 25 | // NoExpiration is the value that must be used as TTL to specify that the given key should never expire |
| 26 | NoExpiration = -1 |
| 27 | |
| 28 | Kilobyte = 1024 |
| 29 | Megabyte = 1024 * Kilobyte |
| 30 | Gigabyte = 1024 * Megabyte |
| 31 | ) |
| 32 | |
| 33 | var ( |
| 34 | ErrKeyDoesNotExist = errors.New("key does not exist") // Returned when a cache key does not exist |
| 35 | ErrKeyHasNoExpiration = errors.New("key has no expiration") // Returned when a cache key has no expiration |
| 36 | ErrJanitorAlreadyRunning = errors.New("janitor is already running") // Returned when the janitor has already been started |
| 37 | ) |
| 38 | |
| 39 | // Cache is the core struct of gocache which contains the data as well as all relevant configuration fields |
| 40 | // |
| 41 | // Do not instantiate this struct directly, use NewCache instead |
| 42 | type Cache struct { |
| 43 | // maxSize is the maximum amount of entries that can be in the cache at any given time |
| 44 | // By default, this is set to DefaultMaxSize |
| 45 | maxSize int |
| 46 | |
| 47 | // maxMemoryUsage is the maximum amount of memory that can be taken up by the cache at any time |
| 48 | // By default, this is set to NoMaxMemoryUsage, meaning that the default behavior is to not evict |
| 49 | // based on maximum memory usage |
| 50 | maxMemoryUsage int |
| 51 | |
| 52 | // evictionPolicy is the eviction policy |
| 53 | evictionPolicy EvictionPolicy |
| 54 | |
| 55 | // defaultTTL is the default TTL for each entry |
| 56 | // Defaults to NoExpiration |
| 57 | defaultTTL time.Duration |
| 58 | |
| 59 | // stats is the object that contains cache statistics/metrics |
| 60 | stats *Statistics |
| 61 | |
| 62 | // entries is the content of the cache |
| 63 | entries map[string]*Entry |
| 64 | |
| 65 | // mutex is the lock for making concurrent operations on the cache |
| 66 | mutex sync.RWMutex |
| 67 | |
| 68 | // head is the cache entry at the head of the cache |
| 69 | head *Entry |
| 70 | |
| 71 | // tail is the last cache node and also the next entry that will be evicted |
| 72 | tail *Entry |
| 73 | |
| 74 | // stopJanitor is the channel used to stop the janitor |
| 75 | stopJanitor chan bool |
| 76 | |
| 77 | // memoryUsage is the approximate memory usage of the cache (dataset only) in bytes |
| 78 | memoryUsage int |
| 79 | |
| 80 | // forceNilInterfaceOnNilPointer determines whether all Set-like functions should set a value as nil if the |
| 81 | // interface passed has a nil value but not a nil type. |
| 82 | // |
| 83 | // By default, interfaces are only nil when both their type and value is nil. |
| 84 | // This means that when you pass a pointer to a nil value, the type of the interface |
| 85 | // will still show as nil, which means that if you don't cast the interface after |
| 86 | // retrieving it, a nil check will return that the value is not false. |
| 87 | forceNilInterfaceOnNilPointer bool |
| 88 | } |
| 89 | |
| 90 | // MaxSize returns the maximum amount of keys that can be present in the cache before |
| 91 | // new entries trigger the eviction of the tail |
| 92 | func (cache *Cache) MaxSize() int { |
| 93 | return cache.maxSize |
| 94 | } |
| 95 | |
| 96 | // MaxMemoryUsage returns the configured maxMemoryUsage of the cache |
| 97 | func (cache *Cache) MaxMemoryUsage() int { |
| 98 | return cache.maxMemoryUsage |
| 99 | } |
| 100 | |
| 101 | // EvictionPolicy returns the EvictionPolicy of the Cache |
| 102 | func (cache *Cache) EvictionPolicy() EvictionPolicy { |
| 103 | return cache.evictionPolicy |
| 104 | } |
| 105 | |
| 106 | // Stats returns statistics from the cache |
| 107 | func (cache *Cache) Stats() Statistics { |
| 108 | cache.mutex.RLock() |
| 109 | stats := Statistics{ |
| 110 | EvictedKeys: cache.stats.EvictedKeys, |
| 111 | ExpiredKeys: cache.stats.ExpiredKeys, |
| 112 | Hits: cache.stats.Hits, |
| 113 | Misses: cache.stats.Misses, |
| 114 | } |
| 115 | cache.mutex.RUnlock() |
| 116 | return stats |
| 117 | } |
| 118 | |
| 119 | // MemoryUsage returns the current memory usage of the cache's dataset in bytes |
| 120 | // If MaxMemoryUsage is set to NoMaxMemoryUsage, this will return 0 |
| 121 | func (cache *Cache) MemoryUsage() int { |
| 122 | cache.mutex.RLock() |
| 123 | defer cache.mutex.RUnlock() |
| 124 | return cache.memoryUsage |
| 125 | } |
| 126 | |
| 127 | // WithMaxSize sets the maximum amount of entries that can be in the cache at any given time |
| 128 | // A maxSize of 0 or less means infinite |
| 129 | func (cache *Cache) WithMaxSize(maxSize int) *Cache { |
| 130 | if maxSize < 0 { |
| 131 | maxSize = NoMaxSize |
| 132 | } |
| 133 | if maxSize != NoMaxSize && cache.Count() == 0 { |
| 134 | cache.entries = make(map[string]*Entry, maxSize) |
| 135 | } |
| 136 | cache.maxSize = maxSize |
| 137 | return cache |
| 138 | } |
| 139 | |
| 140 | // WithMaxMemoryUsage sets the maximum amount of memory that can be used by the cache at any given time |
| 141 | // |
| 142 | // NOTE: This is approximate. |
| 143 | // |
| 144 | // Setting this to NoMaxMemoryUsage will disable eviction by memory usage |
| 145 | func (cache *Cache) WithMaxMemoryUsage(maxMemoryUsageInBytes int) *Cache { |
| 146 | if maxMemoryUsageInBytes < 0 { |
| 147 | maxMemoryUsageInBytes = NoMaxMemoryUsage |
| 148 | } |
| 149 | cache.maxMemoryUsage = maxMemoryUsageInBytes |
| 150 | return cache |
| 151 | } |
| 152 | |
| 153 | // WithEvictionPolicy sets eviction algorithm. |
| 154 | // |
| 155 | // Defaults to FirstInFirstOut (FIFO) |
| 156 | func (cache *Cache) WithEvictionPolicy(policy EvictionPolicy) *Cache { |
| 157 | cache.evictionPolicy = policy |
| 158 | return cache |
| 159 | } |
| 160 | |
| 161 | // WithDefaultTTL sets the default TTL for each entry (unless a different TTL is specified using SetWithTTL or SetAllWithTTL) |
| 162 | // |
| 163 | // Defaults to NoExpiration (-1) |
| 164 | func (cache *Cache) WithDefaultTTL(ttl time.Duration) *Cache { |
| 165 | if ttl > 1 { |
| 166 | cache.defaultTTL = ttl |
| 167 | } |
| 168 | return cache |
| 169 | } |
| 170 | |
| 171 | // WithForceNilInterfaceOnNilPointer sets whether all Set-like functions should set a value as nil if the |
| 172 | // interface passed has a nil value but not a nil type. |
| 173 | // |
| 174 | // In Go, an interface is only nil if both its type and value are nil, which means that a nil pointer |
| 175 | // (e.g. (*Struct)(nil)) will retain its attribution to the type, and the unmodified value returned from |
| 176 | // Cache.Get, for instance, would return false when compared with nil if this option is set to false. |
| 177 | // |
| 178 | // We can bypass this by detecting if the interface's value is nil and setting it to nil rather than |
| 179 | // a nil pointer, which will make the value returned from Cache.Get return true when compared with nil. |
| 180 | // This is exactly what passing true to WithForceNilInterfaceOnNilPointer does, and it's also the default behavior. |
| 181 | // |
| 182 | // Alternatively, you may pass false to WithForceNilInterfaceOnNilPointer, which will mean that you'll have |
| 183 | // to cast the value returned from Cache.Get to its original type to check for whether the pointer returned |
| 184 | // is nil or not. |
| 185 | // |
| 186 | // If set to true (default): |
| 187 | // |
| 188 | // cache := gocache.NewCache().WithForceNilInterfaceOnNilPointer(true) |
| 189 | // cache.Set("key", (*Struct)(nil)) |
| 190 | // value, _ := cache.Get("key") |
| 191 | // // the following returns true, because the interface{} (any) was forcefully set to nil |
| 192 | // if value == nil {} |
| 193 | // // the following will panic, because the value has been casted to its type (which is nil) |
| 194 | // if value.(*Struct) == nil {} |
| 195 | // |
| 196 | // If set to false: |
| 197 | // |
| 198 | // cache := gocache.NewCache().WithForceNilInterfaceOnNilPointer(false) |
| 199 | // cache.Set("key", (*Struct)(nil)) |
| 200 | // value, _ := cache.Get("key") |
| 201 | // // the following returns false, because the interface{} (any) returned has a non-nil type (*Struct) |
| 202 | // if value == nil {} |
| 203 | // // the following returns true, because the value has been cast to its type |
| 204 | // if value.(*Struct) == nil {} |
| 205 | // |
| 206 | // In other words, if set to true, you do not need to cast the value returned from the cache to |
| 207 | // check if the value is nil. |
| 208 | // |
| 209 | // Defaults to true |
| 210 | func (cache *Cache) WithForceNilInterfaceOnNilPointer(forceNilInterfaceOnNilPointer bool) *Cache { |
| 211 | cache.forceNilInterfaceOnNilPointer = forceNilInterfaceOnNilPointer |
| 212 | return cache |
| 213 | } |
| 214 | |
| 215 | // NewCache creates a new Cache |
| 216 | // |
| 217 | // Should be used in conjunction with Cache.WithMaxSize, Cache.WithMaxMemoryUsage and/or Cache.WithEvictionPolicy |
| 218 | // |
| 219 | // gocache.NewCache().WithMaxSize(10000).WithEvictionPolicy(gocache.LeastRecentlyUsed) |
| 220 | func NewCache() *Cache { |
| 221 | return &Cache{ |
| 222 | maxSize: DefaultMaxSize, |
| 223 | evictionPolicy: FirstInFirstOut, |
| 224 | defaultTTL: NoExpiration, |
| 225 | stats: &Statistics{}, |
| 226 | entries: make(map[string]*Entry), |
| 227 | mutex: sync.RWMutex{}, |
| 228 | stopJanitor: nil, |
| 229 | forceNilInterfaceOnNilPointer: true, |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | // Set creates or updates a key with a given value |
| 234 | func (cache *Cache) Set(key string, value any) { |
| 235 | cache.SetWithTTL(key, value, cache.defaultTTL) |
| 236 | } |
| 237 | |
| 238 | // SetWithTTL creates or updates a key with a given value and sets an expiration time (-1 is NoExpiration) |
| 239 | // |
| 240 | // The TTL provided must be greater than 0, or NoExpiration (-1). If a negative value that isn't -1 (NoExpiration) is |
| 241 | // provided, the entry will not be created if the key doesn't exist |
| 242 | func (cache *Cache) SetWithTTL(key string, value any, ttl time.Duration) { |
| 243 | // An interface is only nil if both its value and its type are nil, however, passing a nil pointer as an interface{} |
| 244 | // means that the interface itself is not nil, because the interface value is nil but not the type. |
| 245 | if cache.forceNilInterfaceOnNilPointer { |
| 246 | if value != nil && (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) { |
| 247 | value = nil |
| 248 | } |
| 249 | } |
| 250 | cache.mutex.Lock() |
| 251 | entry, ok := cache.get(key) |
| 252 | if !ok { |
| 253 | // A negative TTL that isn't -1 (NoExpiration) or 0 is an entry that will expire instantly, |
| 254 | // so might as well just not create it in the first place |
| 255 | if ttl != NoExpiration && ttl < 1 { |
| 256 | cache.mutex.Unlock() |
| 257 | return |
| 258 | } |
| 259 | // Cache entry doesn't exist, so we have to create a new one |
| 260 | entry = &Entry{ |
| 261 | Key: key, |
| 262 | RelevantTimestamp: time.Now(), |
| 263 | next: cache.head, |
| 264 | } |
| 265 | entry.Value = value |
| 266 | if cache.head == nil { |
| 267 | cache.tail = entry |
| 268 | } else { |
| 269 | cache.head.previous = entry |
| 270 | } |
| 271 | cache.head = entry |
| 272 | cache.entries[key] = entry |
| 273 | if cache.maxMemoryUsage != NoMaxMemoryUsage { |
| 274 | cache.memoryUsage += entry.SizeInBytes() |
| 275 | } |
| 276 | } else { |
| 277 | // A negative TTL that isn't -1 (NoExpiration) or 0 is an entry that will expire instantly, |
| 278 | // so might as well just delete it immediately instead of updating it |
| 279 | if ttl != NoExpiration && ttl < 1 { |
| 280 | cache.delete(key) |
| 281 | cache.mutex.Unlock() |
| 282 | return |
| 283 | } |
| 284 | if cache.maxMemoryUsage != NoMaxMemoryUsage { |
| 285 | // Subtract the old entry from the cache's memoryUsage |
| 286 | cache.memoryUsage -= entry.SizeInBytes() |
| 287 | } |
| 288 | entry.Value = value |
| 289 | entry.RelevantTimestamp = time.Now() |
| 290 | if cache.maxMemoryUsage != NoMaxMemoryUsage { |
| 291 | // Add the memory usage of the new entry to the cache's memoryUsage |
| 292 | cache.memoryUsage += entry.SizeInBytes() |
| 293 | } |
| 294 | // Because we just updated the entry, we need to move it back to HEAD |
| 295 | cache.moveExistingEntryToHead(entry) |
| 296 | } |
| 297 | if ttl != NoExpiration { |
| 298 | entry.Expiration = time.Now().Add(ttl).UnixNano() |
| 299 | } else { |
| 300 | entry.Expiration = NoExpiration |
| 301 | } |
| 302 | // If the cache doesn't have a maxSize/maxMemoryUsage, then there's no point |
| 303 | // checking if we need to evict an entry, so we'll just return now |
| 304 | if cache.maxSize == NoMaxSize && cache.maxMemoryUsage == NoMaxMemoryUsage { |
| 305 | cache.mutex.Unlock() |
| 306 | return |
| 307 | } |
| 308 | // If there's a maxSize and the cache has more entries than the maxSize, evict |
| 309 | if cache.maxSize != NoMaxSize && len(cache.entries) > cache.maxSize { |
| 310 | cache.evict() |
| 311 | } |
| 312 | // If there's a maxMemoryUsage and the memoryUsage is above the maxMemoryUsage, evict |
| 313 | if cache.maxMemoryUsage != NoMaxMemoryUsage && cache.memoryUsage > cache.maxMemoryUsage { |
| 314 | for cache.memoryUsage > cache.maxMemoryUsage && len(cache.entries) > 0 { |
| 315 | cache.evict() |
| 316 | } |
| 317 | } |
| 318 | cache.mutex.Unlock() |
| 319 | } |
| 320 | |
| 321 | // SetAll creates or updates multiple values |
| 322 | func (cache *Cache) SetAll(entries map[string]any) { |
| 323 | cache.SetAllWithTTL(entries, cache.defaultTTL) |
| 324 | } |
| 325 | |
| 326 | // SetAllWithTTL creates or updates multiple values |
| 327 | func (cache *Cache) SetAllWithTTL(entries map[string]any, ttl time.Duration) { |
| 328 | for key, value := range entries { |
| 329 | cache.SetWithTTL(key, value, ttl) |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | // Get retrieves an entry using the key passed as parameter |
| 334 | // If there is no such entry, the value returned will be nil and the boolean will be false |
| 335 | // If there is an entry, the value returned will be the value cached and the boolean will be true |
| 336 | func (cache *Cache) Get(key string) (any, bool) { |
| 337 | cache.mutex.Lock() |
| 338 | entry, ok := cache.get(key) |
| 339 | if !ok { |
| 340 | cache.stats.Misses++ |
| 341 | cache.mutex.Unlock() |
| 342 | return nil, false |
| 343 | } |
| 344 | if entry.Expired() { |
| 345 | cache.stats.ExpiredKeys++ |
| 346 | cache.delete(key) |
| 347 | cache.mutex.Unlock() |
| 348 | return nil, false |
| 349 | } |
| 350 | cache.stats.Hits++ |
| 351 | if cache.evictionPolicy == LeastRecentlyUsed { |
| 352 | entry.Accessed() |
| 353 | if cache.head == entry { |
| 354 | cache.mutex.Unlock() |
| 355 | return entry.Value, true |
| 356 | } |
| 357 | // Because the eviction policy is LRU, we need to move the entry back to HEAD |
| 358 | cache.moveExistingEntryToHead(entry) |
| 359 | } |
| 360 | cache.mutex.Unlock() |
| 361 | return entry.Value, true |
| 362 | } |
| 363 | |
| 364 | // GetValue retrieves an entry using the key passed as parameter |
| 365 | // Unlike Get, this function only returns the value |
| 366 | func (cache *Cache) GetValue(key string) any { |
| 367 | value, _ := cache.Get(key) |
| 368 | return value |
| 369 | } |
| 370 | |
| 371 | // GetByKeys retrieves multiple entries using the keys passed as parameter |
| 372 | // All keys are returned in the map, regardless of whether they exist or not, however, entries that do not exist in the |
| 373 | // cache will return nil, meaning that there is no way of determining whether a key genuinely has the value nil, or |
| 374 | // whether it doesn't exist in the cache using only this function. |
| 375 | func (cache *Cache) GetByKeys(keys []string) map[string]any { |
| 376 | entries := make(map[string]any) |
| 377 | for _, key := range keys { |
| 378 | entries[key], _ = cache.Get(key) |
| 379 | } |
| 380 | return entries |
| 381 | } |
| 382 | |
| 383 | // GetAll retrieves all cache entries |
| 384 | // |
| 385 | // If the eviction policy is LeastRecentlyUsed, note that unlike Get and GetByKeys, this does not update the last access |
| 386 | // timestamp. The reason for this is that since all cache entries will be accessed, updating the last access timestamp |
| 387 | // would provide very little benefit while harming the ability to accurately determine the next key that will be evicted |
| 388 | // |
| 389 | // You should probably avoid using this if you have a lot of entries. |
| 390 | // |
| 391 | // GetKeysByPattern is a good alternative if you want to retrieve entries that you do not have the key for, as it only |
| 392 | // retrieves the keys and does not trigger active eviction and has a parameter for setting a limit to the number of keys |
| 393 | // you wish to retrieve. |
| 394 | func (cache *Cache) GetAll() map[string]any { |
| 395 | entries := make(map[string]any) |
| 396 | cache.mutex.Lock() |
| 397 | for key, entry := range cache.entries { |
| 398 | if entry.Expired() { |
| 399 | cache.delete(key) |
| 400 | continue |
| 401 | } |
| 402 | entries[key] = entry.Value |
| 403 | } |
| 404 | cache.stats.Hits += uint64(len(entries)) |
| 405 | cache.mutex.Unlock() |
| 406 | return entries |
| 407 | } |
| 408 | |
| 409 | // GetKeysByPattern retrieves a slice of keys that match a given pattern |
| 410 | // If the limit is set to 0, the entire cache will be searched for matching keys. |
| 411 | // If the limit is above 0, the search will stop once the specified number of matching keys have been found. |
| 412 | // |
| 413 | // e.g. |
| 414 | // |
| 415 | // cache.GetKeysByPattern("*some*", 0) will return all keys containing "some" in them |
| 416 | // cache.GetKeysByPattern("*some*", 5) will return 5 keys (or less) containing "some" in them |
| 417 | // |
| 418 | // Note that GetKeysByPattern does not trigger active evictions, nor does it count as accessing the entry (if LRU). |
| 419 | // The reason for that behavior is that these two (active eviction and access) only applies when you access the value |
| 420 | // of the cache entry, and this function only returns the keys. |
| 421 | func (cache *Cache) GetKeysByPattern(pattern string, limit int) []string { |
| 422 | var matchingKeys []string |
| 423 | cache.mutex.Lock() |
| 424 | for key, value := range cache.entries { |
| 425 | if value.Expired() { |
| 426 | continue |
| 427 | } |
| 428 | if MatchPattern(pattern, key) { |
| 429 | matchingKeys = append(matchingKeys, key) |
| 430 | if limit > 0 && len(matchingKeys) >= limit { |
| 431 | break |
| 432 | } |
| 433 | } |
| 434 | } |
| 435 | cache.mutex.Unlock() |
| 436 | return matchingKeys |
| 437 | } |
| 438 | |
| 439 | // Delete removes a key from the cache |
| 440 | // |
| 441 | // Returns false if the key did not exist. |
| 442 | func (cache *Cache) Delete(key string) bool { |
| 443 | cache.mutex.Lock() |
| 444 | ok := cache.delete(key) |
| 445 | cache.mutex.Unlock() |
| 446 | return ok |
| 447 | } |
| 448 | |
| 449 | // DeleteAll deletes multiple entries based on the keys passed as parameter |
| 450 | // |
| 451 | // Returns the number of keys deleted |
| 452 | func (cache *Cache) DeleteAll(keys []string) int { |
| 453 | numberOfKeysDeleted := 0 |
| 454 | cache.mutex.Lock() |
| 455 | for _, key := range keys { |
| 456 | if cache.delete(key) { |
| 457 | numberOfKeysDeleted++ |
| 458 | } |
| 459 | } |
| 460 | cache.mutex.Unlock() |
| 461 | return numberOfKeysDeleted |
| 462 | } |
| 463 | |
| 464 | // DeleteKeysByPattern deletes all entries matching a given key pattern and returns the number of entries deleted. |
| 465 | // |
| 466 | // Note that DeleteKeysByPattern does not trigger active evictions, nor does it count as accessing the entry (if LRU). |
| 467 | func (cache *Cache) DeleteKeysByPattern(pattern string) int { |
| 468 | return cache.DeleteAll(cache.GetKeysByPattern(pattern, 0)) |
| 469 | } |
| 470 | |
| 471 | // Count returns the total amount of entries in the cache, regardless of whether they're expired or not |
| 472 | func (cache *Cache) Count() int { |
| 473 | cache.mutex.RLock() |
| 474 | count := len(cache.entries) |
| 475 | cache.mutex.RUnlock() |
| 476 | return count |
| 477 | } |
| 478 | |
| 479 | // Clear deletes all entries from the cache |
| 480 | func (cache *Cache) Clear() { |
| 481 | cache.mutex.Lock() |
| 482 | cache.entries = make(map[string]*Entry) |
| 483 | cache.memoryUsage = 0 |
| 484 | cache.head = nil |
| 485 | cache.tail = nil |
| 486 | cache.mutex.Unlock() |
| 487 | } |
| 488 | |
| 489 | // TTL returns the time until the cache entry specified by the key passed as parameter |
| 490 | // will be deleted. |
| 491 | func (cache *Cache) TTL(key string) (time.Duration, error) { |
| 492 | cache.mutex.RLock() |
| 493 | entry, ok := cache.get(key) |
| 494 | cache.mutex.RUnlock() |
| 495 | if !ok { |
| 496 | return 0, ErrKeyDoesNotExist |
| 497 | } |
| 498 | if entry.Expiration == NoExpiration { |
| 499 | return 0, ErrKeyHasNoExpiration |
| 500 | } |
| 501 | timeUntilExpiration := time.Until(time.Unix(0, entry.Expiration)) |
| 502 | if timeUntilExpiration < 0 { |
| 503 | // The key has already expired but hasn't been deleted yet. |
| 504 | // From the client's perspective, this means that the cache entry doesn't exist |
| 505 | return 0, ErrKeyDoesNotExist |
| 506 | } |
| 507 | return timeUntilExpiration, nil |
| 508 | } |
| 509 | |
| 510 | // Expire sets a key's expiration time |
| 511 | // |
| 512 | // A TTL of -1 means that the key will never expire |
| 513 | // A TTL of 0 means that the key will expire immediately |
| 514 | // If using LRU, note that this does not reset the position of the key |
| 515 | // |
| 516 | // Returns true if the cache key exists and has had its expiration time altered |
| 517 | func (cache *Cache) Expire(key string, ttl time.Duration) bool { |
| 518 | cache.mutex.Lock() |
| 519 | entry, ok := cache.get(key) |
| 520 | if !ok || entry.Expired() { |
| 521 | cache.mutex.Unlock() |
| 522 | return false |
| 523 | } |
| 524 | if ttl != NoExpiration { |
| 525 | entry.Expiration = time.Now().Add(ttl).UnixNano() |
| 526 | } else { |
| 527 | entry.Expiration = NoExpiration |
| 528 | } |
| 529 | cache.mutex.Unlock() |
| 530 | return true |
| 531 | } |
| 532 | |
| 533 | // get retrieves an entry using the key passed as parameter, but unlike Get, it doesn't update the access time or |
| 534 | // move the position of the entry to the head |
| 535 | func (cache *Cache) get(key string) (*Entry, bool) { |
| 536 | entry, ok := cache.entries[key] |
| 537 | return entry, ok |
| 538 | } |
| 539 | |
| 540 | func (cache *Cache) delete(key string) bool { |
| 541 | entry, ok := cache.entries[key] |
| 542 | if ok { |
| 543 | if cache.maxMemoryUsage != NoMaxMemoryUsage { |
| 544 | cache.memoryUsage -= entry.SizeInBytes() |
| 545 | } |
| 546 | cache.removeExistingEntryReferences(entry) |
| 547 | delete(cache.entries, key) |
| 548 | } |
| 549 | return ok |
| 550 | } |
| 551 | |
| 552 | // moveExistingEntryToHead replaces the current cache head for an existing entry |
| 553 | func (cache *Cache) moveExistingEntryToHead(entry *Entry) { |
| 554 | if !(entry == cache.head && entry == cache.tail) { |
| 555 | cache.removeExistingEntryReferences(entry) |
| 556 | } |
| 557 | if entry != cache.head { |
| 558 | entry.next = cache.head |
| 559 | entry.previous = nil |
| 560 | if cache.head != nil { |
| 561 | cache.head.previous = entry |
| 562 | } |
| 563 | cache.head = entry |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | // removeExistingEntryReferences modifies the next and previous reference of an existing entry and re-links |
| 568 | // the next and previous entry accordingly, as well as the cache head or/and the cache tail if necessary. |
| 569 | // Note that it does not remove the entry from the cache, only the references. |
| 570 | func (cache *Cache) removeExistingEntryReferences(entry *Entry) { |
| 571 | if cache.tail == entry && cache.head == entry { |
| 572 | cache.tail = nil |
| 573 | cache.head = nil |
| 574 | } else if cache.tail == entry { |
| 575 | cache.tail = cache.tail.previous |
| 576 | } else if cache.head == entry { |
| 577 | cache.head = cache.head.next |
| 578 | } |
| 579 | if entry.previous != nil { |
| 580 | entry.previous.next = entry.next |
| 581 | } |
| 582 | if entry.next != nil { |
| 583 | entry.next.previous = entry.previous |
| 584 | } |
| 585 | entry.next = nil |
| 586 | entry.previous = nil |
| 587 | } |
| 588 | |
| 589 | // evict removes the tail from the cache |
| 590 | func (cache *Cache) evict() { |
| 591 | if cache.tail == nil || len(cache.entries) == 0 { |
| 592 | return |
| 593 | } |
| 594 | if cache.tail != nil { |
| 595 | oldTail := cache.tail |
| 596 | cache.removeExistingEntryReferences(oldTail) |
| 597 | delete(cache.entries, oldTail.Key) |
| 598 | if cache.maxMemoryUsage != NoMaxMemoryUsage { |
| 599 | cache.memoryUsage -= oldTail.SizeInBytes() |
| 600 | } |
| 601 | cache.stats.EvictedKeys++ |
| 602 | } |
| 603 | } |