forked from lesismal/nbio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer_heap.go
62 lines (52 loc) · 1.12 KB
/
timer_heap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright 2020 lesismal. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package nbio
import (
"math"
"time"
)
const (
timeForever = time.Duration(math.MaxInt64)
)
// Timer type for export.
type Timer struct {
*htimer
}
// heap timer item.
type htimer struct {
index int
expire time.Time
f func()
parent *Gopher
}
// cancel timer.
func (it *htimer) Stop() {
it.parent.removeTimer(it)
}
// reset timer.
func (it *htimer) Reset(timeout time.Duration) {
it.expire = time.Now().Add(timeout)
it.parent.resetTimer(it)
}
type timerHeap []*htimer
func (h timerHeap) Len() int { return len(h) }
func (h timerHeap) Less(i, j int) bool { return h[i].expire.Before(h[j].expire) }
func (h timerHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
h[i].index = i
h[j].index = j
}
func (h *timerHeap) Push(x interface{}) {
*h = append(*h, x.(*htimer))
n := len(*h)
(*h)[n-1].index = n - 1
}
func (h *timerHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
old[n-1] = nil // avoid memory leak
*h = old[0 : n-1]
return x
}