You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
707 B

  1. package pb_cache
  2. import (
  3. "time"
  4. "github.com/karlseguin/ccache"
  5. )
  6. // a global cache for recently accessed file chunks
  7. type ChunkCache struct {
  8. cache *ccache.Cache
  9. }
  10. func NewChunkCache(maxEntries int64) *ChunkCache {
  11. pruneCount := maxEntries >> 3
  12. if pruneCount <= 0 {
  13. pruneCount = 500
  14. }
  15. return &ChunkCache{
  16. cache: ccache.New(ccache.Configure().MaxSize(maxEntries).ItemsToPrune(uint32(pruneCount))),
  17. }
  18. }
  19. func (c *ChunkCache) GetChunk(fileId string) []byte {
  20. item := c.cache.Get(fileId)
  21. if item == nil {
  22. return nil
  23. }
  24. data := item.Value().([]byte)
  25. item.Extend(time.Hour)
  26. return data
  27. }
  28. func (c *ChunkCache) SetChunk(fileId string, data []byte) {
  29. c.cache.Set(fileId, data, time.Hour)
  30. }