github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/cache/memory.go (about)

     1  package cache
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  	"time"
     7  
     8  	"github.com/safedep/dry/log"
     9  )
    10  
    11  type memoryCache struct {
    12  	store sync.Map
    13  }
    14  
    15  // NewUnsafeMemoryCache returns an unbounded caching implementation not
    16  // suitable for real life use
    17  func NewUnsafeMemoryCache() Cache {
    18  	return &memoryCache{
    19  		store: sync.Map{},
    20  	}
    21  }
    22  
    23  func (c *memoryCache) Put(key *CacheKey, data *CacheData, ttl time.Duration) error {
    24  	log.Debugf("Memory Cache: Storing %v", *key)
    25  	c.store.Store(fmt.Sprintf("%s/%s/%s", key.Source, key.Type, key.Id), data)
    26  
    27  	return nil
    28  }
    29  
    30  func (c *memoryCache) Get(key *CacheKey) (*CacheData, error) {
    31  	log.Debugf("Memory Cache: Loading %v", *key)
    32  	result, ok := c.store.Load(fmt.Sprintf("%s/%s/%s", key.Source, key.Type, key.Id))
    33  	if !ok {
    34  		return nil, fmt.Errorf("key not in cache")
    35  	}
    36  
    37  	return result.(*CacheData), nil
    38  }