cache.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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) Clear() {
  63. c.mu.Lock()
  64. defer c.mu.Unlock()
  65. c.items = make(map[string]*list.Element)
  66. c.queue = list.New()
  67. }
  68. func (c *Cache) clean() {
  69. if element := c.queue.Back(); element != nil {
  70. item := c.queue.Remove(element).(*Item)
  71. delete(c.items, item.Key)
  72. }
  73. }