aboutsummaryrefslogtreecommitdiff
path: root/weed/sftpd/utils/lru_cache.go
blob: 3464a706499dc25ded355ed293c160377fc5f381 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package utils

import (
	"container/list"
)

type CacheEntry struct {
	key   int64
	value []byte
}

type LruCache struct {
	capacity int
	ll       *list.List
	cache    map[int64]*list.Element
}

func NewLRUCache(capacity int) *LruCache {
	return &LruCache{
		capacity: capacity,
		ll:       list.New(),
		cache:    make(map[int64]*list.Element),
	}
}

func (c *LruCache) Get(key int64) ([]byte, bool) {
	if ele, ok := c.cache[key]; ok {
		c.ll.MoveToFront(ele)
		return ele.Value.(*CacheEntry).value, true
	}
	return nil, false
}

func (c *LruCache) Put(key int64, value []byte) {
	if ele, ok := c.cache[key]; ok {
		c.ll.MoveToFront(ele)
		ele.Value.(*CacheEntry).value = value
		return
	}

	if c.ll.Len() >= c.capacity {
		oldest := c.ll.Back()
		if oldest != nil {
			c.ll.Remove(oldest)
			delete(c.cache, oldest.Value.(*CacheEntry).key)
		}
	}

	entry := &CacheEntry{key, value}
	ele := c.ll.PushFront(entry)
	c.cache[key] = ele
}