mirror of
https://github.com/datarhei/core.git
synced 2025-10-05 07:57:13 +08:00
Replace timer-based SMA with a timer-less implementation
This commit is contained in:
@@ -4,38 +4,30 @@ import (
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
timesrc "github.com/datarhei/core/v16/time"
|
||||
)
|
||||
|
||||
type TimeSource interface {
|
||||
Now() time.Time
|
||||
}
|
||||
|
||||
type StdTimeSource struct{}
|
||||
|
||||
func (s *StdTimeSource) Now() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
type CacheEntry[T any] struct {
|
||||
value T
|
||||
validUntil time.Time
|
||||
}
|
||||
|
||||
type Cache[T any] struct {
|
||||
ts TimeSource
|
||||
ts timesrc.Source
|
||||
lock sync.Mutex
|
||||
entries map[string]CacheEntry[T]
|
||||
lastPurge time.Time
|
||||
}
|
||||
|
||||
func NewCache[T any](ts TimeSource) *Cache[T] {
|
||||
func NewCache[T any](ts timesrc.Source) *Cache[T] {
|
||||
c := &Cache[T]{
|
||||
ts: ts,
|
||||
entries: map[string]CacheEntry[T]{},
|
||||
}
|
||||
|
||||
if c.ts == nil {
|
||||
c.ts = &StdTimeSource{}
|
||||
c.ts = ×rc.StdSource{}
|
||||
}
|
||||
|
||||
c.lastPurge = c.ts.Now()
|
||||
|
Reference in New Issue
Block a user