forked from StefanKopieczek/gossip
-
Notifications
You must be signed in to change notification settings - Fork 1
/
timing.go
193 lines (164 loc) · 4.8 KB
/
timing.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package timing
import "time"
// Controls whether library calls should be mocked, or whether we should use the standard Go time library.
// If we're in Mock Mode, then time does not pass as normal, but only progresses when Elapse is called.
// False by default, indicating that we just call through to standard Go functions.
var MockMode bool = false
var currentTimeMock time.Time = time.Unix(0, 0)
var mockTimers []*mockTimer = make([]*mockTimer, 0)
// Interface over Golang's built-in Timers, allowing them to be swapped out for mocked timers.
type Timer interface {
// Returns a channel which sends the current time immediately when the timer expires.
// Equivalent to time.Timer.C; however, we have to use a method here instead of a member since this is an interface.
C() <-chan time.Time
// Resets the timer such that it will expire in duration 'd' after the current time.
// Returns true if the timer had been active, and false if it had expired or been stopped.
Reset(d time.Duration) bool
// Stops the timer, preventing it from firing.
// Returns true if the timer had been active, and false if it had expired or been stopped.
Stop() bool
}
// Implementation of Timer that just wraps time.Timer.
type realTimer struct {
*time.Timer
}
func (t *realTimer) C() <-chan time.Time {
return t.Timer.C
}
func (t *realTimer) Reset(d time.Duration) bool {
return t.Timer.Reset(d)
}
func (t *realTimer) Stop() bool {
return t.Timer.Stop()
}
// Implementation of Timer that mocks time.Timer, firing when the total elapsed time (as controlled by Elapse)
// exceeds the duration specified when the timer was constructed.
type mockTimer struct {
EndTime time.Time
Chan chan time.Time
fired bool
toRun func()
}
func (t *mockTimer) C() <-chan time.Time {
return t.Chan
}
func (t *mockTimer) Reset(d time.Duration) bool {
wasActive := removeMockTimer(t)
t.EndTime = currentTimeMock.Add(d)
if d > 0 {
mockTimers = append(mockTimers, t)
} else {
// The new timer has an expiry time of 0.
// Fire it right away, and don't bother tracking it.
t.Chan <- currentTimeMock
}
return wasActive
}
func (t *mockTimer) Stop() bool {
return removeMockTimer(t)
}
// Creates a new Timer; either a wrapper around a standard Go time.Timer, or a mocked-out Timer,
// depending on whether MockMode is set.
func NewTimer(d time.Duration) Timer {
if MockMode {
t := mockTimer{currentTimeMock.Add(d), make(chan time.Time, 1), false, nil}
if d == 0 {
t.Chan <- currentTimeMock
} else {
mockTimers = append(mockTimers, &t)
}
return &t
} else {
return &realTimer{time.NewTimer(d)}
}
}
// See built-in time.After() function.
func After(d time.Duration) <-chan time.Time {
return NewTimer(d).C()
}
// See built-in time.AfterFunc() function.
func AfterFunc(d time.Duration, f func()) Timer {
if MockMode {
t := mockTimer{currentTimeMock.Add(d), make(chan time.Time, 1), false, f}
if d == 0 {
go f()
t.Chan <- currentTimeMock
} else {
mockTimers = append(mockTimers, &t)
}
return &t
} else {
return &realTimer{time.AfterFunc(d, f)}
}
}
// See built-in time.Sleep() function.
func Sleep(d time.Duration) {
<-After(d)
}
// Increment the current time by the given Duration.
// This function can only be called in Mock Mode, otherwise we will panic.
func Elapse(d time.Duration) {
requireMockMode()
currentTimeMock = currentTimeMock.Add(d)
// Fire any timers whose time has come up.
for _, t := range mockTimers {
t.fired = false
if !t.EndTime.After(currentTimeMock) {
if t.toRun != nil {
go t.toRun()
}
// Clear the channel if something is already in it.
select {
case <-t.Chan:
default:
}
t.Chan <- currentTimeMock
t.fired = true
}
}
// Stop tracking any fired timers.
remainingTimers := make([]*mockTimer, 0)
for _, t := range mockTimers {
if !t.fired {
remainingTimers = append(remainingTimers, t)
}
}
mockTimers = remainingTimers
}
// Returns the current time.
// If Mock Mode is set, this will be the sum of all Durations passed into Elapse calls;
// otherwise it will be the true system time.
func Now() time.Time {
if MockMode {
return currentTimeMock
} else {
return time.Now()
}
}
// Shortcut method to enforce that Mock Mode is enabled.
func requireMockMode() {
if !MockMode {
panic("This method requires MockMode to be enabled")
}
}
// Utility method to remove a mockTimer from the list of outstanding timers.
func removeMockTimer(t *mockTimer) bool {
// First, find the index of the timer in our list.
found := false
var idx int
var elt *mockTimer
for idx, elt = range mockTimers {
if elt == t {
found = true
break
}
}
if found {
// We found the given timer. Remove it.
mockTimers = append(mockTimers[:idx], mockTimers[idx+1:]...)
return true
} else {
// The timer was not present, indicating that it was already expired.
return false
}
}