-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclock.go
99 lines (74 loc) · 1.64 KB
/
clock.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
package clocksteps
import (
"errors"
"sync"
"time"
"go.nhat.io/clock"
)
// ErrClockIsNotSet indicates that the clock must be set by either Clock.Set() or Clock.Freeze() before adding some
// time.Duration into it.
var ErrClockIsNotSet = errors.New("clock is not set")
var _ clock.Clock = (*Clock)(nil)
// Clock is a clock.Clock.
type Clock struct {
timestamp *time.Time
mu sync.Mutex
}
// Now returns a fixed timestamp or time.Now().
func (c *Clock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
if c.timestamp == nil {
return time.Now()
}
return *c.timestamp
}
// Set fixes the clock at a time.
func (c *Clock) Set(t time.Time) {
c.mu.Lock()
defer c.mu.Unlock()
c.timestamp = timestamp(t)
}
// Add adds time to the clock.
func (c *Clock) Add(d time.Duration) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.timestamp == nil {
return ErrClockIsNotSet
}
c.timestamp = timestamp(c.timestamp.Add(d))
return nil
}
// AddDate adds date to the clock.
func (c *Clock) AddDate(years, months, days int) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.timestamp == nil {
return ErrClockIsNotSet
}
c.timestamp = timestamp(c.timestamp.AddDate(years, months, days))
return nil
}
// Freeze freezes the clock.
func (c *Clock) Freeze() {
c.mu.Lock()
defer c.mu.Unlock()
c.timestamp = timestamp(time.Now())
}
// Unfreeze unfreezes the clock.
func (c *Clock) Unfreeze() {
c.mu.Lock()
defer c.mu.Unlock()
c.timestamp = nil
}
// Clock provides clock.Clock.
func (c *Clock) Clock() clock.Clock {
return c
}
// New initiates a new Clock.
func New() *Clock {
return &Clock{}
}
func timestamp(t time.Time) *time.Time {
return &t
}