| 1 |
package twcache |
| 2 |
|
| 3 |
import ( |
| 4 |
"sync" |
| 5 |
"sync/atomic" |
| 6 |
) |
| 7 |
|
| 8 |
// EvictCallback is a function called when an entry is evicted. |
| 9 |
// This includes evictions during Purge or Resize operations. |
| 10 |
type EvictCallback[K comparable, V any] func(key K, value V) |
| 11 |
|
| 12 |
// LRU is a thread-safe, generic LRU cache with a fixed size. |
| 13 |
// It has zero dependencies, high performance, and full features. |
| 14 |
type LRU[K comparable, V any] struct { |
| 15 |
size int |
| 16 |
items map[K]*entry[K, V] |
| 17 |
head *entry[K, V] // Most Recently Used |
| 18 |
tail *entry[K, V] // Least Recently Used |
| 19 |
onEvict EvictCallback[K, V] |
| 20 |
|
| 21 |
mu sync.Mutex |
| 22 |
hits atomic.Int64 |
| 23 |
misses atomic.Int64 |
| 24 |
} |
| 25 |
|
| 26 |
// entry represents a single item in the LRU linked list. |
| 27 |
// It holds the key, value, and pointers to prev/next entries. |
| 28 |
type entry[K comparable, V any] struct { |
| 29 |
key K |
| 30 |
value V |
| 31 |
prev *entry[K, V] |
| 32 |
next *entry[K, V] |
| 33 |
} |
| 34 |
|
| 35 |
// NewLRU creates a new LRU cache with the given size. |
| 36 |
// Returns nil if size <= 0, acting as a disabled cache. |
| 37 |
// Caps size at 100,000 for reasonableness. |
| 38 |
func NewLRU[K comparable, V any](size int) *LRU[K, V] { |
| 39 |
return NewLRUEvict[K, V](size, nil) |
| 40 |
} |
| 41 |
|
| 42 |
// NewLRUEvict creates a new LRU cache with an eviction callback. |
| 43 |
// The callback is optional and called on evictions. |
| 44 |
// Returns nil if size <= 0. |
| 45 |
func NewLRUEvict[K comparable, V any](size int, onEvict EvictCallback[K, V]) *LRU[K, V] { |
| 46 |
if size <= 0 { |
| 47 |
return nil // nil = disabled cache (fast path in hot code) |
| 48 |
} |
| 49 |
if size > 100_000 { |
| 50 |
size = 100_000 // reasonable upper bound |
| 51 |
} |
| 52 |
return &LRU[K, V]{ |
| 53 |
size: size, |
| 54 |
items: make(map[K]*entry[K, V], size), |
| 55 |
onEvict: onEvict, |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
// GetOrCompute retrieves a value or computes it if missing. |
| 60 |
// Ensures no double computation under concurrency. |
| 61 |
// Ideal for expensive computations like twwidth. |
| 62 |
func (c *LRU[K, V]) GetOrCompute(key K, compute func() V) V { |
| 63 |
if c == nil || c.size <= 0 { |
| 64 |
return compute() |
| 65 |
} |
| 66 |
|
| 67 |
c.mu.Lock() |
| 68 |
if e, ok := c.items[key]; ok { |
| 69 |
c.moveToFront(e) |
| 70 |
c.hits.Add(1) |
| 71 |
c.mu.Unlock() |
| 72 |
return e.value |
| 73 |
} |
| 74 |
|
| 75 |
c.misses.Add(1) |
| 76 |
value := compute() // expensive work only on real miss |
| 77 |
|
| 78 |
// Double-check: someone might have added it while computing |
| 79 |
if e, ok := c.items[key]; ok { |
| 80 |
e.value = value |
| 81 |
c.moveToFront(e) |
| 82 |
c.mu.Unlock() |
| 83 |
return value |
| 84 |
} |
| 85 |
|
| 86 |
// Evict if needed |
| 87 |
if len(c.items) >= c.size { |
| 88 |
c.removeOldest() |
| 89 |
} |
| 90 |
|
| 91 |
e := &entry[K, V]{key: key, value: value} |
| 92 |
c.addToFront(e) |
| 93 |
c.items[key] = e |
| 94 |
c.mu.Unlock() |
| 95 |
return value |
| 96 |
} |
| 97 |
|
| 98 |
// Get retrieves a value by key if it exists. |
| 99 |
// Returns the value and true if found, else zero and false. |
| 100 |
// Updates the entry to most recently used. |
| 101 |
func (c *LRU[K, V]) Get(key K) (V, bool) { |
| 102 |
if c == nil || c.size <= 0 { |
| 103 |
var zero V |
| 104 |
return zero, false |
| 105 |
} |
| 106 |
c.mu.Lock() |
| 107 |
defer c.mu.Unlock() |
| 108 |
|
| 109 |
e, ok := c.items[key] |
| 110 |
if !ok { |
| 111 |
c.misses.Add(1) |
| 112 |
var zero V |
| 113 |
return zero, false |
| 114 |
} |
| 115 |
c.hits.Add(1) |
| 116 |
c.moveToFront(e) |
| 117 |
return e.value, true |
| 118 |
} |
| 119 |
|
| 120 |
// Add inserts or updates a key-value pair. |
| 121 |
// Evicts the oldest if cache is full. |
| 122 |
// Returns true if an eviction occurred. |
| 123 |
func (c *LRU[K, V]) Add(key K, value V) (evicted bool) { |
| 124 |
if c == nil || c.size <= 0 { |
| 125 |
return false |
| 126 |
} |
| 127 |
c.mu.Lock() |
| 128 |
defer c.mu.Unlock() |
| 129 |
|
| 130 |
if e, ok := c.items[key]; ok { |
| 131 |
e.value = value |
| 132 |
c.moveToFront(e) |
| 133 |
return false |
| 134 |
} |
| 135 |
|
| 136 |
if len(c.items) >= c.size { |
| 137 |
c.removeOldest() |
| 138 |
evicted = true |
| 139 |
} |
| 140 |
|
| 141 |
e := &entry[K, V]{key: key, value: value} |
| 142 |
c.addToFront(e) |
| 143 |
c.items[key] = e |
| 144 |
return evicted |
| 145 |
} |
| 146 |
|
| 147 |
// Remove deletes a key from the cache. |
| 148 |
// Returns true if the key was found and removed. |
| 149 |
func (c *LRU[K, V]) Remove(key K) bool { |
| 150 |
if c == nil || c.size <= 0 { |
| 151 |
return false |
| 152 |
} |
| 153 |
c.mu.Lock() |
| 154 |
defer c.mu.Unlock() |
| 155 |
|
| 156 |
e, ok := c.items[key] |
| 157 |
if !ok { |
| 158 |
return false |
| 159 |
} |
| 160 |
c.removeNode(e) |
| 161 |
delete(c.items, key) |
| 162 |
return true |
| 163 |
} |
| 164 |
|
| 165 |
// Purge clears all entries from the cache. |
| 166 |
// Calls onEvict for each entry if set. |
| 167 |
// Resets hit/miss counters. |
| 168 |
func (c *LRU[K, V]) Purge() { |
| 169 |
if c == nil || c.size <= 0 { |
| 170 |
return |
| 171 |
} |
| 172 |
c.mu.Lock() |
| 173 |
if c.onEvict != nil { |
| 174 |
for key, e := range c.items { |
| 175 |
c.onEvict(key, e.value) |
| 176 |
} |
| 177 |
} |
| 178 |
c.items = make(map[K]*entry[K, V], c.size) |
| 179 |
c.head = nil |
| 180 |
c.tail = nil |
| 181 |
c.hits.Store(0) |
| 182 |
c.misses.Store(0) |
| 183 |
c.mu.Unlock() |
| 184 |
} |
| 185 |
|
| 186 |
// Len returns the current number of items in the cache. |
| 187 |
func (c *LRU[K, V]) Len() int { |
| 188 |
if c == nil || c.size <= 0 { |
| 189 |
return 0 |
| 190 |
} |
| 191 |
c.mu.Lock() |
| 192 |
n := len(c.items) |
| 193 |
c.mu.Unlock() |
| 194 |
return n |
| 195 |
} |
| 196 |
|
| 197 |
// Cap returns the maximum capacity of the cache. |
| 198 |
func (c *LRU[K, V]) Cap() int { |
| 199 |
if c == nil { |
| 200 |
return 0 |
| 201 |
} |
| 202 |
return c.size |
| 203 |
} |
| 204 |
|
| 205 |
// HitRate returns the cache hit ratio (0.0 to 1.0). |
| 206 |
// Based on hits / (hits + misses). |
| 207 |
func (c *LRU[K, V]) HitRate() float64 { |
| 208 |
h := c.hits.Load() |
| 209 |
m := c.misses.Load() |
| 210 |
total := h + m |
| 211 |
if total == 0 { |
| 212 |
return 0.0 |
| 213 |
} |
| 214 |
return float64(h) / float64(total) |
| 215 |
} |
| 216 |
|
| 217 |
// RemoveOldest removes and returns the least recently used item. |
| 218 |
// Returns key, value, and true if an item was removed. |
| 219 |
// Calls onEvict if set. |
| 220 |
func (c *LRU[K, V]) RemoveOldest() (key K, value V, ok bool) { |
| 221 |
if c == nil || c.size <= 0 { |
| 222 |
return |
| 223 |
} |
| 224 |
c.mu.Lock() |
| 225 |
defer c.mu.Unlock() |
| 226 |
|
| 227 |
if c.tail == nil { |
| 228 |
return |
| 229 |
} |
| 230 |
|
| 231 |
key = c.tail.key |
| 232 |
value = c.tail.value |
| 233 |
|
| 234 |
c.removeOldest() |
| 235 |
return key, value, true |
| 236 |
} |
| 237 |
|
| 238 |
// moveToFront moves an entry to the front (MRU position). |
| 239 |
func (c *LRU[K, V]) moveToFront(e *entry[K, V]) { |
| 240 |
if c.head == e { |
| 241 |
return |
| 242 |
} |
| 243 |
c.removeNode(e) |
| 244 |
c.addToFront(e) |
| 245 |
} |
| 246 |
|
| 247 |
// addToFront adds an entry to the front of the list. |
| 248 |
func (c *LRU[K, V]) addToFront(e *entry[K, V]) { |
| 249 |
e.prev = nil |
| 250 |
e.next = c.head |
| 251 |
if c.head != nil { |
| 252 |
c.head.prev = e |
| 253 |
} |
| 254 |
c.head = e |
| 255 |
if c.tail == nil { |
| 256 |
c.tail = e |
| 257 |
} |
| 258 |
|
| 259 |
} |
| 260 |
|
| 261 |
// removeNode removes an entry from the linked list. |
| 262 |
func (c *LRU[K, V]) removeNode(e *entry[K, V]) { |
| 263 |
if e.prev != nil { |
| 264 |
e.prev.next = e.next |
| 265 |
} else { |
| 266 |
c.head = e.next |
| 267 |
} |
| 268 |
if e.next != nil { |
| 269 |
e.next.prev = e.prev |
| 270 |
} else { |
| 271 |
c.tail = e.prev |
| 272 |
} |
| 273 |
e.prev = nil |
| 274 |
e.next = nil |
| 275 |
} |
| 276 |
|
| 277 |
// removeOldest removes the tail entry (LRU). |
| 278 |
// Calls onEvict if set and deletes from map. |
| 279 |
func (c *LRU[K, V]) removeOldest() { |
| 280 |
if c.tail == nil { |
| 281 |
return |
| 282 |
} |
| 283 |
e := c.tail |
| 284 |
if c.onEvict != nil { |
| 285 |
c.onEvict(e.key, e.value) |
| 286 |
} |
| 287 |
c.removeNode(e) |
| 288 |
delete(c.items, e.key) |
| 289 |
} |