cacheinterface/driver/lru/lru.go
Tyler 28a5d131a6
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
Cleanup go.mod, document things better
2023-02-04 20:31:09 -05:00

68 lines
1.1 KiB
Go

package lru
import (
"github.com/hashicorp/golang-lru"
"meow.tf/go/cacheinterface/v2/driver/memory"
"meow.tf/go/cacheinterface/v2/encoder"
"time"
)
type Options struct {
Encoder encoder.Encoder `default:"msgpack"`
Size int `default:"128"`
}
type Cache struct {
options Options
c *lru.Cache
}
func New(options Options) (*Cache, error) {
c, err := lru.New(options.Size)
if err != nil {
return nil, err
}
return &Cache{
options: options,
c: c,
}, nil
}
func (mc *Cache) Has(key string) bool {
_, exists := mc.c.Get(key)
return exists
}
func (mc *Cache) Get(key string, dst any) error {
item, exists := mc.c.Get(key)
if !exists {
return memory.ErrNotExist
}
return memory.CacheGet(item, dst)
}
func (mc *Cache) GetBytes(key string) ([]byte, error) {
item, exists := mc.c.Get(key)
if !exists {
return nil, memory.ErrNotExist
}
return memory.CacheGetBytes(mc.options.Encoder, item)
}
func (mc *Cache) Set(key string, val any, ttl time.Duration) error {
mc.c.Add(key, val)
return nil
}
func (mc *Cache) Del(key string) error {
mc.c.Remove(key)
return nil
}