2021-05-24 16:46:44 +00:00
|
|
|
package cache
|
|
|
|
|
2021-05-24 17:05:36 +00:00
|
|
|
import (
|
2021-05-25 10:36:48 +00:00
|
|
|
"container/list"
|
2021-05-24 17:05:36 +00:00
|
|
|
"sync"
|
|
|
|
)
|
2021-05-24 16:46:44 +00:00
|
|
|
|
2021-05-24 17:05:36 +00:00
|
|
|
type Cache interface {
|
2021-05-25 10:36:48 +00:00
|
|
|
Put(string, interface{}) bool
|
2021-05-24 17:05:36 +00:00
|
|
|
Get(string) interface{}
|
2021-05-25 10:36:48 +00:00
|
|
|
Len() int
|
2021-05-24 17:05:36 +00:00
|
|
|
}
|
|
|
|
|
2021-05-25 10:36:48 +00:00
|
|
|
type LRUCache struct {
|
|
|
|
cap int
|
|
|
|
mu *sync.Mutex
|
|
|
|
l *list.List
|
|
|
|
m map[string]*list.Element
|
2021-05-24 16:46:44 +00:00
|
|
|
}
|
|
|
|
|
2021-05-25 10:36:48 +00:00
|
|
|
type pair struct {
|
|
|
|
key string
|
|
|
|
value interface{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func New(capacity int) Cache {
|
|
|
|
return &LRUCache{
|
|
|
|
cap: capacity,
|
|
|
|
mu: &sync.Mutex{},
|
|
|
|
l: &list.List{},
|
|
|
|
m: make(map[string]*list.Element, capacity),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *LRUCache) Get(key string) interface{} {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
|
|
|
// if the key exists, move to front
|
|
|
|
if node, ok := c.m[key]; ok {
|
|
|
|
val := node.Value.(*list.Element).Value.(pair).value
|
|
|
|
c.l.MoveToFront(node)
|
|
|
|
return val
|
2021-05-24 16:46:44 +00:00
|
|
|
}
|
2021-05-25 10:36:48 +00:00
|
|
|
return nil
|
2021-05-24 16:46:44 +00:00
|
|
|
}
|
|
|
|
|
2021-05-25 14:45:59 +00:00
|
|
|
func (c *LRUCache) Put(key string, value interface{}) bool {
|
2021-05-24 16:46:44 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
2021-05-25 10:36:48 +00:00
|
|
|
|
2021-06-04 13:26:13 +00:00
|
|
|
if c.cap == 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2021-05-25 10:36:48 +00:00
|
|
|
// if the key already exists, move to front and update the value
|
|
|
|
if node, ok := c.m[key]; ok {
|
|
|
|
c.l.MoveToFront(node)
|
|
|
|
node.Value.(*list.Element).Value = pair{key: key, value: value}
|
2021-05-25 14:45:59 +00:00
|
|
|
return true
|
2021-05-25 10:36:48 +00:00
|
|
|
}
|
|
|
|
|
2021-05-25 14:45:59 +00:00
|
|
|
// if the list is full, delete the last element
|
2021-05-25 10:36:48 +00:00
|
|
|
if c.l.Len() == c.cap {
|
|
|
|
idx := c.l.Back().Value.(*list.Element).Value.(pair).key
|
|
|
|
delete(c.m, idx)
|
|
|
|
c.l.Remove(c.l.Back())
|
2021-05-24 16:46:44 +00:00
|
|
|
}
|
2021-05-25 10:36:48 +00:00
|
|
|
|
|
|
|
// initialize a new list node
|
|
|
|
node := &list.Element{
|
|
|
|
Value: pair{
|
|
|
|
key: key,
|
|
|
|
value: value,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
element := c.l.PushFront(node)
|
|
|
|
c.m[key] = element
|
|
|
|
|
2021-05-25 14:45:59 +00:00
|
|
|
return false
|
2021-05-24 16:46:44 +00:00
|
|
|
}
|
|
|
|
|
2021-05-25 10:36:48 +00:00
|
|
|
func (c *LRUCache) Len() int {
|
|
|
|
return c.l.Len()
|
2021-05-24 16:46:44 +00:00
|
|
|
}
|