-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstopwatch.go
270 lines (218 loc) · 4.88 KB
/
stopwatch.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package stopwatch
import (
"context"
"math"
"sync"
"time"
)
const (
start key = "start"
stop key = "stop"
)
const ctxStopwatch = "stopwatch"
type key string
func (k key) String() string {
return string(k)
}
type record struct {
ts int64
comment string
}
type entries map[key]record
type Split struct {
Name string
Comment string
Duration time.Duration
}
type Stopwatch struct {
Name string
Logger Logger
running bool
keys []key
records entries
rl *sync.Mutex
}
type Logger interface {
Log(timestamp int64, key string, comment string)
}
type nopLogger struct{}
func (l *nopLogger) Log(_ int64, _, _ string) {}
func New(name string, logger Logger) *Stopwatch {
if logger == nil {
logger = &nopLogger{}
}
return &Stopwatch{
Name: name,
Logger: logger,
keys: make([]key, 0),
records: make(map[key]record),
rl: &sync.Mutex{},
}
}
func (w *Stopwatch) Start() error {
if w.stopped() {
return NewAlreadyStoppedErr(w)
}
if w.started() {
return NewAlreadyStartedErr(w)
}
w.setRunning(true)
w.keys = append(w.keys, start)
startComment := ""
startRecord := newRecord(startComment)
w.records[start] = startRecord
w.Logger.Log(startRecord.ts, start.String(), startComment)
return nil
}
func (w *Stopwatch) Lap(lapKey, lapComment string) error {
if w.stopped() {
return NewAlreadyStoppedErr(w)
}
if !w.started() {
return NewNotStartedErr(w)
}
lk := newKey(lapKey)
w.keys = append(w.keys, key(lk))
w.records[lk] = newRecord(lapComment)
w.Logger.Log(time.Now().UTC().UnixNano(), lapKey, lapComment)
return nil
}
func (w *Stopwatch) Running() bool {
w.rl.Lock()
defer w.rl.Unlock()
return w.running
}
func (w *Stopwatch) Stop() error {
if w.stopped() {
return NewAlreadyStoppedErr(w)
}
if !w.started() {
return NewNotStartedErr(w)
}
w.setRunning(false)
w.keys = append(w.keys, stop)
stopComment := ""
stopRecord := newRecord(stopComment)
w.records[stop] = stopRecord
w.Logger.Log(stopRecord.ts, stop.String(), stopComment)
return nil
}
func (w *Stopwatch) Report() (Report, error) {
if !w.started() {
return Report{}, NewNotStartedErr(w)
}
if !w.stopped() {
return Report{}, NewNotStoppedErr(w)
}
duration, err := w.calculateDuration(start, stop)
if err != nil {
return Report{}, err
}
splits := w.calculateSplits()
rpt := Report{
Duration: duration,
Splits: splits,
}
return rpt, nil
}
func (w *Stopwatch) calculateSplits() []Split {
splits := make([]Split, len(w.keys)-1)
var splitStart, splitEnd key
for i := range splits {
splitStart, splitEnd = w.keys[i], w.keys[i+1]
splits[i] = w.calculateSplit(splitStart, splitEnd)
}
return splits
}
func (w *Stopwatch) calculateSplit(begin, end key) Split {
rec := w.records[begin]
dur, _ := w.calculateDuration(begin, end)
return newSplit(begin.String(), rec.comment, dur)
}
func newSplit(splitName string, splitComment string, dur time.Duration) Split {
return Split{
Name: splitName,
Comment: splitComment,
Duration: dur,
}
}
func (w *Stopwatch) calculateDuration(from, to key) (time.Duration, error) {
fromRecord, exists := w.records[from]
if !exists {
return time.Duration(0), NewNonExistentKeyErr(w, from)
}
toRecord, exists := w.records[to]
if !exists {
return time.Duration(0), NewNonExistentKeyErr(w, to)
}
dur := math.Abs(float64(fromRecord.ts - toRecord.ts))
return time.Duration(dur), nil
}
type Report struct {
Duration time.Duration
Splits []Split
}
func newRecord(comment string) record {
return record{
ts: time.Now().UTC().UnixNano(),
comment: comment,
}
}
func newKey(keyName string) key {
return key(keyName)
}
func (w *Stopwatch) setRunning(running bool) {
w.rl.Lock()
defer w.rl.Unlock()
w.running = running
}
func (w *Stopwatch) started() bool {
return len(w.keys) > 0 && w.keys[0] == start
}
func (w *Stopwatch) stopped() bool {
lastIdx := len(w.keys) - 1
return len(w.keys) > 0 && w.keys[lastIdx] == stop
}
//Context Stopwatch Handling
func CtxNew(ctx context.Context, name string, logger Logger) context.Context {
return context.WithValue(ctx, ctxStopwatch, New(name, logger))
}
func CtxStart(ctx context.Context) error {
w, err := getStopwatchFromCtx(ctx)
if err != nil {
return err
}
return w.Start()
}
func CtxStop(ctx context.Context) error {
w, err := getStopwatchFromCtx(ctx)
if err != nil {
return err
}
return w.Stop()
}
func CtxLap(ctx context.Context, lapKey, lapComment string) error {
w, err := getStopwatchFromCtx(ctx)
if err != nil {
return err
}
return w.Lap(lapKey, lapComment)
}
func CtxReport(ctx context.Context) (Report, error) {
w, err := getStopwatchFromCtx(ctx)
if err != nil {
return Report{}, err
}
return w.Report()
}
func getStopwatchFromCtx(ctx context.Context) (*Stopwatch, error) {
wi := ctx.Value(ctxStopwatch)
if wi == nil {
return nil, NewNotFoundErr()
}
w, ok := wi.(*Stopwatch)
if !ok {
return nil, NewBadValueErr(wi)
}
return w, nil
}