-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclock.go
More file actions
65 lines (53 loc) · 1.58 KB
/
clock.go
File metadata and controls
65 lines (53 loc) · 1.58 KB
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
package main
import "time"
// Time is a custom interface to ensure we can test timestamp()
type Time interface {
Now() time.Time
Sub(time.Time) time.Duration
}
type realClock struct{}
func (realClock) Now() time.Time { return time.Now() }
func (c realClock) Sub(t time.Time) time.Duration { return c.Sub(t) }
type stuckClock struct {
sec int64
nsec int64
}
func (c stuckClock) Now() time.Time {
return time.Unix(c.sec, c.nsec)
}
func (c stuckClock) Sub(t time.Time) time.Duration {
when := time.Unix(c.sec, c.nsec)
return when.Sub(time.Unix(c.sec, c.nsec))
}
// StuckClock creates a new "stuck" clock, which starts at the given sec, nsec
// and always returns itself for any Sub() call
func StuckClock(sec, nsec int64) Time {
return stuckClock{sec: sec, nsec: nsec}
}
type monotonicClock struct {
sec int64
nsec int64
secIncrease int64
nsecIncrease int64
}
func (c *monotonicClock) Now() time.Time {
then := time.Unix(c.sec, c.nsec)
c.sec += c.secIncrease
c.nsec += c.nsecIncrease
for c.nsec > 1_000_000_000 {
c.sec++
c.nsec -= 1_000_000_000
}
return then
}
func (c monotonicClock) Sub(t time.Time) time.Duration {
when := time.Unix(c.sec, c.nsec)
return when.Sub(t)
}
// MonotonicClock creates a new "stuck" clock, which starts at the given sec,
// nsec and whenever Now() is called, it returns the last time incremented by
// the given delta seconds and nsec.
func MonotonicClock(sec, nsec, secIncrease, nsecIncrease int64) Time {
mc := monotonicClock{sec: sec, nsec: nsec, secIncrease: secIncrease, nsecIncrease: nsecIncrease}
return &mc
}