Skip to content

Commit 1a27ee2

Browse files
committed
[refactoring] Move providers in a new file, add constructors
1 parent f34420d commit 1a27ee2

File tree

2 files changed

+35
-14
lines changed

2 files changed

+35
-14
lines changed

pkg/timer/provider.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package timer
2+
3+
import "time"
4+
5+
// A TimeProvider returns the current time.
6+
// This is usually the system time, but can be something else for unit tests.
7+
type TimeProvider func() time.Time
8+
9+
// SysTimeProvider is the default system time provider
10+
var SysTimeProvider = func() time.Time { return time.Now() }
11+
12+
// SleepConsumer sleeps the given amount of time.
13+
// This is usually the time.Sleep method, but can be something else for unit tests.
14+
type SleepConsumer func(time.Duration)
15+
16+
// SysSleepConsumer is the default system sleep consumer
17+
var SysSleepConsumer = func(d time.Duration) { time.Sleep(d) }
18+
19+
// NewFixedTimeProviderFromNanoSeconds creates a time provider from long nano seconds that always returns a fixed time
20+
func NewFixedTimeProviderFromNanoSeconds(timestamp int64) TimeProvider {
21+
sec := timestamp / 1e9
22+
nSec := (timestamp - sec) * 1e9
23+
return func() time.Time {
24+
return time.Unix(sec, nSec)
25+
}
26+
}
27+
28+
// NewFixedTimeProviderFromSeconds creates a time provider from floating point seconds that always returns a fixed time
29+
func NewFixedTimeProviderFromSeconds(timestamp float64) TimeProvider {
30+
sec := int64(timestamp)
31+
nSec := int64((timestamp - float64(sec)) * 1e9)
32+
return func() time.Time {
33+
return time.Unix(sec, nSec)
34+
}
35+
}

pkg/timer/timer.go

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,6 @@ import (
44
"time"
55
)
66

7-
// A TimeProvider returns the current time.
8-
// This is usually the system time, but can be something else for unit tests.
9-
type TimeProvider func() time.Time
10-
11-
// SysTimeProvider is the default system time provider
12-
var SysTimeProvider = func() time.Time { return time.Now() }
13-
14-
// SleepConsumer sleeps the given amount of time.
15-
// This is usually the time.Sleep method, but can be something else for unit tests.
16-
type SleepConsumer func(time.Duration)
17-
18-
// SysSleepConsumer is the default system sleep consumer
19-
var SysSleepConsumer = func(d time.Duration) { time.Sleep(d) }
20-
217
// A Timer can be started and stopped. It will start at zero and count up, while running.
228
// It is event driven, there are now threads that update any state.
239
type Timer struct {

0 commit comments

Comments
 (0)