-
Notifications
You must be signed in to change notification settings - Fork 2
/
reader.go
46 lines (42 loc) · 841 Bytes
/
reader.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
package ioshape
import (
"io"
"time"
)
// Reader is a traffic shaper struct that implements io.Reader interface. A
// Reader reads from R by B.
// Priority changes between 0(highest) and 15(lowest).
type Reader struct {
R io.Reader // underlying reader
B *Bucket // bucket
Pr int // priority
}
// Read reads from R by b.
func (rr *Reader) Read(p []byte) (n int, err error) {
if rr.B == nil {
n, err = rr.R.Read(p)
return
}
l := len(p)
m := l
for n < l && err == nil {
k := int(rr.B.getTokens(int64(m), rr.Pr))
if k <= 0 {
time.Sleep(time.Second / (freq * freqMul))
continue
}
var nn int
nn, err = rr.R.Read(p[n : n+k])
if nn < 0 || nn > k {
rr.B.giveTokens(int64(k))
err = ErrOutOfRange
continue
}
if nn != k {
rr.B.giveTokens(int64(k - nn))
}
n += nn
m -= nn
}
return
}