-
Notifications
You must be signed in to change notification settings - Fork 2
/
read.go
112 lines (88 loc) · 2.08 KB
/
read.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package sharpshooter
import (
"time"
)
func (s *Sniper) Read(b []byte) (n int, err error) {
var closeRet bool
var tick *time.Ticker
defer func() {
if tick != nil {
tick.Stop()
}
}()
if len(b) == 0 {
return 0, nil
}
loop:
now := time.Now()
if (!s.readDeadline.IsZero() && s.readDeadline.Before(now)) || (!s.deadline.IsZero() && s.deadline.Before(now)) {
return 0, TIMEOUERROR
}
n += s.copyRcvBuffer(b)
if n <= 0 {
recheck:
if !s.readDeadline.IsZero() || !s.deadline.IsZero() {
var remainTime int64
switch {
case s.readDeadline.IsZero():
remainTime = s.deadline.UnixNano() - time.Now().UnixNano()
case s.deadline.IsZero():
remainTime = s.readDeadline.UnixNano() - time.Now().UnixNano()
default:
if s.readDeadline.After(s.deadline) {
remainTime = s.deadline.UnixNano() - time.Now().UnixNano()
} else {
remainTime = s.readDeadline.UnixNano() - time.Now().UnixNano()
}
}
if remainTime <= 0 {
remainTime = 1
}
if tick == nil {
tick = time.NewTicker(time.Duration(remainTime) * time.Nanosecond)
} else {
tick.Reset(time.Duration(remainTime) * time.Nanosecond)
}
}
if tick != nil {
select {
case _, ok := <-s.readBlock:
if !ok {
return 0, CLOSEERROR
}
goto loop
case _, _ = <-s.closeChan:
if closeRet {
return 0, CLOSEERROR
}
closeRet = true
goto loop
case <-s.errorSign:
return 0, s.errorContainer.Load().(error)
case <-tick.C:
now := time.Now()
if (!s.readDeadline.IsZero() && s.readDeadline.Before(now)) || (s.deadline.Before(now) && !s.deadline.IsZero()) {
return 0, TIMEOUERROR
}
}
} else {
select {
case _, ok := <-s.readBlock:
if !ok {
return 0, CLOSEERROR
}
goto loop
case _, _ = <-s.closeChan:
if closeRet {
return 0, CLOSEERROR
}
closeRet = true
goto loop
case <-s.errorSign:
return 0, s.errorContainer.Load().(error)
}
}
goto recheck
}
return
}