lru_cache.go 936 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package utils
  2. import (
  3. "container/list"
  4. )
  5. type CacheEntry struct {
  6. key int64
  7. value []byte
  8. }
  9. type LruCache struct {
  10. capacity int
  11. ll *list.List
  12. cache map[int64]*list.Element
  13. }
  14. func NewLRUCache(capacity int) *LruCache {
  15. return &LruCache{
  16. capacity: capacity,
  17. ll: list.New(),
  18. cache: make(map[int64]*list.Element),
  19. }
  20. }
  21. func (c *LruCache) Get(key int64) ([]byte, bool) {
  22. if ele, ok := c.cache[key]; ok {
  23. c.ll.MoveToFront(ele)
  24. return ele.Value.(*CacheEntry).value, true
  25. }
  26. return nil, false
  27. }
  28. func (c *LruCache) Put(key int64, value []byte) {
  29. if ele, ok := c.cache[key]; ok {
  30. c.ll.MoveToFront(ele)
  31. ele.Value.(*CacheEntry).value = value
  32. return
  33. }
  34. if c.ll.Len() >= c.capacity {
  35. oldest := c.ll.Back()
  36. if oldest != nil {
  37. c.ll.Remove(oldest)
  38. delete(c.cache, oldest.Value.(*CacheEntry).key)
  39. }
  40. }
  41. entry := &CacheEntry{key, value}
  42. ele := c.ll.PushFront(entry)
  43. c.cache[key] = ele
  44. }