Skip to content

Commit

Permalink
write func getContent
Browse files Browse the repository at this point in the history
  • Loading branch information
toshinari123 committed Jan 10, 2024
1 parent 28f1f86 commit 2222d24
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions internal/cache/contentcache.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package cache

import (
"io"
"bytes"
"sync"

"github.com/dgraph-io/ristretto"
Expand All @@ -11,13 +11,13 @@ const (
contentCacheSize int64 = 1000000000
)

type ContentCache[T io.WriteCloser] struct {
m map[string]sync.Mutex
type ContentCache struct {
m map[string]*sync.Mutex
cache *ristretto.Cache
load func(id string) (T, error)
load func(id string) (*bytes.Buffer, error)
}

func NewContentCache[T io.WriteCloser](load func(id string) (T, error)) (*ContentCache[T], error) {
func NewContentCache(load func(id string) (*bytes.Buffer, error)) (*ContentCache, error) {
cache, err := ristretto.NewCache(&ristretto.Config{
NumCounters: 1e7,
MaxCost: contentCacheSize,
Expand All @@ -27,5 +27,24 @@ func NewContentCache[T io.WriteCloser](load func(id string) (T, error)) (*Conten
return nil, err
}

return &ContentCache[T]{cache: cache, load: load}, nil
return &ContentCache{m: make(map[string]*sync.Mutex), cache: cache, load: load}, nil
}

func (c *ContentCache) getContent(id string) (*bytes.Buffer, error) {
c.m[id].Lock()
defer c.m[id].Unlock()

temp, found := c.cache.Get(id)
ce := temp.(*bytes.Buffer)
if found {
return ce, nil
}

ce, err := c.load(id)
if err != nil {
return bytes.NewBuffer([]byte{}), err
}

c.cache.Set(id, ce, int64(ce.Len()))
return ce, nil
}

0 comments on commit 2222d24

Please sign in to comment.