/
forwardonly.go
64 lines (59 loc) · 1.33 KB
/
forwardonly.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package clock
import (
"sync"
"sync/atomic"
"time"
)
// NewForwardOnlyClock clock that starts at init unix time and will go forward reference clock.
//
// Use zero if initUnixTime is negative integer, else use 'referenceClock()'.
//
// Use 'NewSystemClock()' if referenceClock is nil.
func NewForwardOnlyClock(initUnixTime int64, referenceClock Clock) Clock {
if referenceClock == nil {
referenceClock = NewSystemClock()
}
now := referenceClock()
if initUnixTime < 0 {
if now < 0 {
initUnixTime = 0
} else {
initUnixTime = now
}
}
clock := &forwardOnlyClock{current: initUnixTime, refClock: referenceClock}
offset := now - initUnixTime
if offset > 0 {
clock.offset = offset
}
clock.run()
return clock.Clock()
}
type forwardOnlyClock struct {
current int64
offset int64
refClock Clock
once sync.Once
}
func (c *forwardOnlyClock) Clock() Clock {
return func() int64 {
return c.current + c.offset
}
}
func (c *forwardOnlyClock) run() {
c.once.Do(func() {
go func() {
for {
<-time.After(time.Second)
atomic.AddInt64(&c.current, 1)
go func() {
lastOffset := atomic.LoadInt64(&c.offset)
currentOffset := c.refClock() - atomic.LoadInt64(&c.current)
if currentOffset > lastOffset {
atomic.CompareAndSwapInt64(&c.offset, lastOffset, currentOffset)
}
}()
}
}()
})
}