clock.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package clock
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. type Clock interface {
  7. Now() time.Time
  8. MonotonicNS() uint64
  9. }
  10. type Real struct{}
  11. func (Real) Now() time.Time { return time.Now() }
  12. func (Real) MonotonicNS() uint64 {
  13. return uint64(time.Now().UnixNano())
  14. }
  15. type Fixed struct {
  16. T time.Time
  17. NS uint64
  18. }
  19. func (f *Fixed) Now() time.Time {
  20. if f.T.IsZero() {
  21. return time.Unix(0, 0).UTC()
  22. }
  23. return f.T
  24. }
  25. func (f *Fixed) MonotonicNS() uint64 { return f.NS }
  26. // Fake is a monotonic test clock. Tests must Advance; do not time.Sleep.
  27. type Fake struct {
  28. mu sync.Mutex
  29. t time.Time
  30. ns uint64
  31. }
  32. func NewFake(t time.Time) *Fake {
  33. if t.IsZero() {
  34. t = time.Unix(1, 0).UTC()
  35. }
  36. return &Fake{t: t, ns: uint64(t.UnixNano())}
  37. }
  38. func (f *Fake) Now() time.Time {
  39. f.mu.Lock()
  40. defer f.mu.Unlock()
  41. return f.t
  42. }
  43. func (f *Fake) MonotonicNS() uint64 {
  44. f.mu.Lock()
  45. defer f.mu.Unlock()
  46. return f.ns
  47. }
  48. func (f *Fake) Advance(d time.Duration) {
  49. f.mu.Lock()
  50. defer f.mu.Unlock()
  51. f.t = f.t.Add(d)
  52. if d > 0 {
  53. f.ns += uint64(d)
  54. }
  55. }