github.com/ssgreg/logf@v1.4.1/cache.go (about) 1 package logf 2 3 import ( 4 "container/list" 5 ) 6 7 // Cache is the simple implementation of LRU cache. The Cache is not 8 // goroutine safe. 9 type Cache struct { 10 m map[int32]*list.Element 11 l *list.List 12 13 limit int 14 } 15 16 // NewCache returns a new Cache with the given limit. 17 func NewCache(limit int) *Cache { 18 return &Cache{ 19 m: make(map[int32]*list.Element, limit), 20 l: list.New(), 21 limit: limit, 22 } 23 } 24 25 // Set adds the given buffer with the given key to the cache or replaces 26 // the existing one with the same key. 27 func (c *Cache) Set(k int32, bytes []byte) { 28 e := c.l.PushFront(&element{k, bytes}) 29 c.m[k] = e 30 31 if c.l.Len() > c.limit { 32 c.removeBack() 33 } 34 } 35 36 // Get returns cached buffer for the given key. 37 func (c *Cache) Get(k int32) ([]byte, bool) { 38 if e, ok := c.m[k]; ok { 39 c.l.MoveToFront(e) 40 41 return e.Value.(*element).bytes, true 42 } 43 44 return nil, false 45 } 46 47 // Len returns the count of cached buffers. 48 func (c *Cache) Len() int { 49 return len(c.m) 50 } 51 52 // Clean removes all buffers from the cache. 53 func (c *Cache) Clean() { 54 c.l = list.New() 55 c.m = make(map[int32]*list.Element, c.limit) 56 } 57 58 func (c *Cache) removeBack() { 59 e := c.l.Remove(c.l.Back()) 60 delete(c.m, e.(*element).key) 61 } 62 63 type element struct { 64 key int32 65 bytes []byte 66 }