github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/core/access_contoller/my_lru/lru.go (about)

     1  package my_lru
     2  
     3  import (
     4  	lru "github.com/hashicorp/golang-lru"
     5  	"sync"
     6  )
     7  
     8  type Cache struct {
     9  	mu    sync.Mutex
    10  	cache *lru.Cache
    11  }
    12  
    13  func New(maxEntries int) (*Cache, error) {
    14  	var cache Cache
    15  	var err error
    16  	cache.cache, err = lru.New(maxEntries)
    17  	return &cache, err
    18  }
    19  
    20  // Add adds a value to the cache.
    21  func (c *Cache) Add(key string, value interface{}) {
    22  	c.mu.Lock()
    23  	defer c.mu.Unlock()
    24  
    25  	c.cache.Add(key, value)
    26  }
    27  
    28  // Get looks up a key's value from the cache.
    29  func (c *Cache) Get(key string) (value interface{}, ok bool) {
    30  	c.mu.Lock()
    31  	defer c.mu.Unlock()
    32  
    33  	return c.cache.Get(key)
    34  }
    35  
    36  // Remove removes the provided key from the cache.
    37  func (c *Cache) Remove(key string) {
    38  	c.mu.Lock()
    39  	defer c.mu.Unlock()
    40  
    41  	c.cache.Remove(key)
    42  }
    43  
    44  // RemoveOldest removes the oldest item from the cache.
    45  func (c *Cache) RemoveOldest() {
    46  	c.mu.Lock()
    47  	defer c.mu.Unlock()
    48  
    49  	c.cache.RemoveOldest()
    50  }
    51  
    52  // Len returns the number of items in the cache.
    53  func (c *Cache) Len() int {
    54  	return c.cache.Len()
    55  }
    56  
    57  // Clear purges all stored items from the cache.
    58  func (c *Cache) Clear() {
    59  	c.mu.Lock()
    60  	defer c.mu.Unlock()
    61  
    62  	c.cache.Purge()
    63  }