go.mway.dev/chrono@v0.6.1-0.20240126030049-189c5aef20d2/clock/monotonic_clock.go (about) 1 // Copyright (c) 2023 Matt Way 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to 5 // deal in the Software without restriction, including without limitation the 6 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 7 // sell copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 19 // IN THE THE SOFTWARE. 20 21 package clock 22 23 import ( 24 "time" 25 ) 26 27 var _ Clock = (*monotonicClock)(nil) 28 29 type monotonicClock struct { 30 fn NanotimeFunc 31 } 32 33 func newMonotonicClock(fn NanotimeFunc) *monotonicClock { 34 return &monotonicClock{ 35 fn: fn, 36 } 37 } 38 39 func (c *monotonicClock) After(d time.Duration) <-chan time.Time { 40 return time.After(d) 41 } 42 43 func (c *monotonicClock) AfterFunc(d time.Duration, fn func()) *Timer { 44 x := time.AfterFunc(d, fn) 45 return &Timer{ 46 C: x.C, 47 timer: x, 48 } 49 } 50 51 func (c *monotonicClock) Nanotime() int64 { 52 return c.fn() 53 } 54 55 func (c *monotonicClock) NewStopwatch() *Stopwatch { 56 return newStopwatch(c) 57 } 58 59 func (c *monotonicClock) NewTicker(d time.Duration) *Ticker { 60 x := time.NewTicker(d) 61 return &Ticker{ 62 C: x.C, 63 ticker: x, 64 } 65 } 66 67 func (c *monotonicClock) NewTimer(d time.Duration) *Timer { 68 timer := time.NewTimer(d) 69 return &Timer{ 70 C: timer.C, 71 timer: timer, 72 } 73 } 74 75 func (c *monotonicClock) Now() time.Time { 76 return time.Unix(0, c.fn()) 77 } 78 79 func (c *monotonicClock) Since(t time.Time) time.Duration { 80 return c.SinceNanotime(t.UnixNano()) 81 } 82 83 func (c *monotonicClock) SinceNanotime(ns int64) time.Duration { 84 return time.Duration(c.Nanotime() - ns) 85 } 86 87 func (c *monotonicClock) Sleep(d time.Duration) { 88 time.Sleep(d) 89 } 90 91 func (c *monotonicClock) Tick(d time.Duration) <-chan time.Time { 92 //nolint:staticcheck 93 return time.Tick(d) 94 }