aboutsummaryrefslogtreecommitdiff
path: root/weed/util/chunk_cache/chunk_cache_in_memory.go
blob: 1eb00e1faa23ad9db2198a179ef01cc5bcb81a1c (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
package chunk_cache

import (
	"time"

	"github.com/karlseguin/ccache/v2"
)

// a global cache for recently accessed file chunks
type ChunkCacheInMemory struct {
	cache *ccache.Cache
}

func NewChunkCacheInMemory(maxEntries int64) *ChunkCacheInMemory {
	pruneCount := maxEntries >> 3
	if pruneCount <= 0 {
		pruneCount = 500
	}
	return &ChunkCacheInMemory{
		cache: ccache.New(ccache.Configure().MaxSize(maxEntries).ItemsToPrune(uint32(pruneCount))),
	}
}

func (c *ChunkCacheInMemory) GetChunk(fileId string) []byte {
	item := c.cache.Get(fileId)
	if item == nil {
		return nil
	}
	data := item.Value().([]byte)
	item.Extend(time.Hour)
	return data
}

func (c *ChunkCacheInMemory) SetChunk(fileId string, data []byte) {
	c.cache.Set(fileId, data, time.Hour)
}