-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclock.go
More file actions
109 lines (81 loc) · 1.86 KB
/
clock.go
File metadata and controls
109 lines (81 loc) · 1.86 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
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
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 {
timestamps []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 len(c.timestamps) == 0 {
return time.Now()
}
result := c.timestamps[0]
if len(c.timestamps) > 1 {
c.timestamps = c.timestamps[1:]
}
return result
}
// Set fixes the clock at a time.
func (c *Clock) Set(t time.Time) {
c.mu.Lock()
defer c.mu.Unlock()
c.timestamps = []time.Time{t}
}
// Next sets the next timestamps to be returned by Now().
func (c *Clock) Next(t ...time.Time) {
c.mu.Lock()
defer c.mu.Unlock()
c.timestamps = append(c.timestamps, t...)
}
// Add adds time to the clock.
func (c *Clock) Add(d time.Duration) error {
c.mu.Lock()
defer c.mu.Unlock()
if len(c.timestamps) == 0 {
return ErrClockIsNotSet
}
c.timestamps[0] = c.timestamps[0].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 len(c.timestamps) == 0 {
return ErrClockIsNotSet
}
c.timestamps[0] = c.timestamps[0].AddDate(years, months, days)
return nil
}
// Freeze freezes the clock.
func (c *Clock) Freeze() {
c.mu.Lock()
defer c.mu.Unlock()
c.timestamps = []time.Time{time.Now()}
}
// Unfreeze unfreezes the clock.
func (c *Clock) Unfreeze() {
c.mu.Lock()
defer c.mu.Unlock()
c.timestamps = nil
}
// Clock provides clock.Clock.
func (c *Clock) Clock() clock.Clock {
return c
}
// New initiates a new Clock.
func New() *Clock {
return &Clock{}
}