| 1 |
package mint |
| 2 |
|
| 3 |
import ( |
| 4 |
"time" |
| 5 |
) |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
type timerCb func() error |
| 12 |
|
| 13 |
type timer struct { |
| 14 |
label string |
| 15 |
cb timerCb |
| 16 |
deadline time.Time |
| 17 |
duration uint32 |
| 18 |
} |
| 19 |
|
| 20 |
type timerSet struct { |
| 21 |
ts []*timer |
| 22 |
} |
| 23 |
|
| 24 |
func newTimerSet() *timerSet { |
| 25 |
return &timerSet{} |
| 26 |
} |
| 27 |
|
| 28 |
func (ts *timerSet) start(label string, cb timerCb, delayMs uint32) *timer { |
| 29 |
now := time.Now() |
| 30 |
t := timer{ |
| 31 |
label, |
| 32 |
cb, |
| 33 |
now.Add(time.Millisecond * time.Duration(delayMs)), |
| 34 |
delayMs, |
| 35 |
} |
| 36 |
logf(logTypeHandshake, "Timer %s set [%v -> %v]", t.label, now, t.deadline) |
| 37 |
|
| 38 |
var i int |
| 39 |
ntimers := len(ts.ts) |
| 40 |
for i = 0; i < ntimers; i++ { |
| 41 |
if t.deadline.Before(ts.ts[i].deadline) { |
| 42 |
break |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
tmp := make([]*timer, 0, ntimers+1) |
| 47 |
tmp = append(tmp, ts.ts[:i]...) |
| 48 |
tmp = append(tmp, &t) |
| 49 |
tmp = append(tmp, ts.ts[i:]...) |
| 50 |
ts.ts = tmp |
| 51 |
|
| 52 |
return &t |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
func (ts *timerSet) check(now time.Time) error { |
| 59 |
for i, t := range ts.ts { |
| 60 |
if now.After(t.deadline) { |
| 61 |
ts.ts = append(ts.ts[:i], ts.ts[:i+1]...) |
| 62 |
if t.cb != nil { |
| 63 |
logf(logTypeHandshake, "Timer %s expired [%v > %v]", t.label, now, t.deadline) |
| 64 |
cb := t.cb |
| 65 |
t.cb = nil |
| 66 |
err := cb() |
| 67 |
if err != nil { |
| 68 |
return err |
| 69 |
} |
| 70 |
} |
| 71 |
} else { |
| 72 |
break |
| 73 |
} |
| 74 |
} |
| 75 |
return nil |
| 76 |
} |
| 77 |
|
| 78 |
|
| 79 |
func (ts *timerSet) remaining() (bool, time.Duration) { |
| 80 |
for _, t := range ts.ts { |
| 81 |
if t.cb != nil { |
| 82 |
return true, time.Until(t.deadline) |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
return false, time.Duration(0) |
| 87 |
} |
| 88 |
|
| 89 |
func (ts *timerSet) cancel(label string) { |
| 90 |
for _, t := range ts.ts { |
| 91 |
if t.label == label { |
| 92 |
t.cancel() |
| 93 |
} |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
func (ts *timerSet) getTimer(label string) *timer { |
| 98 |
for _, t := range ts.ts { |
| 99 |
if t.label == label && t.cb != nil { |
| 100 |
return t |
| 101 |
} |
| 102 |
} |
| 103 |
return nil |
| 104 |
} |
| 105 |
|
| 106 |
func (ts *timerSet) getAllTimers() []string { |
| 107 |
var ret []string |
| 108 |
|
| 109 |
for _, t := range ts.ts { |
| 110 |
if t.cb != nil { |
| 111 |
ret = append(ret, t.label) |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
return ret |
| 116 |
} |
| 117 |
|
| 118 |
func (t *timer) cancel() { |
| 119 |
logf(logTypeHandshake, "Timer %s cancelled", t.label) |
| 120 |
t.cb = nil |
| 121 |
t.label = "" |
| 122 |
} |