DojiSum's picture
Publish the current 141-task UXInteract release
ef987bb verified
Raw History Blame Contribute Delete
2.5 kB
package lru
import "time"
type entry struct {
key string
value string
expiresAt time.Time
ttl time.Duration
prev *entry
next *entry
}
type Cache struct {
capacity int
items map[string]*entry
head *entry
tail *entry
now func() time.Time
}
func NewCache(capacity int) *Cache {
if capacity < 1 {
capacity = 1
}
return NewCacheWithClock(capacity, time.Now)
}
// NewCacheWithClock exposes deterministic TTL testing without changing NewCache.
func NewCacheWithClock(capacity int, now func() time.Time) *Cache {
if capacity < 1 {
capacity = 1
}
if now == nil {
now = time.Now
}
return &Cache{capacity: capacity, items: map[string]*entry{}, now: now}
}
func (c *Cache) Set(key string, value string) { c.set(key, value, 0) }
func (c *Cache) SetWithTTL(key string, value string, ttl time.Duration) { c.set(key, value, ttl) }
func (c *Cache) set(key, value string, ttl time.Duration) {
if e, ok := c.items[key]; ok {
e.value = value
e.ttl = ttl
if ttl > 0 {
e.expiresAt = c.now().Add(ttl)
} else {
e.expiresAt = time.Time{}
}
c.moveToFront(e)
return
}
e := &entry{key: key, value: value, ttl: ttl}
if ttl > 0 {
e.expiresAt = c.now().Add(ttl)
}
c.items[key] = e
c.pushFront(e)
if len(c.items) > c.capacity {
c.remove(c.tail)
}
}
func (c *Cache) Get(key string) (string, bool) {
e, ok := c.items[key]
if !ok || c.expired(e) {
if ok {
c.remove(e)
}
return "", false
}
c.moveToFront(e)
return e.value, true
}
func (c *Cache) GetAndRenewTTL(key string) (string, bool) {
e, ok := c.items[key]
if !ok || c.expired(e) {
if ok {
c.remove(e)
}
return "", false
}
if e.ttl > 0 {
e.expiresAt = c.now().Add(e.ttl)
}
c.moveToFront(e)
return e.value, true
}
func (c *Cache) expired(e *entry) bool { return !e.expiresAt.IsZero() && !c.now().Before(e.expiresAt) }
func (c *Cache) pushFront(e *entry) {
e.prev = nil
e.next = c.head
if c.head != nil {
c.head.prev = e
}
c.head = e
if c.tail == nil {
c.tail = e
}
}
func (c *Cache) moveToFront(e *entry) {
if e == c.head {
return
}
if e.prev != nil {
e.prev.next = e.next
}
if e.next != nil {
e.next.prev = e.prev
}
if e == c.tail {
c.tail = e.prev
}
c.pushFront(e)
}
func (c *Cache) remove(e *entry) {
if e == nil {
return
}
if e.prev != nil {
e.prev.next = e.next
} else {
c.head = e.next
}
if e.next != nil {
e.next.prev = e.prev
} else {
c.tail = e.prev
}
delete(c.items, e.key)
}