2020-04-12 04:12:41 +00:00
|
|
|
package chunk_cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
2021-01-08 10:17:43 +00:00
|
|
|
"github.com/karlseguin/ccache/v2"
|
2020-04-12 04:12:41 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// 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) {
|
2021-03-23 05:33:07 +00:00
|
|
|
localCopy := make([]byte, len(data))
|
|
|
|
copy(localCopy, data)
|
|
|
|
c.cache.Set(fileId, localCopy, time.Hour)
|
2020-04-12 04:12:41 +00:00
|
|
|
}
|