| 1 | package chronos |
| 2 | |
| 3 | import "time" |
| 4 | |
| 5 | // Clock is the injectable-time seam: it provides the current time and |
| 6 | // creates timers, so callers can substitute a fake clock in tests. |
| 7 | type Clock interface { |
| 8 | // Now returns the current time. |
| 9 | Now() time.Time |
| 10 | // NewTimer returns a [Timer] that fires once after d. |
| 11 | NewTimer(d time.Duration) Timer |
| 12 | } |
| 13 | |
| 14 | // Timer is a single-shot timer created by a [Clock]. |
| 15 | type Timer interface { |
| 16 | // C returns the channel on which the fire time is delivered. |
| 17 | C() <-chan time.Time |
| 18 | // Stop prevents the timer from firing. It reports whether the call |
| 19 | // stops the timer (false if it has already fired or been stopped). |
| 20 | Stop() bool |
| 21 | } |
| 22 | |
| 23 | // realClock is a [Clock] backed by the standard library wall clock. |
| 24 | type realClock struct{} |
| 25 | |
| 26 | // defaultClock is the package default [Clock] backed by [time]. |
| 27 | var defaultClock = realClock{} |
| 28 | |
| 29 | // Now returns the current wall-clock time. |
| 30 | func (realClock) Now() time.Time { return time.Now() } |
| 31 | |
| 32 | // NewTimer returns a [Timer] wrapping [time.NewTimer]. |
| 33 | func (realClock) NewTimer(d time.Duration) Timer { |
| 34 | return realTimer{t: time.NewTimer(d)} |
| 35 | } |
| 36 | |
| 37 | // realTimer adapts a [*time.Timer] to the [Timer] interface. |
| 38 | type realTimer struct { |
| 39 | t *time.Timer |
| 40 | } |
| 41 | |
| 42 | // C returns the underlying timer's channel. |
| 43 | func (r realTimer) C() <-chan time.Time { return r.t.C } |
| 44 | |
| 45 | // Stop stops the underlying timer. |
| 46 | func (r realTimer) Stop() bool { return r.t.Stop() } |
| 47 | |