2023-01-27 21:37:20 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2020-03-19 00:37:15 +00:00
|
|
|
|
2020-04-29 02:56:11 +00:00
|
|
|
package tstest
|
2020-03-19 00:37:15 +00:00
|
|
|
|
2020-03-27 10:05:25 +00:00
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
2020-03-19 00:37:15 +00:00
|
|
|
|
|
|
|
// Clock is a testing clock that advances every time its Now method is
|
|
|
|
// called, beginning at Start.
|
|
|
|
//
|
|
|
|
// The zero value starts virtual time at an arbitrary value recorded
|
2020-03-27 07:38:11 +00:00
|
|
|
// in Start on the first call to Now, and time never advances.
|
2020-03-19 00:37:15 +00:00
|
|
|
type Clock struct {
|
|
|
|
// Start is the first value returned by Now.
|
|
|
|
Start time.Time
|
|
|
|
// Step is how much to advance with each Now call.
|
|
|
|
Step time.Duration
|
|
|
|
// Present is the time that the next Now call will receive.
|
|
|
|
Present time.Time
|
2020-03-27 10:05:25 +00:00
|
|
|
|
|
|
|
sync.Mutex
|
2020-03-19 00:37:15 +00:00
|
|
|
}
|
|
|
|
|
2022-09-25 18:29:55 +00:00
|
|
|
// Now returns the virtual clock's current time, and advances it
|
2020-03-19 00:37:15 +00:00
|
|
|
// according to its step configuration.
|
|
|
|
func (c *Clock) Now() time.Time {
|
2020-03-27 10:05:25 +00:00
|
|
|
c.Lock()
|
|
|
|
defer c.Unlock()
|
2020-07-11 05:16:36 +00:00
|
|
|
c.initLocked()
|
|
|
|
step := c.Step
|
|
|
|
ret := c.Present
|
|
|
|
c.Present = c.Present.Add(step)
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Clock) Advance(d time.Duration) {
|
|
|
|
c.Lock()
|
|
|
|
defer c.Unlock()
|
|
|
|
c.initLocked()
|
|
|
|
c.Present = c.Present.Add(d)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Clock) initLocked() {
|
2020-03-19 00:37:15 +00:00
|
|
|
if c.Start.IsZero() {
|
|
|
|
c.Start = time.Now()
|
2020-04-17 20:19:41 +00:00
|
|
|
}
|
|
|
|
if c.Present.Before(c.Start) {
|
2020-03-19 00:37:15 +00:00
|
|
|
c.Present = c.Start
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reset rewinds the virtual clock to its start time.
|
|
|
|
func (c *Clock) Reset() {
|
2020-03-27 10:05:25 +00:00
|
|
|
c.Lock()
|
|
|
|
defer c.Unlock()
|
2020-03-19 00:37:15 +00:00
|
|
|
c.Present = c.Start
|
|
|
|
}
|