Skip to content

Commit

Permalink
chore: add the timeSource interface
Browse files Browse the repository at this point in the history
  • Loading branch information
maypok86 committed Oct 2, 2024
1 parent 920138a commit 8e51668
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 9 deletions.
10 changes: 8 additions & 2 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ type expiryPolicy[K comparable, V any] interface {
Clear()
}

type timeSource interface {
Init()
Offset() int64
Time(offset int64) time.Time
}

// Cache is a structure performs a best-effort bounding of a hash table using eviction algorithm
// to determine which entries to evict when the capacity is exceeded.
type Cache[K comparable, V any] struct {
Expand All @@ -72,7 +78,7 @@ type Cache[K comparable, V any] struct {
expiryPolicy expiryPolicy[K, V]
stats statsRecorder
logger Logger
clock *clock.Clock
clock timeSource
stripedBuffer *lossy.Striped[K, V]
writeBuffer *queue.Growable[task[K, V]]
singleflight *group[K, V]
Expand Down Expand Up @@ -123,7 +129,7 @@ func newCache[K comparable, V any](b *Builder[K, V]) *Cache[K, V] {
doneClose: make(chan struct{}, 1),
weigher: b.getWeigher(),
onDeletion: b.onDeletion,
clock: &clock.Clock{},
clock: &clock.Real{},
}

if _, ok := b.statsRecorder.(noopStatsRecorder); ok {
Expand Down
8 changes: 4 additions & 4 deletions internal/clock/clock.go → internal/clock/real.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ import (
"time"
)

type Clock struct {
type Real struct {
start time.Time
initMutex sync.Mutex
isInitialized atomic.Bool
}

func (c *Clock) Init() {
func (c *Real) Init() {
if !c.isInitialized.Load() {
c.initMutex.Lock()
if !c.isInitialized.Load() {
Expand All @@ -37,13 +37,13 @@ func (c *Clock) Init() {
}
}

func (c *Clock) Offset() int64 {
func (c *Real) Offset() int64 {
if !c.isInitialized.Load() {
return 0
}
return time.Since(c.start).Nanoseconds()
}

func (c *Clock) Time(offset int64) time.Time {
func (c *Real) Time(offset int64) time.Time {
return c.start.Add(time.Duration(offset))
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,12 @@ func BenchmarkNanotime(b *testing.B) {
})
}

func BenchmarkClock(b *testing.B) {
func BenchmarkReal(b *testing.B) {
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
var ts int64
c := New()
c := &Real{}
c.Init()
for pb.Next() {
ts += c.Offset()
}
Expand Down
3 changes: 2 additions & 1 deletion internal/clock/clock_test.go → internal/clock/real_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ import (
)

func TestNow(t *testing.T) {
c := New()
c := &Real{}
c.Init()

got := c.Offset() / 1e9
if got != 0 {
Expand Down

0 comments on commit 8e51668

Please sign in to comment.