mclock.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package mclock is a wrapper for a monotonic clock source
  17. package mclock
  18. import (
  19. "time"
  20. "github.com/aristanetworks/goarista/monotime"
  21. )
  22. // AbsTime represents absolute monotonic time.
  23. type AbsTime time.Duration
  24. // Now returns the current absolute monotonic time.
  25. func Now() AbsTime {
  26. return AbsTime(monotime.Now())
  27. }
  28. // Add returns t + d.
  29. func (t AbsTime) Add(d time.Duration) AbsTime {
  30. return t + AbsTime(d)
  31. }
  32. // Clock interface makes it possible to replace the monotonic system clock with
  33. // a simulated clock.
  34. type Clock interface {
  35. Now() AbsTime
  36. Sleep(time.Duration)
  37. After(time.Duration) <-chan time.Time
  38. AfterFunc(d time.Duration, f func()) Event
  39. }
  40. // Event represents a cancellable event returned by AfterFunc
  41. type Event interface {
  42. Cancel() bool
  43. }
  44. // System implements Clock using the system clock.
  45. type System struct{}
  46. // Now implements Clock.
  47. func (System) Now() AbsTime {
  48. return AbsTime(monotime.Now())
  49. }
  50. // Sleep implements Clock.
  51. func (System) Sleep(d time.Duration) {
  52. time.Sleep(d)
  53. }
  54. // After implements Clock.
  55. func (System) After(d time.Duration) <-chan time.Time {
  56. return time.After(d)
  57. }
  58. // AfterFunc implements Clock.
  59. func (System) AfterFunc(d time.Duration, f func()) Event {
  60. return (*SystemEvent)(time.AfterFunc(d, f))
  61. }
  62. // SystemEvent implements Event using time.Timer.
  63. type SystemEvent time.Timer
  64. // Cancel implements Event.
  65. func (e *SystemEvent) Cancel() bool {
  66. return (*time.Timer)(e).Stop()
  67. }