1
0

cache.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package lru_memory_cache
  2. import (
  3. "container/list"
  4. "errors"
  5. "sync"
  6. )
  7. type Cache struct {
  8. capacity int
  9. mu sync.RWMutex
  10. items map[string]*list.Element
  11. queue *list.List
  12. }
  13. type Item struct {
  14. Key string
  15. Value interface{}
  16. }
  17. func NewCache(c Config) (*Cache, error) {
  18. if c.capacity == 0 {
  19. return nil, errors.New("empty capacity")
  20. }
  21. return &Cache{
  22. capacity: int(c.capacity),
  23. items: make(map[string]*list.Element),
  24. queue: list.New(),
  25. }, nil
  26. }
  27. func (c *Cache) Set(key string, value interface{}) {
  28. c.mu.Lock()
  29. defer c.mu.Unlock()
  30. if element, found := c.items[key]; found {
  31. c.queue.MoveToFront(element)
  32. element.Value.(*Item).Value = value
  33. return
  34. }
  35. if c.queue.Len() == c.capacity {
  36. c.clean()
  37. }
  38. item := &Item{
  39. Key: key,
  40. Value: value,
  41. }
  42. element := c.queue.PushFront(item)
  43. c.items[item.Key] = element
  44. }
  45. func (c *Cache) Get(key string) (interface{}, bool) {
  46. c.mu.RLock()
  47. defer c.mu.RUnlock()
  48. if element, found := c.items[key]; found {
  49. c.queue.MoveToFront(element)
  50. return element.Value.(*Item).Value, true
  51. }
  52. return nil, false
  53. }
  54. func (c *Cache) Delete(key string) {
  55. c.mu.Lock()
  56. defer c.mu.Unlock()
  57. if element, found := c.items[key]; found {
  58. c.queue.Remove(element)
  59. delete(c.items, key)
  60. }
  61. }
  62. func (c *Cache) clean() {
  63. if element := c.queue.Back(); element != nil {
  64. item := c.queue.Remove(element).(*Item)
  65. delete(c.items, item.Key)
  66. }
  67. }