2025-04-21 11:07:53 -05:00
|
|
|
package ezcache
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"errors"
|
|
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type ezc[K comparable, V any] struct {
|
|
|
|
|
fetch Fetcher[K, V]
|
|
|
|
|
exp time.Duration
|
|
|
|
|
cache map[K]V
|
|
|
|
|
setTime map[K]time.Time
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func New[K comparable, V any](fetcher Fetcher[K, V], exp time.Duration) (Cache[K, V], error) {
|
|
|
|
|
c := &ezc[K, V]{}
|
|
|
|
|
err := c.SetFetcher(fetcher)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
err = c.SetExpiry(exp)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c.cache = make(map[K]V)
|
|
|
|
|
c.setTime = make(map[K]time.Time)
|
|
|
|
|
return c, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var errUnimpl = errors.New("unimplemented")
|
|
|
|
|
|
|
|
|
|
func (c *ezc[K, V]) Get(key K) (V, error) {
|
|
|
|
|
var val V
|
|
|
|
|
return val, errUnimpl
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (c *ezc[K, V]) SetFetcher(f Fetcher[K, V]) error {
|
|
|
|
|
if f == nil {
|
|
|
|
|
return ErrInvalidFetcher
|
|
|
|
|
}
|
|
|
|
|
c.fetch = f
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (c *ezc[K, V]) SetExpiry(exp time.Duration) error {
|
|
|
|
|
if exp <= 0 {
|
2025-04-21 11:24:51 -05:00
|
|
|
return ErrInvalidExpiry
|
2025-04-21 11:07:53 -05:00
|
|
|
}
|
|
|
|
|
c.exp = exp
|
|
|
|
|
return nil
|
|
|
|
|
}
|