forked from BorisBorshevsky/timemock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimemock.go
79 lines (66 loc) · 1.34 KB
/
timemock.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package timemock
import (
"sync"
"sync/atomic"
"time"
)
type timemockClock struct {
rw *sync.RWMutex
frozen atomic.Bool
traveled atomic.Bool
freezeTime time.Time
travelTime time.Time
scale float64
}
func (c *timemockClock) Scale(scale float64) {
c.rw.Lock()
defer c.rw.Unlock()
c.scale = scale
if !c.traveled.Load() {
now := time.Now()
c.freezeTime = now
c.travelTime = now
c.traveled.Store(true)
}
}
func (c *timemockClock) Now() time.Time {
// fast path
if !c.frozen.Load() && !c.traveled.Load() {
return time.Now()
}
c.rw.RLock()
defer c.rw.RUnlock()
if c.frozen.Load() {
return c.freezeTime
}
if c.traveled.Load() {
return c.freezeTime.Add(time.Duration(float64(time.Since(c.travelTime)) * c.scale))
}
return time.Now()
}
func (c *timemockClock) Freeze(t time.Time) {
c.rw.Lock()
defer c.rw.Unlock()
c.freezeTime = t
c.frozen.Store(true)
}
func (c *timemockClock) Travel(t time.Time) {
c.rw.Lock()
defer c.rw.Unlock()
c.freezeTime = t
c.travelTime = time.Now()
c.traveled.Store(true)
}
func (c *timemockClock) Since(t time.Time) time.Duration {
return c.Now().Sub(t)
}
func (c *timemockClock) Until(t time.Time) time.Duration {
return t.Sub(c.Now())
}
func (c *timemockClock) Return() {
c.rw.Lock()
defer c.rw.Unlock()
c.frozen.Store(false)
c.traveled.Store(false)
c.scale = 1
}