clock.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package dsig
  2. import (
  3. "time"
  4. "github.com/jonboulle/clockwork"
  5. )
  6. // Clock wraps a clockwork.Clock (which could be real or fake) in order
  7. // to default to a real clock when a nil *Clock is used. In other words,
  8. // if you attempt to use a nil *Clock it will defer to the real system
  9. // clock. This allows Clock to be easily added to structs with methods
  10. // that currently reference the time package, without requiring every
  11. // instantiation of that struct to be updated.
  12. type Clock struct {
  13. wrapped clockwork.Clock
  14. }
  15. func (c *Clock) getWrapped() clockwork.Clock {
  16. if c == nil {
  17. return clockwork.NewRealClock()
  18. }
  19. return c.wrapped
  20. }
  21. func (c *Clock) After(d time.Duration) <-chan time.Time {
  22. return c.getWrapped().After(d)
  23. }
  24. func (c *Clock) Sleep(d time.Duration) {
  25. c.getWrapped().Sleep(d)
  26. }
  27. func (c *Clock) Now() time.Time {
  28. return c.getWrapped().Now()
  29. }
  30. func NewRealClock() *Clock {
  31. return &Clock{
  32. wrapped: clockwork.NewRealClock(),
  33. }
  34. }
  35. func NewFakeClock(wrapped clockwork.Clock) *Clock {
  36. return &Clock{
  37. wrapped: wrapped,
  38. }
  39. }
  40. func NewFakeClockAt(t time.Time) *Clock {
  41. return &Clock{
  42. wrapped: clockwork.NewFakeClockAt(t),
  43. }
  44. }