File: clock.go

package info (click to toggle)
golang-github-bep-clocks 0.5.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 92 kB
  • sloc: makefile: 2
file content (103 lines) | stat: -rw-r--r-- 2,420 bytes parent folder | download
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
package clocks

import (
	"time"
)

// TimeCupFinalNorway1976 is the start time in UTC for the final match of the 1976 Norwegian Football Cup.
// This is typically used in tests where you need a historic time with a special meaning.
var TimeCupFinalNorway1976 = time.Date(1976, time.October, 24, 12, 15, 2, 127686412, time.UTC)

// Clock provides the sub set of methods in time.Time that this package provides.
type Clock interface {
	Now() time.Time
	Since(t time.Time) time.Duration
	Until(t time.Time) time.Duration

	// Offset returns the offset of this clock relative to the system clock.
	Offset() time.Duration
}

// Start creates a new Clock starting at t.
func Start(t time.Time) Clock {
	return &clock{
		offset: t.Sub(time.Now()),
	}
}

type clock struct {
	offset time.Duration
}

// Now returns the current time relative to the configured start time.
func (c *clock) Now() time.Time {
	return time.Now().Add(c.offset)
}

// Since returns the time elapsed since t.
func (c *clock) Since(t time.Time) time.Duration {
	return c.Now().Sub(t)
}

// Until returns the duration until t.
func (c *clock) Until(t time.Time) time.Duration {
	return t.Sub(c.Now())
}

// Offset returns the offset of this clock relative to the system clock.
// This can be used to convert to/from system time.
func (c *clock) Offset() time.Duration {
	return c.offset
}

var goClock = &systemClock{}

// System is a Clock that uses the system clock, meaning it just delegates to time.Now() etc.
func System() Clock {
	return goClock
}

type systemClock struct{}

func (c *systemClock) Now() time.Time {
	return time.Now()
}

func (c *systemClock) Since(t time.Time) time.Duration {
	return time.Since(t)
}

func (c *systemClock) Until(t time.Time) time.Duration {
	return time.Until(t)
}

func (c *systemClock) Offset() time.Duration {
	return 0
}

// Fixed returns a Clock that always returns the given time.
func Fixed(t time.Time) Clock {
	return &fixedClock{t: t}
}

// fixedClock is a Clock that always returns the same time.
type fixedClock struct {
	t time.Time
}

func (c *fixedClock) Now() time.Time {
	return c.t
}

func (c *fixedClock) Since(t time.Time) time.Duration {
	return c.Now().Sub(t)
}

func (c *fixedClock) Until(t time.Time) time.Duration {
	return t.Sub(c.Now())
}

// Offset returns the offset of this clock relative to the system clock.
func (c *fixedClock) Offset() time.Duration {
	return time.Since(c.t)
}