Skip to content

Commit

Permalink
fix ExpireNano overflow
Browse files Browse the repository at this point in the history
  • Loading branch information
Yiling-J committed Jan 12, 2025
1 parent 7e53110 commit ec0a517
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 1 deletion.
22 changes: 21 additions & 1 deletion internal/clock/clock.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package clock

import (
"math"
"sync/atomic"
"time"
)
Expand Down Expand Up @@ -28,9 +29,28 @@ func (c *Clock) SetNowCache(n int64) {
}

func (c *Clock) ExpireNano(ttl time.Duration) int64 {
return c.NowNano() + ttl.Nanoseconds()
// Both `ttl` and `nano + ttl` can overflow, but we only handle the overflow of `nano + ttl` here.
// An overflowed `ttl` can be either positive or negative. If it's positive, we won't detect it since it behaves
// like a regular `ttl`. Users of Theine should ensure that `ttl` does not overflow (this should be the case in most scenarios
// unless the value is directly manipulated via math operations).
// When `nano + ttl` overflows, we cap the returned expiration time at `math.MaxInt64`.
return saturatingAdd(c.NowNano(), ttl.Nanoseconds())
}

func (c *Clock) SetStart(ts int64) {
c.Start = time.Unix(0, ts)
}

func saturatingAdd(a, b int64) int64 {
var max int64 = math.MaxInt64
var min int64 = math.MinInt64
if b > 0 && a > max-b {
return max
}

if b < 0 && a < min-b {
return min
}

return a + b
}
59 changes: 59 additions & 0 deletions internal/clock/clock_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package clock_test

import (
"math"
"testing"
"time"

"github.com/Yiling-J/theine-go/internal/clock"
"github.com/stretchr/testify/require"
)

func TestClock_NowNano(t *testing.T) {
c := &clock.Clock{Start: time.Now()}
start := c.NowNano()
time.Sleep(5 * time.Millisecond)
end := c.NowNano()

require.Greater(t, end, start)
}

func TestClock_ExpireNano(t *testing.T) {
c := &clock.Clock{Start: time.Now()}
nano := c.NowNano()

ttl := 1 * time.Second
expireNano := c.ExpireNano(ttl)
lower := nano + ttl.Nanoseconds()
upper := c.NowNano() + ttl.Nanoseconds()
require.Greater(t, expireNano, lower)
require.Less(t, expireNano, upper)

overflowTTL := time.Duration(math.MaxInt64)
expireNano = c.ExpireNano(overflowTTL)
require.Equal(t, int64(math.MaxInt64), expireNano)

}

func TestClock_RefreshNowCache(t *testing.T) {
c := &clock.Clock{Start: time.Now()}
now := c.NowNanoCached()
time.Sleep(5 * time.Millisecond)
require.Equal(t, now, c.NowNanoCached())

c.RefreshNowCache()
require.NotEqual(t, c.NowNanoCached(), now)
}

func TestClock_SetNowCache(t *testing.T) {
c := &clock.Clock{}
c.SetNowCache(123456789)
require.Equal(t, int64(123456789), c.NowNanoCached())
}

func TestClock_SetStart(t *testing.T) {
c := &clock.Clock{}
ts := time.Now().UnixNano()
c.SetStart(ts)
require.Equal(t, ts, c.Start.UnixNano())
}

0 comments on commit ec0a517

Please sign in to comment.