clock.go 800 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package gcache
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. type Clock interface {
  7. Now() time.Time
  8. }
  9. type RealClock struct{}
  10. func NewRealClock() Clock {
  11. return RealClock{}
  12. }
  13. func (rc RealClock) Now() time.Time {
  14. t := time.Now()
  15. return t
  16. }
  17. type FakeClock interface {
  18. Clock
  19. Advance(d time.Duration)
  20. }
  21. func NewFakeClock() FakeClock {
  22. return &fakeclock{
  23. // Taken from github.com/jonboulle/clockwork: use a fixture that does not fulfill Time.IsZero()
  24. now: time.Date(1984, time.April, 4, 0, 0, 0, 0, time.UTC),
  25. }
  26. }
  27. type fakeclock struct {
  28. now time.Time
  29. mutex sync.RWMutex
  30. }
  31. func (fc *fakeclock) Now() time.Time {
  32. fc.mutex.RLock()
  33. defer fc.mutex.RUnlock()
  34. t := fc.now
  35. return t
  36. }
  37. func (fc *fakeclock) Advance(d time.Duration) {
  38. fc.mutex.Lock()
  39. defer fc.mutex.Unlock()
  40. fc.now = fc.now.Add(d)
  41. }