| 1 | package types |
| 2 | |
| 3 | // EvictReason is the reason for an entry to be evicted from the cache. |
| 4 | // It is used in the [OnEvictCallback] function. |
| 5 | type EvictReason int |
| 6 | |
| 7 | const ( |
| 8 | // EvictReasonExpired is used when an item is removed because its TTL has expired. |
| 9 | EvictReasonExpired = iota |
| 10 | // EvictReasonEvicted is used when an item is removed because the cache size limit was exceeded. |
| 11 | EvictReasonEvicted |
| 12 | // EvictReasonRemoved is used when an item is explicitly deleted. |
| 13 | EvictReasonRemoved |
| 14 | ) |
| 15 | |
| 16 | type OnEvictCallback[K comparable, V any] func(key K, value V, reason EvictReason) |
| 17 | |
| 18 | // Cache is the interface for a cache. |
| 19 | type Cache[K comparable, V any] interface { |
| 20 | // Set sets the value for the given key on cache. |
| 21 | Set(key K, value V) |
| 22 | |
| 23 | // Get gets the value for the given key from cache. |
| 24 | Get(key K) (value V, ok bool) |
| 25 | |
| 26 | // Remove removes the provided key from the cache. |
| 27 | Remove(key K) (ok bool) |
| 28 | |
| 29 | // Contains check if a key exists in cache without updating the recent-ness |
| 30 | Contains(key K) (ok bool) |
| 31 | |
| 32 | // Peek returns key's value without updating the recent-ness. |
| 33 | Peek(key K) (value V, ok bool) |
| 34 | |
| 35 | // SetOnEvicted sets the callback function that will be called when an entry is evicted from the cache. |
| 36 | SetOnEvicted(callback OnEvictCallback[K, V]) |
| 37 | |
| 38 | // Len returns the number of entries in the cache. |
| 39 | Len() int |
| 40 | |
| 41 | // Purge clears all cache entries |
| 42 | Purge() |
| 43 | |
| 44 | // Close closes the cache and releases any resources associated with it. |
| 45 | Close() |
| 46 | } |