forked from ckousik/go-libp2p
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deadline.go
77 lines (67 loc) · 1.18 KB
/
deadline.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package libp2pwebrtc
import (
"sync"
"time"
)
type deadline struct {
m sync.Mutex
timer *time.Timer
closeChan chan struct{}
}
func newDeadline() *deadline {
return &deadline{
timer: nil,
closeChan: make(chan struct{}),
}
}
func (d *deadline) set(t time.Time) {
d.m.Lock()
defer d.m.Unlock()
// if an existing timer is set, stop the timer
// from firing and drain the channel
if d.timer != nil {
if !d.timer.Stop() {
<-d.closeChan
}
}
// remove reference to existing stopped timer
// so it can be GC'd
d.timer = nil
closed := isClosed(d.closeChan)
// no deadline
if t.IsZero() {
if closed {
d.closeChan = make(chan struct{})
}
return
}
if duration := time.Until(t); duration < 0 {
if !closed {
close(d.closeChan)
}
} else {
if closed {
d.closeChan = make(chan struct{})
}
d.timer = time.AfterFunc(duration, func() {
// check to ensure channel is not closed
// twice
select {
case <-d.closeChan:
default:
close(d.closeChan)
}
})
}
}
func (d *deadline) wait() <-chan struct{} {
return d.closeChan
}
func isClosed(c <-chan struct{}) bool {
select {
case <-c:
return true
default:
}
return false
}