package clock import ( "sync" "time" ) type Clock interface { Now() time.Time MonotonicNS() uint64 } type Real struct{} func (Real) Now() time.Time { return time.Now() } func (Real) MonotonicNS() uint64 { return uint64(time.Now().UnixNano()) } type Fixed struct { T time.Time NS uint64 } func (f *Fixed) Now() time.Time { if f.T.IsZero() { return time.Unix(0, 0).UTC() } return f.T } func (f *Fixed) MonotonicNS() uint64 { return f.NS } // Fake is a monotonic test clock. Tests must Advance; do not time.Sleep. type Fake struct { mu sync.Mutex t time.Time ns uint64 } func NewFake(t time.Time) *Fake { if t.IsZero() { t = time.Unix(1, 0).UTC() } return &Fake{t: t, ns: uint64(t.UnixNano())} } func (f *Fake) Now() time.Time { f.mu.Lock() defer f.mu.Unlock() return f.t } func (f *Fake) MonotonicNS() uint64 { f.mu.Lock() defer f.mu.Unlock() return f.ns } func (f *Fake) Advance(d time.Duration) { f.mu.Lock() defer f.mu.Unlock() f.t = f.t.Add(d) if d > 0 { f.ns += uint64(d) } }