|
| 1 | +package glock |
| 2 | + |
| 3 | +import ( |
| 4 | + "sync" |
| 5 | + "time" |
| 6 | +) |
| 7 | + |
| 8 | +type Advanceable interface { |
| 9 | + Advance(duration time.Duration) |
| 10 | + BlockingAdvance(duration time.Duration) |
| 11 | + SetCurrent(now time.Time) |
| 12 | +} |
| 13 | + |
| 14 | +// advanceable is the base type for mock clocks and tickers. This struct is |
| 15 | +// written to be used as as a mixin, where the containing struct can mutate |
| 16 | +// its internals (assuming correct coordination is used). |
| 17 | +// |
| 18 | +// An "advanceable" struct has a current time set of subscribers that may |
| 19 | +// change over time. The current time can be moved explicitly by the user. |
| 20 | +type advanceable struct { |
| 21 | + now time.Time |
| 22 | + subscribers []subscriber |
| 23 | + m *sync.Mutex |
| 24 | + cond *sync.Cond |
| 25 | +} |
| 26 | + |
| 27 | +type subscriber interface { |
| 28 | + // signal performs some behavior if the given current time is after a |
| 29 | + // deadline registered previously. This method should not block. If the |
| 30 | + // subscriber is still interested in being updated with the current |
| 31 | + // time, it should return true; the clock or timer instance will drop |
| 32 | + // a reference to this subscriber otherwise. |
| 33 | + signal(now time.Time) (requeue bool) |
| 34 | +} |
| 35 | + |
| 36 | +// newAdvanceableAt returns a new advanceable struct with the given current time. |
| 37 | +func newAdvanceableAt(now time.Time) *advanceable { |
| 38 | + m := &sync.Mutex{} |
| 39 | + |
| 40 | + return &advanceable{ |
| 41 | + now: now, |
| 42 | + m: m, |
| 43 | + cond: sync.NewCond(m), |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +// Advance will advance the clock's internal time by the given duration. |
| 48 | +func (a *advanceable) Advance(duration time.Duration) { |
| 49 | + a.m.Lock() |
| 50 | + a.setCurrent(a.now.Add(duration)) |
| 51 | + a.m.Unlock() |
| 52 | +} |
| 53 | + |
| 54 | +// SetCurrent sets the clock's internal time to the given time. |
| 55 | +func (a *advanceable) SetCurrent(now time.Time) { |
| 56 | + a.m.Lock() |
| 57 | + a.setCurrent(now) |
| 58 | + a.m.Unlock() |
| 59 | +} |
| 60 | + |
| 61 | +// setCurrent sets the new current time and invokes and filters the list of |
| 62 | +// subscribers. |
| 63 | +func (a *advanceable) setCurrent(now time.Time) { |
| 64 | + filtered := a.subscribers[:0] |
| 65 | + for _, e := range a.subscribers { |
| 66 | + if e.signal(now) { |
| 67 | + filtered = append(filtered, e) |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + a.now = now |
| 72 | + a.subscribers = filtered |
| 73 | + a.cond.Broadcast() |
| 74 | +} |
| 75 | + |
| 76 | +// register marks a subscriber to be updated when the current time changes. |
| 77 | +func (a *advanceable) register(subscriber subscriber) { |
| 78 | + a.subscribers = append(a.subscribers, subscriber) |
| 79 | + a.cond.Broadcast() |
| 80 | +} |
0 commit comments